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
kropp/intellij-makefile
src/main/kotlin/name/kropp/intellij/makefile/MakefileRunConfigurationEditor.kt
1
4467
package name.kropp.intellij.makefile import com.intellij.execution.configuration.EnvironmentVariablesComponent import com.intellij.icons.AllIcons import com.intellij.openapi.application.PathMacros import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.* import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.psi.PsiManager import com.intellij.ui.* import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.util.ui.FormBuilder import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel import javax.swing.event.DocumentEvent class MakefileRunConfigurationEditor(private val project: Project) : SettingsEditor<MakefileRunConfiguration>() { private val filenameField = TextFieldWithBrowseButton() private val targetCompletionProvider = TextFieldWithAutoCompletion.StringsCompletionProvider(emptyList(), MakefileTargetIcon) private val targetField = TextFieldWithAutoCompletion<String>(project, targetCompletionProvider, true, "") private val argumentsField = ExpandableTextField() private val workingDirectoryField = TextFieldWithBrowseButton() private val environmentVarsComponent = EnvironmentVariablesComponent() private val panel: JPanel by lazy { FormBuilder.createFormBuilder() .setAlignLabelOnRight(false) .setHorizontalGap(UIUtil.DEFAULT_HGAP) .setVerticalGap(UIUtil.DEFAULT_VGAP) .addLabeledComponent("&Makefile", filenameField) .addLabeledComponent("&Targets", targetField) .addComponent(LabeledComponent.create(argumentsField, "&Arguments")) .addLabeledComponent("&Working Directory", createComponentWithMacroBrowse(workingDirectoryField)) .addComponent(environmentVarsComponent) .panel } init { filenameField.addBrowseFolderListener("Makefile", "Makefile path", project, MakefileFileChooserDescriptor()) filenameField.textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(event: DocumentEvent) { updateTargetCompletion(filenameField.text) } }) workingDirectoryField.addBrowseFolderListener("Choose Working Directory", "Choose Working Directory", project, FileChooserDescriptorFactory.createSingleFolderDescriptor()) } fun updateTargetCompletion(filename: String) { val file = LocalFileSystem.getInstance().findFileByPath(filename) if (file != null) { val psiFile = PsiManager.getInstance(project).findFile(file) if (psiFile != null) { targetCompletionProvider.setItems(name.kropp.intellij.makefile.findTargets(psiFile).map { it.name }) return } } targetCompletionProvider.setItems(emptyList()) } override fun createEditor() = panel override fun applyEditorTo(configuration: MakefileRunConfiguration) { configuration.filename = filenameField.text configuration.target = targetField.text configuration.workingDirectory = workingDirectoryField.text configuration.environmentVariables = environmentVarsComponent.envData configuration.arguments = argumentsField.text } override fun resetEditorFrom(configuration: MakefileRunConfiguration) { filenameField.text = configuration.filename targetField.text = configuration.target workingDirectoryField.text = configuration.workingDirectory environmentVarsComponent.envData = configuration.environmentVariables argumentsField.text = configuration.arguments updateTargetCompletion(configuration.filename) } // copied & converted to Kotlin from com.intellij.execution.ui.CommonProgramParametersPanel private fun createComponentWithMacroBrowse(textAccessor: TextFieldWithBrowseButton): JComponent { val button = FixedSizeButton(textAccessor) button.icon = AllIcons.Actions.ListFiles button.addActionListener { JBPopupFactory.getInstance().createPopupChooserBuilder(PathMacros.getInstance().userMacroNames.toList()).setItemChosenCallback { item: String -> textAccessor.text = "$$item$" }.setMovable(false).setResizable(false).createPopup().showUnderneathOf(button) } return JPanel(BorderLayout()).apply { add(textAccessor, BorderLayout.CENTER) add(button, BorderLayout.EAST) } } }
mit
8933f3579cd09ffd880fc03e33a91b90
43.237624
175
0.788225
5.414545
false
true
false
false
kantega/niagara
niagara-http/src/main/kotlin/org/kantega/niagara/http/responses.kt
1
1081
package org.kantega.niagara.http import io.vavr.collection.TreeMap import io.vavr.control.Option import org.kantega.niagara.data.appendIfMissing import java.io.InputStream val Ok = Response(TreeMap.empty(), TreeMap.empty(), 200, Option.none()) val NotFound = Ok.withStatusCode(404) fun Ok(body: String): Response { return Ok.withBody(body) } fun Ok(value: InputStream): Response { return Ok.withBody(value) } fun classPathResources(prefix: String): (Request) -> Response = { request -> val path = prefix.appendIfMissing("/")+request.remainingPath.mkString("/") val maybeInputStream = Option.of(Thread.currentThread().contextClassLoader.getResourceAsStream(path)) maybeInputStream.fold( { NotFound }, { inputStream -> Ok(inputStream) } ) } fun classPathResource(name: String): (Request) -> Response = { _ -> val maybeInputStream = Option.of(Thread.currentThread().contextClassLoader.getResourceAsStream(name)) maybeInputStream.fold( { NotFound }, { inputStream -> Ok(inputStream) } ) }
apache-2.0
3bab9c2324e5481861f8a2f65ed48339
21.541667
84
0.697502
4.06391
false
false
false
false
XanderWang/XanderPanel
xanderpanel/src/main/java/com/xander/panel/PanelController.kt
1
29158
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xander.panel import android.content.Context import android.graphics.drawable.Drawable import android.os.Build import android.util.Log import android.util.TypedValue import android.view.* import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.animation.TranslateAnimation import android.widget.* import android.widget.AdapterView.OnItemClickListener import android.widget.AdapterView.OnItemLongClickListener import androidx.core.view.isNotEmpty import androidx.viewpager.widget.ViewPager import com.viewpagerindicator.CirclePageIndicator import java.util.* class PanelController(private val mContext: Context, private val mXanderPanel: XanderPanel) : View.OnClickListener, MenuItem.OnMenuItemClickListener { /** * 整个布局容器 */ private lateinit var rootLayout: FrameLayout /** * 整个容器背景 处理点击外部消失和背景渐变效果 */ private lateinit var rootLayoutBg: View /** * 背景颜色 */ private var backgroundColor = -0x70000000 /** * 内容面板 root 布局 */ private lateinit var rootPanel: LinearLayout /** * 标题面板 */ private lateinit var titlePanel: LinearLayout /** * 标题面板下的模板,不指定自定义的 title view 的时候显示这个 */ private lateinit var titleTemplate: LinearLayout /** * 标题 icon */ private lateinit var titleTemplateIcon: ImageView /** * 标题 icon 内容 */ private var titleIconDrawable: Drawable? = null /** * 默认 icon 资源 */ private var titleIconResId = -1 /** * 标题 TextView */ private lateinit var titleTemplateText: TextView /** * 标题 text 内容 */ private var titleTextStr: CharSequence = "" /** * 用户自定义顶部内容 */ private var mCustomTitleView: View? = null /** * 内容面板 */ private lateinit var contentPanel: LinearLayout /** * 内容 ScrollView 容器 */ private lateinit var contentScrollView: ScrollView /** * 内容 text */ private lateinit var contentMessageView: TextView /** * 内容 text 内容 */ private var contentMessageStr: CharSequence = "" /** * 表格显示的时候每页显示的行数 */ var pageGridRow = 2 /** * 表格显示的时候每页显示的列数 */ var pageGridCol = 3 /** * 用户自定义的View Panel */ private lateinit var customPanel: FrameLayout /** * 用户自定义的 View */ private var customView: View? = null /** * 底部的按钮 */ private lateinit var controllerPanel: LinearLayout /** * 取消按钮 */ private lateinit var controllerNegativeButton: Button var negativeStr: CharSequence = "" /** * 确认按钮 */ private lateinit var controllerPositiveButton: Button var positiveStr: CharSequence = "" var mControllerListener: PanelControllerListener? = null private var mViewSpacingSpecified = false private var mViewSpacingLeft = 0 private var mViewSpacingTop = 0 private var mViewSpacingRight = 0 private var mViewSpacingBottom = 0 private val rootLayoutId: Int = R.layout.xander_panel var canceledTouchOutside = true var showSheetCancel = true var sheetCancelStr: CharSequence = "" var showSheet = false lateinit var sheetItems: Array<String> var sheetListener: SheetListener? = null var actionMenu: ActionMenu? = null var menuListener: PanelMenuListener? = null var showMenuAsGrid = false var shareMode = false var shareStr = "" var shareImages: Array<String> = arrayOf() var panelItemClickListener = PanelItemClickListener() var gravity = Gravity.BOTTOM private var panelMargin = 160 init { val typedArray = mContext.obtainStyledAttributes(COLORR_ATTRS) backgroundColor = typedArray.getColor(0, -0x70000000) typedArray.recycle() } fun getParentView(): View { return rootLayout } fun setPanelMargin(margin: Int) { panelMargin = margin } fun setTitle(title: String) { titleTextStr = title } fun setCustomTitle(customTitleView: View?) { mCustomTitleView = customTitleView } fun setMessage(message: String) { contentMessageStr = message } /** * Set the view to display in the dialog. */ fun setCustomView(view: View?) { customView = view mViewSpacingSpecified = false } /** * Set the view to display in the dialog along with the spacing around that view */ fun setCustomView(view: View?, viewSpacingLeft: Int, viewSpacingTop: Int, viewSpacingRight: Int, viewSpacingBottom: Int) { customView = view mViewSpacingSpecified = true mViewSpacingLeft = viewSpacingLeft mViewSpacingTop = viewSpacingTop mViewSpacingRight = viewSpacingRight mViewSpacingBottom = viewSpacingBottom } /** * Set resId to 0 if you don't want an icon. * * @param resId the resourceId of the drawable to use as the icon or 0 * if you don't want an icon. */ fun setIcon(resId: Int) { titleIconResId = resId if (resId > 0) { titleTemplateIcon.setImageResource(titleIconResId) titleTemplateIcon.visibility = View.VISIBLE } else if (resId == 0) { titleTemplateIcon.visibility = View.GONE } } fun setIcon(icon: Drawable?) { titleIconDrawable = icon titleIconDrawable?.let { titleTemplateIcon.setImageDrawable(it) titleTemplateIcon.visibility = View.VISIBLE } ?: apply { titleTemplateIcon.visibility = View.GONE } } /** * @param attrId the attributeId of the theme-specific drawable * to resolve the resourceId for. * @return resId the resourceId of the theme-specific drawable */ fun getIconAttributeResId(attrId: Int): Int { val out = TypedValue() mContext.theme.resolveAttribute(attrId, out, true) return out.resourceId } fun applyView() { ensureInflaterLayout() applyRootPanel() when { showSheet -> { applySheet() } actionMenu?.isNotEmpty() == true -> { applyMenu() } else -> { applyTitlePanel() applyContentPanel() applyCustomPanel() applyControllerPanel() } } } override fun onClick(view: View) { when (view.id) { R.id.controller_nagetive -> { mControllerListener?.let { mXanderPanel.dismiss() it.onPanelNegativeClick(mXanderPanel) } } R.id.controller_positive -> { mControllerListener?.let { mXanderPanel.dismiss() it.onPanelPositiveClick(mXanderPanel) } } R.id.root_background -> { if (canceledTouchOutside) { mXanderPanel.dismiss() } } R.id.xander_panel_sheet_cancel -> { sheetListener?.onSheetCancelClick() mXanderPanel.dismiss() } } } private fun ensureInflaterLayout() { if (null != rootLayout) { return } val inflater = LayoutInflater.from(mContext) rootLayout = inflater.inflate(rootLayoutId, null) as FrameLayout rootLayoutBg = rootLayout.findViewById(R.id.root_background) rootLayoutBg.setOnClickListener(this) rootLayoutBg.setBackgroundColor(backgroundColor) rootPanel = rootLayout.findViewById<View>(R.id.panel_root) as LinearLayout titlePanel = rootPanel.findViewById<View>(R.id.title_panel) as LinearLayout titleTemplate = titlePanel.findViewById<View>(R.id.title_template) as LinearLayout titleTemplateIcon = titleTemplate.findViewById<View>(R.id.title_icon) as ImageView titleTemplateText = titleTemplate.findViewById<View>(R.id.title_text) as TextView contentPanel = rootPanel.findViewById<View>(R.id.content_panel) as LinearLayout contentScrollView = rootPanel.findViewById<View>(R.id.msg_scrollview) as ScrollView contentMessageView = contentScrollView.findViewById<View>(R.id.msg_text) as TextView customPanel = rootLayout.findViewById<View>(R.id.custom_panel) as FrameLayout controllerPanel = rootLayout.findViewById<View>(R.id.controller_pannle) as LinearLayout controllerNegativeButton = controllerPanel.findViewById<View>(R.id.controller_nagetive) as Button controllerNegativeButton.setOnClickListener(this) controllerPositiveButton = controllerPanel.findViewById<View>(R.id.controller_positive) as Button controllerPositiveButton.setOnClickListener(this) } private fun applyRootPanel() { val layoutParams = rootPanel.layoutParams as FrameLayout.LayoutParams var sheetMargin = 0 layoutParams.gravity = gravity if (showSheet) { gravity = Gravity.BOTTOM layoutParams.gravity = gravity sheetMargin = mContext.resources.getDimension(R.dimen.panel_sheet_margin).toInt() } layoutParams.leftMargin = sheetMargin layoutParams.topMargin = sheetMargin layoutParams.rightMargin = sheetMargin layoutParams.bottomMargin = sheetMargin if (Gravity.TOP == gravity) { layoutParams.bottomMargin = panelMargin } else if (Gravity.BOTTOM == gravity) { layoutParams.topMargin = panelMargin } rootPanel.layoutParams = layoutParams rootPanel.setOnClickListener(null) val paddingTop = if (Build.VERSION.SDK_INT > 19) SystemBarTintManager.getStatusBarHeight(mContext) else 0 val paddingBottom = if (Build.VERSION.SDK_INT > 19) SystemBarTintManager.getNavigationBarHeight(mContext) else 0 if (Gravity.TOP == gravity) { rootPanel.setPadding(0, paddingTop, 0, 0) } else if (Gravity.BOTTOM == gravity) { rootPanel.setPadding(0, 0, 0, paddingBottom) } if (!showSheet) { rootPanel.setBackgroundResource(R.color.panel_root_layout_bg) } } private fun applyTitlePanel(): Boolean { var hasTitle = true mCustomTitleView?.let { titleTemplate.visibility = View.GONE // Add the custom title view directly to the titlePanel layout titlePanel.visibility = View.VISIBLE // hide title temple val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) titlePanel.addView(mCustomTitleView, 1, lp) } ?: apply { if (titleTextStr.isNotEmpty()) { titlePanel.visibility = View.VISIBLE /* Display the title if a title is supplied, else hide it */ titleTemplate.visibility = View.VISIBLE titleTemplateText.text = titleTextStr /* Do this last so that if the user has supplied any * icons we use them instead of the default ones. If the * user has specified 0 then make it disappear. */ when { titleIconResId > 0 -> { titleTemplateIcon.setImageResource(titleIconResId) } titleIconDrawable != null -> { titleTemplateIcon.setImageDrawable(titleIconDrawable) } titleIconResId == 0 -> { /* Apply the padding from the icon to ensure the * title is aligned correctly. */ titleTemplateText.setPadding(titleTemplateIcon.paddingLeft, titleTemplateIcon.paddingTop, titleTemplateIcon.paddingRight, titleTemplateIcon.paddingBottom) titleTemplateIcon.visibility = View.GONE } } } else { // Hide the title template titlePanel.visibility = View.GONE hasTitle = false } } return hasTitle } private fun applyContentPanel() { if (contentMessageStr.isNotEmpty()) { contentPanel.visibility = View.VISIBLE contentScrollView.isFocusable = false contentMessageView.text = contentMessageStr } else { contentPanel.visibility = View.GONE } } private fun applyCustomPanel() { customView?.let { titlePanel.visibility = View.GONE contentPanel.visibility = View.GONE // 清空内容 customPanel.visibility = View.VISIBLE customPanel.removeAllViews() customPanel.addView(customView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) if (mViewSpacingSpecified) { customPanel.setPadding(mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight, mViewSpacingBottom) } } ?: apply { customPanel.visibility = View.GONE } } private fun applyControllerPanel() { controllerNegativeButton.let { it.text = negativeStr it.visibility = if (negativeStr.isNotEmpty()) View.VISIBLE else View.GONE } controllerPositiveButton.let { it.text = negativeStr it.visibility = if (positiveStr.isNotEmpty()) View.VISIBLE else View.GONE } controllerPanel.let { it.visibility = if (positiveStr.isEmpty() && positiveStr.isEmpty()) View.GONE else View.VISIBLE } } private fun applySheet() { rootPanel.removeAllViews() val inflater = LayoutInflater.from(mContext) val sheetView = inflater.inflate(R.layout.xander_panel_sheet, rootLayout, false) val sheetCancel = sheetView.findViewById<View>(R.id.xander_panel_sheet_cancel) as TextView sheetCancel.visibility = if (showSheetCancel) View.VISIBLE else View.GONE sheetCancel.text = sheetCancelStr sheetCancel.setOnClickListener(this) val sheetList = sheetView.findViewById<View>(R.id.xander_panel_sheet_list) as ListView val sheetAdapter = SheetAdapter(mContext, sheetItems) sheetList.adapter = sheetAdapter sheetList.onItemClickListener = panelItemClickListener // sheetList.setOnItemLongClickListener(panelItemClickListenr); rootPanel.addView(sheetView) } override fun onMenuItemClick(item: MenuItem): Boolean { var result = false menuListener?.let { it.onMenuClick(item) mXanderPanel.dismiss() result = true } ?: apply { if (shareMode && item is ActionMenuItem) { ShareTools.share(mContext, shareStr, shareImages, item.componentName) mXanderPanel.dismiss() result = true } } return result } private fun applyMenu() { rootPanel.removeAllViews() val count = actionMenu?.size() ?: 0 if (count == 0) { return } for (i in count - 1 downTo 0) { actionMenu?.getItem(i)?.setOnMenuItemClickListener(this) } val inflater = LayoutInflater.from(mContext) if (showMenuAsGrid) { val view = inflater.inflate(R.layout.xander_panel_menu_gridviewpager, rootPanel, false) val viewPager = view.findViewById<View>(R.id.xander_panel_gridviewpager) as ViewPager var row = pageGridRow var col = pageGridCol if (count < col) { row = 1 col = count } val pagerAdapter = GridViewPagerAdapter(mContext, row, col) val params = viewPager.layoutParams as LinearLayout.LayoutParams val screenWidth = mContext.resources.displayMetrics.widthPixels params.height = screenWidth / 3.coerceAtLeast(col) * row Log.d("wxy", "params ${params.width},${params.height}") viewPager.layoutParams = params pagerAdapter.setActionMenus(actionMenu!!, viewPager) viewPager.adapter = pagerAdapter val indicator = view.findViewById<View>(R.id.xander_panel_indicator) as CirclePageIndicator indicator.setViewPager(viewPager) rootPanel.addView(view) } else { val menuList = inflater.inflate(R.layout.xander_panel_menu_list, rootPanel, false) as ListView val menuAdapter = MenuAdapter(mContext, actionMenu!!) menuList.adapter = menuAdapter menuList.onItemClickListener = panelItemClickListener rootPanel.addView(menuList) } } fun animateShow() { doAnim(ANIM_TYPE_SHOW) } fun animateDismiss() { doAnim(ANIM_TYPE_DISMISS) } private fun doAnim(type: Int) { rootLayoutBg.startAnimation(createBgAnimation(type)) rootPanel.startAnimation(createPanelAnimation(type)) } private fun createPanelAnimation(animType: Int): Animation? { val type = TranslateAnimation.RELATIVE_TO_SELF var animation: TranslateAnimation? = null if (ANIM_TYPE_SHOW == animType) { if (Gravity.TOP == gravity) { animation = TranslateAnimation(type, 0F, type, 0F, type, -1F, type, 0F) } else if (Gravity.BOTTOM == gravity) { animation = TranslateAnimation(type, 0F, type, 0F, type, 1F, type, 0F) } } else { if (Gravity.TOP == gravity) { animation = TranslateAnimation(type, 0F, type, 0F, type, 0F, type, -1F) } else if (Gravity.BOTTOM == gravity) { animation = TranslateAnimation(type, 0F, type, 0F, type, 0F, type, 1F) } } animation?.duration = DURATION_TRANSLATE.toLong() animation?.fillAfter = true return animation } private fun createBgAnimation(animType: Int): Animation { var alphaAnimation: AlphaAnimation = if (ANIM_TYPE_SHOW == animType) { AlphaAnimation(0F, 1F) } else { AlphaAnimation(1F, 0F) } alphaAnimation.duration = DURATION_ALPHA.toLong() alphaAnimation.fillAfter = true return alphaAnimation } companion object { private val BACKGROUND_COLOR = R.attr.xPanel_BackgroudColor private val COLORR_ATTRS: IntArray = intArrayOf(BACKGROUND_COLOR) const val DURATION = 300L const val DURATION_TRANSLATE = 200 const val DURATION_ALPHA = DURATION const val ANIM_TYPE_SHOW = 0 const val ANIM_TYPE_DISMISS = 1 /** * 检测 view 是否可以输入 * * @param view * @return */ fun canTextInput(view: View): Boolean { if (view.onCheckIsTextEditor()) { return true } if (view !is ViewGroup) { return false } var childCount = view.childCount while (childCount > 0) { var childView = view.getChildAt(childCount) if (canTextInput(childView)) { return true } childCount-- } return false } } } class PanelParams(var context: Context) { var panelMargin = 200 var icon: Drawable? = null var iconId = 0 var iconAttrId = 0 var title = "" var customTitleView: View? = null var message = "" var customView: View? = null var viewSpacingSpecified = false var viewSpacingLeft = 0 var viewSpacingTop = 0 var viewSpacingRight = 0 var viewSpacingBottom = 0 var cancelable = true var canceledOnTouchOutside = true var showSheetCancel = true var sheetCancelStr: CharSequence = "" var showSheet = false var sheetItems: Array<String> = arrayOf() var sheetListener: SheetListener? = null var share = false var shareText = "" var shareImages: Array<String> = arrayOf() var filterPackages: Array<String> = arrayOf() var nagetive: CharSequence = "" var positive: CharSequence = "" var controllerListener: PanelControllerListener? = null var actionMenu: ActionMenu? = null var menuListener: PanelMenuListener? = null /** * 表格显示的时候每页显示的行数 */ var pagerGridRow = 2 /** * 表格显示的时候每页显示的列数 */ var pagerGridCol = 3 var showMenuAsGrid = false var showListener: PanelShowListener? = null var dismissListener: PanelDismissListener? = null var mGravity = Gravity.BOTTOM fun apply(panelController: PanelController) { // title customTitleView?.let { panelController.setCustomTitle(it) } ?: apply { if (title.isNotEmpty()) { panelController.setTitle(title) } when { iconAttrId > 0 -> { panelController.setIcon(panelController.getIconAttributeResId(iconAttrId)) } iconId >= 0 -> { panelController.setIcon(iconId) } else -> { icon?.apply { panelController.setIcon(this) } } } } // msg if (message.isNotEmpty()) { panelController.setMessage(message) } // custom view customView?.let { when { viewSpacingSpecified -> { panelController.setCustomView(customView, viewSpacingLeft, viewSpacingTop, viewSpacingRight, viewSpacingBottom) } else -> { panelController.setCustomView(customView) } } } if (share) { actionMenu = ShareTools.createShareActionMenu(context, shareText, shareImages, filterPackages) } // set menu actionMenu?.let { panelController.shareMode = share panelController.shareStr = shareText panelController.shareImages = shareImages panelController.showMenuAsGrid = showMenuAsGrid panelController.pageGridRow = pagerGridRow panelController.pageGridCol = pagerGridCol panelController.menuListener = menuListener panelController.actionMenu = it.clone(it.size()) panelController.actionMenu!!.removeInvisible() } // set sheet panelController.showSheet = showSheet panelController.showSheetCancel = showSheetCancel panelController.sheetCancelStr = sheetCancelStr panelController.sheetItems = sheetItems panelController.sheetListener = sheetListener // set controller panelController.positiveStr = positive panelController.negativeStr = nagetive panelController.mControllerListener = controllerListener // other settings panelController.gravity = mGravity panelController.canceledTouchOutside = canceledOnTouchOutside panelController.setPanelMargin(panelMargin) panelController.applyView() } } class MenuAdapter(context: Context, private val menu: ActionMenu) : BaseAdapter() { private val inflater: LayoutInflater = LayoutInflater.from(context) override fun getCount(): Int { return menu.size() } override fun getItem(position: Int): Any? { return menu.getItem(position) } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { var newConvertView = convertView val menuHolder: MenuHolderA if (null == convertView) { newConvertView = inflater.inflate(R.layout.xander_panel_menu_list_item, parent, false) menuHolder = MenuHolderA(newConvertView) newConvertView.tag = menuHolder } else { menuHolder = convertView.tag as MenuHolderA } menuHolder.bindMenuItem(menu.getItem(position)) return newConvertView } } class MenuHolderA(parent: View) { private lateinit var menuIcon: ImageView private lateinit var menuTitle: TextView init { bindView(parent) } private fun bindView(parent: View) { menuIcon = parent.findViewById<View?>(R.id.panel_menu_icon) as ImageView menuTitle = parent.findViewById<View?>(R.id.panel_menu_title) as TextView } fun bindMenuItem(menuItem: MenuItem) { if (null == menuItem.icon) { menuIcon.visibility = View.GONE } else { menuIcon.visibility = View.VISIBLE menuIcon.setImageDrawable(menuItem.icon) } menuTitle.text = menuItem.title } } class SheetAdapter(contexts: Context, sheetItems: Array<String>) : BaseAdapter() { private val inflater: LayoutInflater = LayoutInflater.from(contexts) private val mSheetItems: MutableList<String> = ArrayList() init { mSheetItems.addAll(sheetItems) } override fun getCount(): Int { return mSheetItems.size } override fun getItem(position: Int): Any? { return mSheetItems[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var newConvertView = convertView if (null == convertView) { newConvertView = inflater.inflate(R.layout.xander_panel_sheet_item, parent, false) } val textView = newConvertView as TextView when { count == 1 -> { textView.setBackgroundResource(R.drawable.sheet_item_just_one) } position == 0 -> { textView.setBackgroundResource(R.drawable.sheet_item_top) } position == count - 1 -> { textView.setBackgroundResource(R.drawable.sheet_item_bottom) } else -> { textView.setBackgroundResource(R.drawable.sheet_item_normal) } } textView.text = mSheetItems[position] return newConvertView } } class PanelItemClickListener : OnItemClickListener, OnItemLongClickListener { override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // if (showSheet && mSheetListener != null) { // mSheetListener.onSheetItemClick(position) // } else if (null != actionMenu && null != menuListener) { // menuListener.onMenuClick(actionMenu.getItem(position)) // } else if (mShare) { // val menuItem = actionMenu.getItem(position) // if (menuItem is ActionMenuItem) { // (menuItem as ActionMenuItem).invoke() // } // return // } // mXanderPanel.dismiss() } override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean { // if (showSheet && mSheetListener != null) { // mSheetListener.onSheetItemClick(position) // } else if (null != actionMenu && null != menuListener) { // menuListener.onMenuClick(actionMenu.getItem(position)) // } else if (mShare) { // val menuItem = actionMenu.getItem(position) // if (menuItem is ActionMenuItem) { // (menuItem as ActionMenuItem).invoke() // } // return true // } // mXanderPanel.dismiss() return true } }
apache-2.0
e5e13fba6fec09bffc2f35fa9e9c1b27
31.25
120
0.608183
5.074264
false
false
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/ui/notifications/NotificationsAdapter.kt
1
4663
package com.andreapivetta.blu.ui.notifications import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.andreapivetta.blu.R import com.andreapivetta.blu.common.utils.Utils import com.andreapivetta.blu.common.utils.loadAvatar import com.andreapivetta.blu.data.model.Notification import com.andreapivetta.blu.ui.profile.UserActivity import com.andreapivetta.blu.ui.tweetdetails.TweetDetailsActivity import kotlinx.android.synthetic.main.notification_item.view.* import kotlinx.android.synthetic.main.notification_item_header.view.* import java.util.* /** * Created by andrea on 29/09/16. */ class NotificationsAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { class NotificationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun setup(notification: Notification) { itemView.userProfilePicImageView.loadAvatar(notification.profilePicURL) itemView.notificationTypeImageView.setImageDrawable( NotificationAssetsSelector.getIcon(notification, itemView.context)) itemView.userNameTextView.text = notification.userName itemView.timeTextView.text = Utils.formatDate(notification.timestamp) itemView.notificationTextView.text = NotificationAssetsSelector .getText(notification, itemView.context) itemView.setOnClickListener { when (notification.type) { Notification.FOLLOW -> UserActivity.launch(itemView.context, notification.userId) Notification.MENTION, Notification.RETWEET, Notification.FAVOURITE -> TweetDetailsActivity.launch(itemView.context, notification.tweetId) } } } } class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun setup(old: Boolean) { itemView.labelTextView.text = if (old) "Old" else "New" } } private val TYPE_HEADER_NEW = 0 private val TYPE_HEADER_OLD = 1 private val TYPE_NOTIFICATION_NEW = 2 private val TYPE_NOTIFICATION_OLD = 3 var unreadNotifications: List<Notification> = ArrayList() var readNotifications: List<Notification> = ArrayList() override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder = if (viewType == TYPE_NOTIFICATION_NEW || viewType == TYPE_NOTIFICATION_OLD) NotificationViewHolder(LayoutInflater.from(parent?.context) .inflate(R.layout.notification_item, parent, false)) else HeaderViewHolder(LayoutInflater.from(parent?.context) .inflate(R.layout.notification_item_header, parent, false)) override fun getItemCount(): Int { if (unreadNotifications.isNotEmpty()) if (readNotifications.isNotEmpty()) return 2 + readNotifications.size + unreadNotifications.size else return 1 + unreadNotifications.size else if (readNotifications.isNotEmpty()) return 1 + readNotifications.size return 0 } override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { when (getItemViewType(position)) { TYPE_NOTIFICATION_NEW -> (holder as NotificationViewHolder) .setup(unreadNotifications[getRealIndex(position)]) TYPE_NOTIFICATION_OLD -> (holder as NotificationViewHolder) .setup(readNotifications[getRealIndex(position)]) TYPE_HEADER_OLD -> (holder as HeaderViewHolder).setup(true) TYPE_HEADER_NEW -> (holder as HeaderViewHolder).setup(false) } } override fun getItemViewType(position: Int): Int = if (unreadNotifications.isNotEmpty()) { if (position == 0) TYPE_HEADER_NEW else if (position <= unreadNotifications.size) TYPE_NOTIFICATION_NEW else if (position == unreadNotifications.size + 1 && unreadNotifications.isNotEmpty()) TYPE_HEADER_OLD else TYPE_NOTIFICATION_OLD } else { if (position == 0) TYPE_HEADER_OLD else TYPE_NOTIFICATION_OLD } private fun getRealIndex(position: Int): Int = if (getItemViewType(position) == TYPE_NOTIFICATION_NEW) position - 1 else if (unreadNotifications.isNotEmpty()) position - 2 - unreadNotifications.size else position - 1 }
apache-2.0
670c4e166d90e33c08fefdaaf029a019
39.556522
101
0.659876
5.169623
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/fragments/usersearch/UserSearchFrag.kt
1
4317
package com.duopoints.android.fragments.usersearch import android.os.Bundle import android.support.annotation.AnimRes import android.support.v7.widget.SearchView import android.text.TextUtils import android.view.* import android.widget.Toast import com.duopoints.android.R import com.duopoints.android.fragments.base.BasePresenterFrag import com.duopoints.android.rest.models.dbviews.UserData import com.duopoints.android.ui.lists.UserSearchAdapter import com.duopoints.android.ui.lists.base.AdapterDelegatesManager import com.duopoints.android.ui.lists.base.BaseAdapter import com.duopoints.android.ui.lists.layouts.dividers.SimpleVerticalItemDivider import com.duopoints.android.ui.lists.layouts.linear.PreFetchVerticalLayoutManager import com.duopoints.android.utils.UiUtils import kotlinx.android.synthetic.main.frag_user_search.* class UserSearchFrag : BasePresenterFrag<UserSearchPresenter>() { lateinit var adapter: BaseAdapter override fun createPresenter(): UserSearchPresenter { return UserSearchPresenter(this) } @AnimRes override fun getEnterAnimation(): Int { return R.anim.enter_from_right } @AnimRes override fun getExitAnimation(): Int { return R.anim.exit_to_right } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return createAndBindView(R.layout.frag_user_search, inflater, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mainActivity.setToolbar(userSearchToolbar) userSearchLceRecyclerView.setEmptyViewTitle("Start searching by typing in the search field...") // Setup RecyclerView adapter = BaseAdapter(AdapterDelegatesManager().addDelegate(UserSearchAdapter())) userSearchLceRecyclerView.recyclerView.isNestedScrollingEnabled = false userSearchLceRecyclerView.recyclerView.layoutManager = PreFetchVerticalLayoutManager(context) userSearchLceRecyclerView.recyclerView.addItemDecoration(SimpleVerticalItemDivider(UiUtils.convertDpToPixel(12f).toInt())) userSearchLceRecyclerView.recyclerView.adapter = adapter userSearchLceRecyclerView.empty() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) // Inflate new Menu inflater.inflate(R.menu.user_search_menu, menu) val menuItem = menu.findItem(R.id.action_search) UiUtils.tintMenuIcon(context, menuItem, UiUtils.getResId(context, R.attr.colorMenuIconTint)) val searchView = menuItem.actionView as SearchView searchView.isIconified = false searchView.setOnCloseListener { mainActivity.supportFragmentManager.popBackStack() true } searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { if (!TextUtils.isEmpty(query) && query.length < 3) { Toast.makeText(context, "Search for 3 letters or more", Toast.LENGTH_SHORT).show() } else { presenter.searchForUser(query) userSearchLceRecyclerView.loading() closeKeyboard() } return true } override fun onQueryTextChange(newText: String): Boolean { return true } }) } override fun onPause() { closeKeyboard() super.onPause() } /****************** * CALL BACKS ******************/ fun loadSearch(users: List<UserData>) { adapter.replaceData(users) userSearchLceRecyclerView.loaded(users.isEmpty()) } fun errorSearching(throwable: Throwable) { userSearchLceRecyclerView.setErrorViewTitle("Error: " + throwable.message) userSearchLceRecyclerView.error() Toast.makeText(context, "Error:" + throwable.message, Toast.LENGTH_LONG).show() throwable.printStackTrace() } companion object { @JvmStatic fun newInstance(): UserSearchFrag { return UserSearchFrag() } } }
gpl-3.0
6f7879e484e00315f1e442de1abcbd71
33.544
130
0.694
5.127078
false
false
false
false
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/service/MobileNetworkService.kt
3
929
package org.worshipsongs.service import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo /** * author:Madasamy * version:1.2.0 */ class MobileNetworkService : IMobileNetworkService { override fun isWifi(`object`: Any): Boolean { //object should be system service val connectivityManager = `object` as ConnectivityManager val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI } override fun isMobileData(`object`: Any): Boolean { val connectivityManager = `object` as ConnectivityManager val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_MOBILE } }
gpl-3.0
12d6f3aeb96f024d693d4a3851e0e125
29.966667
67
0.707212
5.497041
false
false
false
false
andrei-heidelbacher/metanalysis
analyzers/chronolens-decapsulations/src/main/kotlin/org/chronolens/decapsulations/DecapsulationsCommand.kt
1
1740
/* * Copyright 2017 Andrei Heidelbacher <[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 org.chronolens.decapsulations import org.chronolens.core.cli.Subcommand import org.chronolens.core.cli.restrictTo import org.chronolens.core.serialization.JsonModule internal class DecapsulationsCommand : Subcommand() { override val help: String get() = """ Loads the persisted repository, detects the decapsulations that occurred during the evolution of the project and reports the results to the standard output. """ private val keepConstants by option<Boolean>() .help("do not ignore decapsulations of constant fields") .defaultValue(false) private val minMetricValue by option<Int>().help( """ignore source files that have less decapsulations than the specified limit""" ).defaultValue(0).restrictTo(min = 0) override fun run() { val analyzer = HistoryAnalyzer(!keepConstants) val repository = load() val report = analyzer.analyze(repository.getHistory()) val files = report.files.filter { it.value >= minMetricValue } JsonModule.serialize(System.out, files) } }
apache-2.0
828710bf16e7e81fcea7d2e8aa7d4970
36.826087
80
0.717241
4.566929
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/data/provider/standard/JsonRpcDataProvider.kt
1
8181
/* Copyright 2015 Andreas Würl 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.blitzortung.android.data.provider.standard import android.content.SharedPreferences import android.util.Log import org.blitzortung.android.app.Main import org.blitzortung.android.app.view.PreferenceKey import org.blitzortung.android.app.view.get import org.blitzortung.android.data.Parameters import org.blitzortung.android.data.beans.Station import org.blitzortung.android.data.beans.Strike import org.blitzortung.android.data.provider.DataBuilder import org.blitzortung.android.data.provider.DataProvider import org.blitzortung.android.data.provider.DataProviderType import org.blitzortung.android.data.provider.result.ResultEvent import org.blitzortung.android.jsonrpc.JsonRpcClient import org.blitzortung.android.util.TimeFormat import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.net.URL import java.text.SimpleDateFormat import java.util.* class JsonRpcDataProvider( preferences: SharedPreferences, private val agentSuffix: String ) : DataProvider(preferences, PreferenceKey.SERVICE_URL) { private lateinit var serviceUrl: String private val dataBuilder: DataBuilder private var nextId = 0 init { dataBuilder = DataBuilder() Log.v(Main.LOG_TAG, "JsonRpcDataProvider($serviceUrl)") } override val type: DataProviderType = DataProviderType.RPC private fun setUpClient(): JsonRpcClient { val client = JsonRpcClient(serviceUrl, agentSuffix) return client.apply { connectionTimeout = 40000 socketTimeout = 40000 } } override fun reset() { nextId = 0 } override val isCapableOfHistoricalData: Boolean = true @Throws(JSONException::class) private fun addStrikes(response: JSONObject, result: ResultEvent): ResultEvent { val strikes = ArrayList<Strike>() val referenceTimestamp = getReferenceTimestamp(response) val strikes_array = response.get("s") as JSONArray for (i in 0..strikes_array.length() - 1) { strikes.add(dataBuilder.createDefaultStrike(referenceTimestamp, strikes_array.getJSONArray(i))) } if (response.has("next")) { nextId = response.get("next") as Int } return result.copy(strikes = strikes) } private fun addRasterData(response: JSONObject, result: ResultEvent, info: String): ResultEvent { val rasterParameters = dataBuilder.createRasterParameters(response, info) val referenceTimestamp = getReferenceTimestamp(response) val strikes_array = response.get("r") as JSONArray val strikes = ArrayList<Strike>() for (i in 0..strikes_array.length() - 1) { strikes.add(dataBuilder.createRasterElement(rasterParameters, referenceTimestamp, strikes_array.getJSONArray(i))) } return result.copy(strikes = strikes, rasterParameters = rasterParameters, incrementalData = false) } @Throws(JSONException::class) private fun getReferenceTimestamp(response: JSONObject): Long { return TimeFormat.parseTime(response.getString("t")) } @Throws(JSONException::class) private fun addStrikesHistogram(response: JSONObject, result: ResultEvent): ResultEvent { var resultVar = result if (response.has("h")) { val histogram_array = response.get("h") as JSONArray val histogram = IntArray(histogram_array.length()) for (i in 0..histogram_array.length() - 1) { histogram[i] = histogram_array.getInt(i) } resultVar = resultVar.copy(histogram = histogram) } return resultVar } override fun <T> retrieveData(retrieve: DataRetriever.() -> T): T { val client = setUpClient() val t = Retriever(client).retrieve() client.shutdown() return t } private inner class Retriever(val client: JsonRpcClient) : DataRetriever { override fun getStations(region: Int): List<Station> { val stations = ArrayList<Station>() try { val response = client.call("get_stations") val stations_array = response.get("stations") as JSONArray for (i in 0..stations_array.length() - 1) { stations.add(dataBuilder.createStation(stations_array.getJSONArray(i))) } } catch (e: Exception) { throw RuntimeException(e) } return stations } override fun getStrikesGrid(parameters: Parameters, result: ResultEvent): ResultEvent { var resultVar = result nextId = 0 val intervalDuration = parameters.intervalDuration val intervalOffset = parameters.intervalOffset val rasterBaselength = parameters.rasterBaselength val countThreshold = parameters.countThreshold val region = parameters.region try { val response = client.call("get_strikes_grid", intervalDuration, rasterBaselength, intervalOffset, region, countThreshold) val info = "%.0f km".format(rasterBaselength / 1000f) resultVar = addRasterData(response, resultVar, info) resultVar = addStrikesHistogram(response, resultVar) } catch (e: Exception) { throw RuntimeException(e) } Log.v(Main.LOG_TAG, "JsonRpcDataProvider: read %d bytes (%d raster positions, region %d)".format(client.lastNumberOfTransferredBytes, resultVar.strikes?.size, region)) return resultVar } override fun getStrikes(parameters: Parameters, result: ResultEvent): ResultEvent { var resultVar = result val intervalDuration = parameters.intervalDuration val intervalOffset = parameters.intervalOffset if (intervalOffset < 0) { nextId = 0 } resultVar = resultVar.copy(incrementalData = (nextId != 0)) try { val response = client.call("get_strikes", intervalDuration, if (intervalOffset < 0) intervalOffset else nextId) resultVar = addStrikes(response, resultVar) resultVar = addStrikesHistogram(response, resultVar) } catch (e: Exception) { throw RuntimeException(e) } Log.v(Main.LOG_TAG, "JsonRpcDataProvider: read %d bytes (%d new strikes)".format(client.lastNumberOfTransferredBytes, resultVar.strikes?.size)) return resultVar } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) { when (key) { PreferenceKey.SERVICE_URL -> serviceUrl = toCheckedUrl(sharedPreferences.get(PreferenceKey.SERVICE_URL, "")) else -> { } } } private fun toCheckedUrl(serviceUrl: String): String { try { URL(serviceUrl) } catch (e: Exception) { Log.e(Main.LOG_TAG, "JsonRpcDataProvider.tocheckedUrl($serviceUrl) invalid") return DEFAULT_SERVICE_URL } return serviceUrl } companion object { private val DATE_TIME_FORMATTER = SimpleDateFormat("yyyyMMdd'T'HH:mm:ss") private val DEFAULT_SERVICE_URL = "http://bo-service.tryb.de/" init { val tz = TimeZone.getTimeZone("UTC") DATE_TIME_FORMATTER.timeZone = tz } } }
apache-2.0
76947b382f9815df9869ae683d90baea
34.258621
167
0.6522
4.892344
false
false
false
false
natanieljr/droidmate
project/pcComponents/core/src/main/kotlin/org/droidmate/device/TcpClientBase.kt
1
3865
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.device import org.droidmate.device.error.DeviceException import org.droidmate.deviceInterface.communication.SerializationHelper import java.io.DataInputStream import java.io.DataOutputStream import java.io.EOFException import java.io.Serializable import java.net.ConnectException import java.net.Socket import java.net.SocketException import java.net.SocketTimeoutException class TcpClientBase<in InputToServerT : Serializable, out OutputFromServerT : Serializable> constructor(private val hostIp: String, private val socketTimeout: Int) : ITcpClientBase<InputToServerT, OutputFromServerT> { /*companion object { private val logcat = LoggerFactory.getLogger(TcpClientBase::class.java) }*/ @Suppress("UNCHECKED_CAST") @Throws(TcpServerUnreachableException::class, DeviceException::class) override fun queryServer(input: InputToServerT, port: Int): OutputFromServerT { try { //logcat.trace("Socket socket = this.tryGetSocket($hostIp, $port)") val socket = this.tryGetSocket(hostIp, port) // logcat.trace("Got socket: $hostIp:$port timeout: ${this.socketTimeout}") socket.soTimeout = this.socketTimeout // This will block until corresponding socket output stream (located on server) is flushed. // // Reference: // 1. the ObjectInputStream constructor comment. // 2. search for: "Note - The ObjectInputStream constructor blocks until" in: // http://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html // // logcat.trace("inputStream = new ObjectInputStream(socket<$hostIp:$port>.inputStream)") val inputStream = DataInputStream(socket.inputStream) // logcat.trace("Got input stream") val outputStream = DataOutputStream(socket.outputStream) // logcat.trace("got outputStream") SerializationHelper.writeObjectToStream(outputStream, input) outputStream.flush() val output = SerializationHelper.readObjectFromStream(inputStream) as OutputFromServerT // logcat.trace("socket.close()") socket.close() return output } catch (e: EOFException) { throw TcpServerUnreachableException(e) } catch (e: SocketTimeoutException) { throw TcpServerUnreachableException(e) } catch (e: SocketException) { throw TcpServerUnreachableException(e) } catch (e: TcpServerUnreachableException) { throw e } catch (t: Throwable) { throw DeviceException("TcpClientBase has thrown a ${t.javaClass.simpleName} while querying server. " + "Requesting to stop further apk explorations.", t, true) } } @Throws(TcpServerUnreachableException::class) private fun tryGetSocket(hostIp: String, port: Int): Socket { try { val socket = Socket(hostIp, port) assert(socket.isConnected) return socket } catch (e: ConnectException) { throw TcpServerUnreachableException(e) } } }
gpl-3.0
e111440fa7de26153ec3f32b550da806
36.173077
126
0.752393
4.160388
false
false
false
false
Light-Team/ModPE-IDE-Source
data/src/main/kotlin/com/brackeys/ui/data/converter/ThemeConverter.kt
1
12348
/* * Copyright 2021 Brackeys IDE contributors. * * 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.brackeys.ui.data.converter import androidx.core.graphics.toColorInt import com.brackeys.ui.data.model.themes.ExternalScheme import com.brackeys.ui.data.model.themes.ExternalTheme import com.brackeys.ui.data.storage.database.entity.theme.ThemeEntity import com.brackeys.ui.data.utils.toHexString import com.brackeys.ui.domain.model.themes.ThemeModel import com.brackeys.ui.editorkit.model.ColorScheme import com.brackeys.ui.language.base.model.SyntaxScheme import java.util.* object ThemeConverter { fun toModel(themeEntity: ThemeEntity): ThemeModel { return ThemeModel( uuid = themeEntity.uuid, name = themeEntity.name, author = themeEntity.author, description = themeEntity.description, isExternal = true, colorScheme = ColorScheme( textColor = themeEntity.textColor.toColorInt(), backgroundColor = themeEntity.backgroundColor.toColorInt(), gutterColor = themeEntity.gutterColor.toColorInt(), gutterDividerColor = themeEntity.gutterDividerColor.toColorInt(), gutterCurrentLineNumberColor = themeEntity.gutterCurrentLineNumberColor.toColorInt(), gutterTextColor = themeEntity.gutterTextColor.toColorInt(), selectedLineColor = themeEntity.selectedLineColor.toColorInt(), selectionColor = themeEntity.selectionColor.toColorInt(), suggestionQueryColor = themeEntity.suggestionQueryColor.toColorInt(), findResultBackgroundColor = themeEntity.findResultBackgroundColor.toColorInt(), delimiterBackgroundColor = themeEntity.delimiterBackgroundColor.toColorInt(), syntaxScheme = SyntaxScheme( numberColor = themeEntity.numberColor.toColorInt(), operatorColor = themeEntity.operatorColor.toColorInt(), keywordColor = themeEntity.keywordColor.toColorInt(), typeColor = themeEntity.typeColor.toColorInt(), langConstColor = themeEntity.langConstColor.toColorInt(), preprocessorColor = themeEntity.preprocessorColor.toColorInt(), variableColor = themeEntity.variableColor.toColorInt(), methodColor = themeEntity.methodColor.toColorInt(), stringColor = themeEntity.stringColor.toColorInt(), commentColor = themeEntity.commentColor.toColorInt(), tagColor = themeEntity.tagColor.toColorInt(), tagNameColor = themeEntity.tagNameColor.toColorInt(), attrNameColor = themeEntity.attrNameColor.toColorInt(), attrValueColor = themeEntity.attrValueColor.toColorInt(), entityRefColor = themeEntity.entityRefColor.toColorInt() ) ) ) } fun toEntity(themeModel: ThemeModel): ThemeEntity { return ThemeEntity( uuid = themeModel.uuid, name = themeModel.name, author = themeModel.author, description = themeModel.description, textColor = themeModel.colorScheme.textColor.toHexString(), backgroundColor = themeModel.colorScheme.backgroundColor.toHexString(), gutterColor = themeModel.colorScheme.gutterColor.toHexString(), gutterDividerColor = themeModel.colorScheme.gutterDividerColor.toHexString(), gutterCurrentLineNumberColor = themeModel.colorScheme.gutterCurrentLineNumberColor.toHexString(), gutterTextColor = themeModel.colorScheme.gutterTextColor.toHexString(), selectedLineColor = themeModel.colorScheme.selectedLineColor.toHexString(), selectionColor = themeModel.colorScheme.selectionColor.toHexString(), suggestionQueryColor = themeModel.colorScheme.suggestionQueryColor.toHexString(), findResultBackgroundColor = themeModel.colorScheme.findResultBackgroundColor.toHexString(), delimiterBackgroundColor = themeModel.colorScheme.delimiterBackgroundColor.toHexString(), numberColor = themeModel.colorScheme.syntaxScheme.numberColor.toHexString(), operatorColor = themeModel.colorScheme.syntaxScheme.operatorColor.toHexString(), keywordColor = themeModel.colorScheme.syntaxScheme.keywordColor.toHexString(), typeColor = themeModel.colorScheme.syntaxScheme.typeColor.toHexString(), langConstColor = themeModel.colorScheme.syntaxScheme.langConstColor.toHexString(), preprocessorColor = themeModel.colorScheme.syntaxScheme.preprocessorColor.toHexString(), variableColor = themeModel.colorScheme.syntaxScheme.variableColor.toHexString(), methodColor = themeModel.colorScheme.syntaxScheme.methodColor.toHexString(), stringColor = themeModel.colorScheme.syntaxScheme.stringColor.toHexString(), commentColor = themeModel.colorScheme.syntaxScheme.commentColor.toHexString(), tagColor = themeModel.colorScheme.syntaxScheme.tagColor.toHexString(), tagNameColor = themeModel.colorScheme.syntaxScheme.tagNameColor.toHexString(), attrNameColor = themeModel.colorScheme.syntaxScheme.attrNameColor.toHexString(), attrValueColor = themeModel.colorScheme.syntaxScheme.attrValueColor.toHexString(), entityRefColor = themeModel.colorScheme.syntaxScheme.entityRefColor.toHexString() ) } fun toExternalTheme(themeModel: ThemeModel): ExternalTheme { return ExternalTheme( uuid = themeModel.uuid, name = themeModel.name, author = themeModel.author, description = themeModel.description, externalScheme = ExternalScheme( textColor = themeModel.colorScheme.textColor.toHexString(), backgroundColor = themeModel.colorScheme.backgroundColor.toHexString(), gutterColor = themeModel.colorScheme.gutterColor.toHexString(), gutterDividerColor = themeModel.colorScheme.gutterDividerColor.toHexString(), gutterCurrentLineNumberColor = themeModel.colorScheme.gutterCurrentLineNumberColor.toHexString(), gutterTextColor = themeModel.colorScheme.gutterTextColor.toHexString(), selectedLineColor = themeModel.colorScheme.selectedLineColor.toHexString(), selectionColor = themeModel.colorScheme.selectionColor.toHexString(), suggestionQueryColor = themeModel.colorScheme.suggestionQueryColor.toHexString(), findResultBackgroundColor = themeModel.colorScheme.findResultBackgroundColor.toHexString(), delimiterBackgroundColor = themeModel.colorScheme.delimiterBackgroundColor.toHexString(), numberColor = themeModel.colorScheme.syntaxScheme.numberColor.toHexString(), operatorColor = themeModel.colorScheme.syntaxScheme.operatorColor.toHexString(), keywordColor = themeModel.colorScheme.syntaxScheme.keywordColor.toHexString(), typeColor = themeModel.colorScheme.syntaxScheme.typeColor.toHexString(), langConstColor = themeModel.colorScheme.syntaxScheme.langConstColor.toHexString(), preprocessorColor = themeModel.colorScheme.syntaxScheme.preprocessorColor.toHexString(), variableColor = themeModel.colorScheme.syntaxScheme.variableColor.toHexString(), methodColor = themeModel.colorScheme.syntaxScheme.methodColor.toHexString(), stringColor = themeModel.colorScheme.syntaxScheme.stringColor.toHexString(), commentColor = themeModel.colorScheme.syntaxScheme.commentColor.toHexString(), tagColor = themeModel.colorScheme.syntaxScheme.tagColor.toHexString(), tagNameColor = themeModel.colorScheme.syntaxScheme.tagNameColor.toHexString(), attrNameColor = themeModel.colorScheme.syntaxScheme.attrNameColor.toHexString(), attrValueColor = themeModel.colorScheme.syntaxScheme.attrValueColor.toHexString(), entityRefColor = themeModel.colorScheme.syntaxScheme.entityRefColor.toHexString() ) ) } fun toModel(externalTheme: ExternalTheme?): ThemeModel { return ThemeModel( uuid = externalTheme?.uuid ?: UUID.randomUUID().toString(), name = externalTheme?.name ?: "", author = externalTheme?.author ?: "", description = externalTheme?.description ?: "", isExternal = true, colorScheme = ColorScheme( textColor = (externalTheme?.externalScheme?.textColor ?: "#000000").toColorInt(), backgroundColor = (externalTheme?.externalScheme?.backgroundColor ?: "#000000").toColorInt(), gutterColor = (externalTheme?.externalScheme?.gutterColor ?: "#000000").toColorInt(), gutterDividerColor = (externalTheme?.externalScheme?.gutterDividerColor ?: "#000000").toColorInt(), gutterCurrentLineNumberColor = (externalTheme?.externalScheme?.gutterCurrentLineNumberColor ?: "#000000").toColorInt(), gutterTextColor = (externalTheme?.externalScheme?.gutterTextColor ?: "#000000").toColorInt(), selectedLineColor = (externalTheme?.externalScheme?.selectedLineColor ?: "#000000").toColorInt(), selectionColor = (externalTheme?.externalScheme?.selectionColor ?: "#000000").toColorInt(), suggestionQueryColor = (externalTheme?.externalScheme?.suggestionQueryColor ?: "#000000").toColorInt(), findResultBackgroundColor = (externalTheme?.externalScheme?.findResultBackgroundColor ?: "#000000").toColorInt(), delimiterBackgroundColor = (externalTheme?.externalScheme?.delimiterBackgroundColor ?: "#000000").toColorInt(), syntaxScheme = SyntaxScheme( numberColor = (externalTheme?.externalScheme?.numberColor ?: "#000000").toColorInt(), operatorColor = (externalTheme?.externalScheme?.operatorColor ?: "#000000").toColorInt(), keywordColor = (externalTheme?.externalScheme?.keywordColor ?: "#000000").toColorInt(), typeColor = (externalTheme?.externalScheme?.typeColor ?: "#000000").toColorInt(), langConstColor = (externalTheme?.externalScheme?.langConstColor ?: "#000000").toColorInt(), preprocessorColor = (externalTheme?.externalScheme?.preprocessorColor ?: "#000000").toColorInt(), variableColor = (externalTheme?.externalScheme?.variableColor ?: "#000000").toColorInt(), methodColor = (externalTheme?.externalScheme?.methodColor ?: "#000000").toColorInt(), stringColor = (externalTheme?.externalScheme?.stringColor ?: "#000000").toColorInt(), commentColor = (externalTheme?.externalScheme?.commentColor ?: "#000000").toColorInt(), tagColor = (externalTheme?.externalScheme?.tagColor ?: "#000000").toColorInt(), tagNameColor = (externalTheme?.externalScheme?.tagNameColor ?: "#000000").toColorInt(), attrNameColor = (externalTheme?.externalScheme?.attrNameColor ?: "#000000").toColorInt(), attrValueColor = (externalTheme?.externalScheme?.attrValueColor ?: "#000000").toColorInt(), entityRefColor = (externalTheme?.externalScheme?.entityRefColor ?: "#000000").toColorInt() ) ) ) } }
apache-2.0
0c4fdb064b8735149328acdf81cefc49
66.851648
135
0.681082
6.233216
false
false
false
false
arturbosch/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Metric.kt
2
1698
package io.gitlab.arturbosch.detekt.api /** * Metric type, can be an integer or double value. Internally it is stored as an integer, * but the conversion factor and is double attributes can be used to retrieve it as a double value. */ data class Metric( val type: String, val value: Int, val threshold: Int, val isDouble: Boolean = false, val conversionFactor: Int = DEFAULT_FLOAT_CONVERSION_FACTOR ) { constructor( type: String, value: Double, threshold: Double, conversionFactor: Int = DEFAULT_FLOAT_CONVERSION_FACTOR ) : this( type, value = (value * conversionFactor).toInt(), threshold = (threshold * conversionFactor).toInt(), isDouble = true, conversionFactor = conversionFactor ) /** * Convenient method to retrieve the raised value as a double. * Internally the value is stored as an int with a conversion factor to not loose * any precision in calculations. */ fun doubleValue(): Double = value.convertAsDouble() /** * Specified threshold for this metric as a double value. */ fun doubleThreshold(): Double = threshold.convertAsDouble() private fun Int.convertAsDouble(): Double = if (isDouble) { this.toDouble() / conversionFactor } else { error("This metric was not marked as double!") } override fun toString(): String = if (isDouble) "${doubleValue()}/${doubleThreshold()}" else "$value/$threshold" } /** * To represent a value of 0.5, use the metric value 50 and the conversion factor of 100. (50 / 100 = 0.5) */ const val DEFAULT_FLOAT_CONVERSION_FACTOR: Int = 100
apache-2.0
8c50c592514c5c614e5d0e86d44c288f
31.037736
116
0.64841
4.601626
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/graph/GraphLabel.kt
1
1057
package ch.bailu.aat_gtk.view.graph import ch.bailu.aat_gtk.lib.extensions.setText import ch.bailu.aat_lib.view.graph.LabelInterface import ch.bailu.gtk.gtk.Align import ch.bailu.gtk.gtk.Box import ch.bailu.gtk.gtk.Label import ch.bailu.gtk.gtk.Orientation import ch.bailu.gtk.type.Str class GraphLabel : LabelInterface { val layout = Box(Orientation.VERTICAL, 0) private val labels = HashMap<Int, Label>() init { layout.marginTop = 5 layout.marginEnd = 5 layout.halign = Align.END layout.valign = Align.START } override fun setText(color: Int, text: String) { if (!labels.containsKey(color)) { println(text) val label = Label(Str(text)) label.xalign = 1f layout.append(label) labels[color] = label } else { labels[color]?.apply { this.setText(text) } } } override fun setText(color: Int, text: String, unit: String) { setText(color, "$text [$unit]") } }
gpl-3.0
6b1b46681494185fd2b57b4fc21d34de
25.425
66
0.606433
3.748227
false
false
false
false
nemerosa/ontrack
ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/validation/ThresholdConfig.kt
2
2195
package net.nemerosa.ontrack.extension.general.validation import net.nemerosa.ontrack.model.form.Form import net.nemerosa.ontrack.model.form.YesNo import net.nemerosa.ontrack.model.structure.ValidationRunStatusID import net.nemerosa.ontrack.model.form.Int as IntField data class ThresholdConfig( val warningThreshold: Int?, val failureThreshold: Int?, val okIfGreater: Boolean = true ) { fun computeStatus(value: Int): ValidationRunStatusID = if (okIfGreater) { when { failureThreshold != null && value < failureThreshold -> ValidationRunStatusID.STATUS_FAILED warningThreshold != null && value < warningThreshold -> ValidationRunStatusID.STATUS_WARNING else -> ValidationRunStatusID.STATUS_PASSED } } else { when { failureThreshold != null && value > failureThreshold -> ValidationRunStatusID.STATUS_FAILED warningThreshold != null && value > warningThreshold -> ValidationRunStatusID.STATUS_WARNING else -> ValidationRunStatusID.STATUS_PASSED } } } fun ThresholdConfig?.toForm(): Form = Form.create() .with( IntField.of("warningThreshold") .label("Warning threshold") .help("Percentage to reach before having a warning. Optional.") .optional() .value(this?.warningThreshold) ) .with( IntField.of("failureThreshold") .label("Failure threshold") .help("Percentage to reach before having a failure. Optional.") .optional() .value(this?.failureThreshold) ) .with( YesNo.of("okIfGreater") .label("OK if greater") .value(this?.okIfGreater ?: true) )
mit
2531d8f550e5167a397a1259a279de35
42.039216
112
0.515718
6.253561
false
false
false
false
xiaojinzi123/Component
ComponentImpl/src/main/java/com/xiaojinzi/component/cache/CacheType.kt
1
1435
package com.xiaojinzi.component.cache import android.app.ActivityManager import android.content.Context import com.xiaojinzi.component.support.Utils /** * 构建 [Cache] 时,使用 [CacheType] 中声明的类型,来区分不同的模块 * 从而为不同的模块构建不同的缓存策略 */ interface CacheType { companion object { const val CLASS_CACHE_TYPE_ID = 0 val CLASS_CACHE: CacheType = object : CacheType { private val MAX_SIZE = 25 override val cacheTypeId: Int get() = CLASS_CACHE_TYPE_ID override fun calculateCacheSize(context: Context): Int { Utils.checkNullPointer(context, "context") val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val targetMemoryCacheSize: Int = if (Utils.isLowMemoryDevice(activityManager)) { activityManager.memoryClass / 6 } else { activityManager.memoryClass / 4 } return if (targetMemoryCacheSize > MAX_SIZE) { MAX_SIZE } else targetMemoryCacheSize } } } /** * 返回框架内需要缓存的模块对应的 `id` */ val cacheTypeId: Int /** * 计算对应模块需要的缓存大小 */ fun calculateCacheSize(context: Context): Int }
apache-2.0
870fd490c751b80bcbba65f9a6fc3bc0
26.829787
107
0.593726
4.554007
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/DataConverter.kt
1
5935
package be.florien.anyflow.data import be.florien.anyflow.data.local.model.* import be.florien.anyflow.data.server.model.AmpacheAlbum import be.florien.anyflow.data.server.model.AmpacheArtist import be.florien.anyflow.data.server.model.AmpachePlayList import be.florien.anyflow.data.server.model.AmpacheSong import be.florien.anyflow.data.view.* /** * Server to Database */ fun AmpacheSong.toDbSong() = DbSong( id = id, song = song, title = title, name = name, artistName = artist.name, artistId = artist.id, albumName = album.name, albumId = album.id, albumArtistName = albumartist.name, albumArtistId = albumartist.id, filename = filename, track = track, time = time, year = year, bitrate = bitrate, rate = rate, url = url, art = art, preciserating = preciserating, rating = rating, averagerating = averagerating, composer = composer, genre = genre.joinToString(",") { it.name }, null ) fun AmpacheArtist.toDbArtist() = DbArtist( id = id, name = name, preciserating = preciserating, rating = rating, art = art ) fun AmpacheAlbum.toDbAlbum() = DbAlbum( id = id, name = name, artistName = artist.name, artistId = artist.id, year = year, tracks = tracks, disk = disk, art = art, preciserating = preciserating, rating = rating ) fun AmpachePlayList.toDbPlaylist() = DbPlaylist( id = id, name = name, owner = owner ) /** * Database to view */ fun DbSong.toViewSong() = Song( id = id, title = title, artistName = artistName, albumName = albumName, albumArtistName = albumArtistName, time = time, url = url, art = art, genre = genre ) fun DbSong.toViewSongInfo() = SongInfo( id = id, track = track, title = title, artistName = artistName, artistId = artistId, albumName = albumName, albumId = albumId, albumArtistName = albumArtistName, albumArtistId = albumArtistId, time = time, url = url, art = art, year = year, genre = genre, fileName = filename, local = local ) fun DbSongDisplay.toViewSong() = Song( id = id, title = title, artistName = artistName, albumName = albumName, albumArtistName = albumArtistName, time = time, art = art, url = url, genre = genre ) fun DbFilter.toViewFilter(): Filter<*> = when (clause) { DbFilter.TITLE_IS -> Filter.TitleIs(argument) DbFilter.TITLE_CONTAIN -> Filter.TitleContain(argument) DbFilter.GENRE_IS -> Filter.GenreIs(argument) DbFilter.SONG_ID -> Filter.SongIs(argument.toLong(), displayText, displayImage) DbFilter.ARTIST_ID -> Filter.ArtistIs(argument.toLong(), displayText, displayImage) DbFilter.ALBUM_ARTIST_ID -> Filter.AlbumArtistIs(argument.toLong(), displayText, displayImage) DbFilter.ALBUM_ID -> Filter.AlbumIs(argument.toLong(), displayText, displayImage) DbFilter.PLAYLIST_ID -> Filter.PlaylistIs(argument.toLong(), displayText) DbFilter.DOWNLOADED -> Filter.DownloadedStatusIs(true) DbFilter.NOT_DOWNLOADED -> Filter.DownloadedStatusIs(false) else -> Filter.TitleIs("") } fun DbFilterGroup.toViewFilterGroup() = FilterGroup( id = id, name = name ) fun DbOrder.toViewOrder(): Order { return when (orderingType) { Order.ASCENDING -> Order.Ordered(priority, subject) Order.PRECISE_POSITION -> Order.Precise(orderingArgument, subject, priority) Order.RANDOM -> Order.Random(priority, subject, orderingArgument) else -> Order.Ordered(priority, subject) } } fun DbAlarm.toViewAlarm() = Alarm( id = id, hour = hour, minute = minute, isRepeating = monday || tuesday || wednesday || thursday || friday || saturday || sunday, daysToTrigger = listOf(monday, tuesday, wednesday, thursday, friday, saturday, sunday), active = active ) /** * View to database */ fun Song.toDbSongDisplay() = DbSongDisplay( id = id, title = title, artistName = artistName, albumName = albumName, albumArtistName = albumArtistName, time = time, art = art, url = url, genre = genre ) fun SongInfo.toDbSongToPlay() = DbSongToPlay( id = id, local = local ) fun Filter<*>.toDbFilter(groupId: Long) = DbFilter( id = null, clause = when (this) { is Filter.TitleIs -> DbFilter.TITLE_IS is Filter.TitleContain -> DbFilter.TITLE_CONTAIN is Filter.GenreIs -> DbFilter.GENRE_IS is Filter.Search -> DbFilter.SEARCH is Filter.SongIs -> DbFilter.SONG_ID is Filter.ArtistIs -> DbFilter.ARTIST_ID is Filter.AlbumArtistIs -> DbFilter.ALBUM_ARTIST_ID is Filter.AlbumIs -> DbFilter.ALBUM_ID is Filter.PlaylistIs -> DbFilter.PLAYLIST_ID is Filter.DownloadedStatusIs -> if (this.argument) DbFilter.DOWNLOADED else DbFilter.NOT_DOWNLOADED }, joinClause = when (this) { is Filter.PlaylistIs -> DbFilter.PLAYLIST_ID_JOIN else -> null }, argument = argument.toString(), displayText = displayText, displayImage = displayImage, filterGroup = groupId ) fun FilterGroup.toDbFilterGroup() = DbFilterGroup( id = id, name = name ) fun Order.toDbOrder() = DbOrder( priority = priority, subject = subject, orderingType = ordering, orderingArgument = argument ) fun Alarm.toDbAlarm() = DbAlarm( id = id, hour = hour, minute = minute, active = active, monday = daysToTrigger[0], tuesday = daysToTrigger[1], wednesday = daysToTrigger[2], thursday = daysToTrigger[3], friday = daysToTrigger[4], saturday = daysToTrigger[5], sunday = daysToTrigger[6] ) /** * View to View */ fun SongInfo.toSong() = Song(id = id, title = title, artistName = artistName, albumName = albumName, albumArtistName = albumArtistName, time = time, art = art, url = url, genre = genre)
gpl-3.0
5ce5fd8012e782e51be526f407cf0197
25.14978
185
0.65813
3.977882
false
false
false
false
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/ui/PlaidItemsListExtension.kt
1
4916
/* * Copyright 2019 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("PlaidItemsList") package io.plaidapp.core.ui import io.plaidapp.core.data.PlaidItem import io.plaidapp.core.data.PlaidItemSorting import io.plaidapp.core.designernews.data.stories.model.Story import io.plaidapp.core.designernews.domain.StoryWeigher import io.plaidapp.core.dribbble.data.api.ShotWeigher import io.plaidapp.core.dribbble.data.api.model.Shot import io.plaidapp.core.producthunt.data.ProductHuntSourceItem.Companion.SOURCE_PRODUCT_HUNT import io.plaidapp.core.producthunt.data.api.PostWeigher import io.plaidapp.core.producthunt.data.api.model.Post import java.util.Collections /** * Prepares items for display of de-duplicating items and sorting them (depending on the data * source). */ fun getPlaidItemsForDisplayExpanded( oldItems: List<PlaidItem>, newItems: List<PlaidItem>, columns: Int ): List<PlaidItem> { val itemsToBeDisplayed = getPlaidItemsForDisplay(oldItems, newItems) expandPopularItems(itemsToBeDisplayed, columns) return itemsToBeDisplayed } fun getPlaidItemsForDisplay( oldItems: List<PlaidItem>, newItems: List<PlaidItem> ): List<PlaidItem> { val itemsToBeDisplayed = oldItems.toMutableList() weighItems(newItems.toMutableList()) deduplicateAndAdd(itemsToBeDisplayed, newItems) sort(itemsToBeDisplayed) return itemsToBeDisplayed } fun expandPopularItems(items: List<PlaidItem>, columns: Int) { // for now just expand the first dribbble image per page which should be // the most popular according to our weighing & sorting val expandedPositions = mutableListOf<Int>() var page = -1 items.forEachIndexed { index, item -> if (item is Shot && item.page > page) { item.colspan = columns page = item.page expandedPositions.add(index) } else { item.colspan = 1 } } // make sure that any expanded items are at the start of a row // so that we don't leave any gaps in the grid expandedPositions.indices.forEach { expandedPos -> val pos = expandedPositions[expandedPos] val extraSpannedSpaces = expandedPos * (columns - 1) val rowPosition = (pos + extraSpannedSpaces) % columns if (rowPosition != 0) { val swapWith = pos + (columns - rowPosition) if (swapWith < items.size) { Collections.swap(items, pos, swapWith) } } } } /** * Calculate a 'weight' [0, 1] for each data type for sorting. Each data type/source has a * different metric for weighing it e.g. Dribbble uses likes etc. but some sources should keep * the order returned by the API. Weights are 'scoped' to the page they belong to and lower * weights are sorted earlier in the grid (i.e. in ascending weight). */ private fun weighItems(items: MutableList<out PlaidItem>?) { if (items == null || items.isEmpty()) return // some sources should just use the natural order i.e. as returned by the API as users // have an expectation about the order they appear in items.filter { SOURCE_PRODUCT_HUNT == it.dataSource }.apply { PlaidItemSorting.NaturalOrderWeigher().weigh(this) } // otherwise use our own weight calculation. We prefer this as it leads to a less // regular pattern of items in the grid items.filterIsInstance<Shot>().apply { ShotWeigher().weigh(this) } items.filterIsInstance<Story>().apply { StoryWeigher().weigh(this) } items.filter { it is Post && SOURCE_PRODUCT_HUNT != it.dataSource }.apply { @Suppress("UNCHECKED_CAST") PostWeigher().weigh(this as List<Post>) } } /** * De-dupe as the same item can be returned by multiple feeds */ private fun deduplicateAndAdd(oldItems: MutableList<PlaidItem>, newItems: List<PlaidItem>) { val count = oldItems.count() newItems.forEach { newItem -> var add = true for (i in 0 until count) { val existingItem = oldItems[i] if (newItem == existingItem) { add = false break } } if (add) { oldItems.add(newItem) } } } private fun sort(items: MutableList<out PlaidItem>) { Collections.sort<PlaidItem>(items, PlaidItemSorting.PlaidItemComparator()) // sort by weight }
apache-2.0
27b1d4843a213c0c1a64e62b0035691f
34.366906
96
0.687347
4.198121
false
false
false
false
mockk/mockk
modules/mockk/src/commonMain/kotlin/io/mockk/impl/recording/states/VerifyingState.kt
1
3424
package io.mockk.impl.recording.states import io.mockk.MockKException import io.mockk.MockKGateway.VerificationParameters import io.mockk.MockKGateway.VerificationResult import io.mockk.impl.log.Logger import io.mockk.impl.recording.CommonCallRecorder import io.mockk.impl.stub.Stub import io.mockk.impl.verify.VerificationHelpers class VerifyingState( recorder: CommonCallRecorder, val params: VerificationParameters ) : RecordingState(recorder) { override fun wasNotCalled(list: List<Any>) { addWasNotCalled(list) } override fun recordingDone(): CallRecordingState { checkMissingCalls() val verifier = recorder.factories.verifier(params) val sorter = recorder.factories.verificationCallSorter() sorter.sort(recorder.calls) val outcome = recorder.safeExec { verifier.verify( sorter.regularCalls, params ) } if (outcome.matches) { verifier.captureArguments() } log.trace { "Done verification. Outcome: $outcome" } failIfNotPassed(outcome, params.inverse) markVerified(outcome) checkWasNotCalled(sorter.wasNotCalledCalls.map { it.matcher.self }) return recorder.factories.answeringState(recorder) } private fun checkMissingCalls() { if (recorder.calls.isEmpty()) { throw MockKException("Missing calls inside verify { ... } block.") } } private fun failIfNotPassed(outcome: VerificationResult, inverse: Boolean) { when (outcome) { is VerificationResult.OK -> if (inverse) { val callsReport = VerificationHelpers.formatCalls(outcome.verifiedCalls) throw AssertionError("Inverse verification failed.\n\nVerified calls:\n$callsReport") } is VerificationResult.Failure -> if (!inverse) { throw AssertionError("Verification failed: ${outcome.message}") } } } private fun markVerified(outcome: VerificationResult) { if (outcome is VerificationResult.OK) { for (invocation in outcome.verifiedCalls) { recorder.ack.markCallVerified(invocation) } } } private fun checkWasNotCalled(mocks: List<Any>) { val calledStubs = mutableListOf<Stub>() for (mock in mocks) { val stub = recorder.stubRepo.stubFor(mock) val calls = stub.allRecordedCalls() if (calls.isNotEmpty()) { calledStubs += stub } } if (calledStubs.isNotEmpty()) { if (calledStubs.size == 1) { val calledStub = calledStubs[0] throw AssertionError(recorder.safeExec { "Verification failed: ${calledStub.toStr()} should not be called:\n" + calledStub.allRecordedCalls().joinToString("\n") }) } else { throw AssertionError(recorder.safeExec { "Verification failed: ${calledStubs.joinToString(", ") { it.toStr() }} should not be called:\n" + calledStubs.flatMap { it.allRecordedCalls() }.joinToString("\n") }) } } } companion object { val log = Logger<VerifyingState>() } }
apache-2.0
03b3245f769f296e629cb8d821dfa471
31.609524
117
0.597547
5.04271
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/widget/custom/loading/CircleLoadingLite.kt
1
4214
package com.engineer.imitate.ui.widget.custom.loading import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.Animatable import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.Animation class CircleLoadingLite : View, Animatable, ValueAnimator.AnimatorUpdateListener { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onAttachedToWindow() { super.onAttachedToWindow() startLoading() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() stopLoading() } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) var outR = centerX - lineWidth outR *= mRotateAngle var inR = outR * 0.7f var innR = outR * 0.4f mOuterCircleRectF.set(centerX - outR, centerY - outR, centerX + outR, centerY + outR) mInnerCircleRectF.set(centerX - inR, centerY - inR, centerX + inR, centerY + inR) mInnerCircleRectF1.set(centerX - innR, centerY - innR, centerX + innR, centerY + innR) canvas?.save() canvas?.drawArc(mOuterCircleRectF, 0f, 360f, false, mStrokePaint) canvas?.drawArc(mInnerCircleRectF, 0f, 360f, false, mStrokePaint) canvas?.drawArc(mInnerCircleRectF1, 0f, 360f, false, mStrokePaint) canvas?.restore() } public fun startLoading() { start() } public fun stopLoading() { stop() } override fun onAnimationUpdate(animation: ValueAnimator) { if (animation != null) { mRotateAngle = animation.animatedValue as Float invalidate() } } override fun isRunning(): Boolean { return mFloatValueAnimator.isRunning } override fun start() { if (mFloatValueAnimator.isStarted) { return } mFloatValueAnimator.addUpdateListener(this) mFloatValueAnimator.start() } override fun stop() { mFloatValueAnimator.removeAllUpdateListeners() mFloatValueAnimator.end() } private val ANIMATION_START_DELAY: Long = 200 private val ANIMATION_DURATION: Long = 1000 private val OUTER_CIRCLE_ANGLE = 270.0f private val INTER_CIRCLE_ANGLE = 90.0f private lateinit var mFloatValueAnimator: ValueAnimator private lateinit var mStrokePaint: Paint private lateinit var mOuterCircleRectF: RectF private lateinit var mInnerCircleRectF: RectF private lateinit var mInnerCircleRectF1: RectF private var centerX: Int = 0 private var centerY: Int = 0 private var lineWidth = 10.0f private var mRotateAngle: Float = 0.toFloat() init { initAnimations() initPaint() } private fun initPaint() { mOuterCircleRectF = RectF() mInnerCircleRectF = RectF() mInnerCircleRectF1 = RectF() // mStrokePaint = Paint() mStrokePaint.style = Paint.Style.STROKE mStrokePaint.strokeWidth = lineWidth mStrokePaint.color = Color.RED mStrokePaint.isAntiAlias = true mStrokePaint.strokeCap = Paint.Cap.ROUND mStrokePaint.strokeJoin = Paint.Join.ROUND } private fun initAnimations() { mFloatValueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f) mFloatValueAnimator.repeatCount = Animation.INFINITE mFloatValueAnimator.repeatMode = ValueAnimator.RESTART mFloatValueAnimator.duration = ANIMATION_DURATION mFloatValueAnimator.startDelay = ANIMATION_START_DELAY mFloatValueAnimator.interpolator = AccelerateDecelerateInterpolator() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) centerX = width / 2 centerY = height / 2 } }
apache-2.0
f3136a485853663b1e7f119d0e454d36
27.869863
112
0.679165
4.992891
false
false
false
false
inlacou/VolleyControllerLibrary
volleycontroller/src/main/java/com/libraries/inlacou/volleycontroller/InternetCall.kt
1
9078
package com.libraries.inlacou.volleycontroller import com.android.volley.* import com.android.volley.Response.success import com.libraries.inlacou.volleycontroller.multipart.DataPart import com.libraries.inlacou.volleycontroller.multipart.VolleyMultipartRequest import org.json.JSONObject import timber.log.Timber import java.io.IOException /** * Created by inlacou on 10/09/14. * Last updated by inlacou on 24/10/18. */ class InternetCall { var method: Method = Method.GET private set var code: String = "" private set var url: String? = null private set var headers: MutableMap<String, String> = mutableMapOf() private set var params: MutableMap<String, String> = mutableMapOf() private set var rawBody: String = "" private set var fileKey: String? = null private set var file: File? = null private set var retryPolicy: DefaultRetryPolicy? = null private set var interceptors: MutableList<Interceptor> = mutableListOf() private set var successCallbacks: MutableList<((response: VcResponse, code: String) -> Unit)> = mutableListOf() private set var errorCallbacks: MutableList<((error: VolleyError, code: String) -> Unit)> = mutableListOf() private set var cancelTag: Any? = null private set var allowLocationRedirect: Boolean = true private set init { setRetryPolicy(DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)) } fun setUrl(url: String, urlEncodeSpaces: Boolean = true): InternetCall { return this.apply { this.url = if(urlEncodeSpaces) url.replace(" ", "%20") else url } } fun setFile(key: String, file: File): InternetCall { this.fileKey = key this.file = file return this } fun setRawBody(rawBody: String): InternetCall { this.rawBody = rawBody return this } fun setRawBody(json: JSONObject): InternetCall { putHeader("Content-type", VolleyController.ContentType.JSON.toString()) this.rawBody = json.toString() return this } fun setHeaders(headers: MutableMap<String, String>): InternetCall { this.headers = headers return this } fun setParams(params: MutableMap<String, String>): InternetCall { rawBody = "" this.params = params return this } fun addSuccessCallback(callback: ((item: VcResponse, code: String) -> Unit)): InternetCall { this.successCallbacks.add(callback) return this } fun addErrorCallback(callback: ((error: VolleyError, code: String) -> Unit)): InternetCall { this.errorCallbacks.add(callback) return this } fun setAllowLocationRedirect(b: Boolean): InternetCall { allowLocationRedirect = b return this } fun setCode(code: String): InternetCall { this.code = code return this } fun setMethod(method: Method): InternetCall { this.method = method return this } fun replaceAccessToken(oldAccessToken: String, newAccessToken: String): InternetCall { url?.let { setUrl(it.replace(oldAccessToken, newAccessToken)) } headers.forEach { if(it.value.contains(oldAccessToken)) headers[it.key] = it.value.replace(oldAccessToken, newAccessToken) } params.forEach { if(it.value.contains(oldAccessToken)) headers[it.key] = it.value.replace(oldAccessToken, newAccessToken) } if (rawBody.isNotEmpty() && rawBody.contains(oldAccessToken)) { rawBody = rawBody.replace(oldAccessToken, newAccessToken) } return this } /** * Applies any interceptor present * Should be called before build() */ fun applyInterceptors(){ interceptors.forEach { it.intercept(this) } } fun build(listener: Response.Listener<VcResponse>, errorListener: Response.ErrorListener): Request<*> { val request: Request<*> = if (file == null) { object : CustomRequest(this.method.value(), url, errorListener) { override fun deliverResponse(response: VcResponse) { listener.onResponse(response) } override fun parseNetworkResponse(response: NetworkResponse): Response<VcResponse> { val newCustomResponse = VcResponse(response) newCustomResponse.code = code //we set here the response (the object received by deliverResponse); return success(newCustomResponse, newCustomResponse.chacheHeaders) } @Throws(AuthFailureError::class) override fun getHeaders(): Map<String, String>? { return [email protected] } override fun getParams(): Map<String, String>? { return [email protected] } @Throws(AuthFailureError::class) override fun getBody(): ByteArray { val body = [email protected] if (body.isNotEmpty()) { return body.toByteArray() } return super.getBody() ?: "".toByteArray() } } } else { object : VolleyMultipartRequest(method.value(), url, errorListener) { override fun deliverResponse(response: Any?) { listener.onResponse(response as VcResponse) } override fun parseNetworkResponse(response: NetworkResponse): Response<Any?> { val newCustomResponse = VcResponse(response) newCustomResponse.code = code //we set here the response (the object received by deliverResponse); return success(newCustomResponse, newCustomResponse.chacheHeaders) } override fun getParams(): Map<String, String> { return [email protected] } override fun getByteData(): Map<String, DataPart> { val byteData = mutableMapOf<String, DataPart>() // file name could found file base or direct access from real path // for now just get bitmap data from ImageView try { fileKey?.let { byteData[it] = DataPart(file?.name + "." + file?.format, ImageUtils.getFileDataFromBitmap(ImageUtils.getBitmapFromPath(file?.location)), file?.type.toString() + "/" + file?.format) } } catch (e: IOException) { e.printStackTrace() } byteData.forEach { Timber.v("${[email protected]} byteData -> ${it.key}: ${it.value}") } return byteData } } } request.retryPolicy = retryPolicy if (cancelTag != null) request.tag = cancelTag return request } fun setRetryPolicy(retryPolicy: DefaultRetryPolicy): InternetCall { this.retryPolicy = retryPolicy return this } fun addInterceptors(interceptors: List<Interceptor>): InternetCall { this.interceptors.addAll(interceptors) return this } fun putInterceptors(interceptors: List<Interceptor>): InternetCall { this.interceptors.clear() this.interceptors.addAll(interceptors) return this } /** * Alias for putInterceptors */ fun setInterceptors(interceptors: List<Interceptor>): InternetCall { return putInterceptors(interceptors) } fun addInterceptor(interceptor: Interceptor?): InternetCall { if (interceptor == null) { return this } this.interceptors.add(interceptor) return this } fun putHeader(key: String, value: String): InternetCall { headers[key] = value return this } fun putParam(key: String, value: String?): InternetCall { if (value == null) { return this } rawBody = "" params[key] = value return this } fun putHeaders(headers: Map<String, String>?): InternetCall { if (headers == null) { return this } this.headers.putAll(headers) return this } fun putParams(params: MutableMap<String, String>): InternetCall { this.params.clear() rawBody = "" this.params.putAll(params) return this } fun addParams(params: MutableMap<String, String>): InternetCall { rawBody = "" this.params.putAll(params) return this } fun setCancelTag(tag: Any): InternetCall { this.cancelTag = tag return this } fun get(){ setMethod(Method.GET) } fun post(){ setMethod(Method.POST) } fun put(){ setMethod(Method.PUT) } fun delete(){ setMethod(Method.DELETE) } enum class Method { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, TRACE; internal fun value(): Int { return when (this) { GET -> Request.Method.GET POST -> Request.Method.POST PUT -> Request.Method.PUT DELETE -> Request.Method.DELETE PATCH -> Request.Method.PATCH HEAD -> Request.Method.HEAD OPTIONS -> Request.Method.OPTIONS TRACE -> Request.Method.TRACE } } override fun toString(): String { return when (this) { GET -> "GET" POST -> "POST" PUT -> "PUT" DELETE -> "DELETE" PATCH -> "PATCH" HEAD -> "HEAD" OPTIONS -> "OPTIONS" TRACE -> "TRACE" } } } fun toPostmanString(): String { var result = "" result += "Method: $method\n" result += "Code: $code\n" result += "URL: $url\n" if(headers.isNotEmpty()) { result += "headers:\n" headers.forEach { result += "\t${it.key}: ${it.value}\n" } }else{ result += "headers: none\n" } if(params.isNotEmpty()) { result += "params:\n" params.forEach { result += "\t${it.key}: ${it.value}\n" } }else{ result += "params: none\n" } if(rawBody.isNotEmpty()) { result += "body:\n" result += rawBody }else{ result += "body: none\n" } file?.let { result += "file: ${file?.location}\n" } return result } interface Interceptor { /** * @param internetCall */ fun intercept(internetCall: InternetCall) } }
gpl-3.0
b58e54396b5078cbff4e045bbd881e7a
24.357542
203
0.693655
3.581065
false
false
false
false
ShikiEiki/GFTools
app/src/main/java/com/gftools/MainActivity.kt
1
7139
package com.gftools import android.app.Activity import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.databinding.DataBindingUtil import android.graphics.Bitmap import android.hardware.display.DisplayManager import android.hardware.display.VirtualDisplay import android.media.Image import android.media.ImageReader import android.media.projection.MediaProjection import android.media.projection.MediaProjectionManager import android.os.Bundle import android.os.IBinder import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import com.gftools.databinding.ActivityMainBinding import com.gftools.utils.* import java.io.* class MainActivity : BaseActivity() { companion object Static{ lateinit var mMediaProjection : MediaProjection lateinit var mVirturlDisplay : VirtualDisplay lateinit var mImgReader : ImageReader lateinit var activityInstance : MainActivity fun startCapture() : Bitmap{ var image : Image = mImgReader.acquireLatestImage() var pixelStride = image.planes[0].pixelStride var rowStride = image.planes[0].rowStride var rowPadding = rowStride - pixelStride * image.width var mBitmap = Bitmap.createBitmap(image.width + rowPadding / pixelStride , image.height , Bitmap.Config.ARGB_8888) mBitmap.copyPixelsFromBuffer(image.planes[0].buffer) mBitmap = Bitmap.createBitmap(mBitmap , 0 , 0 , image.width , image.height) image.close() return mBitmap } } lateinit var mMediaProjectionManager : MediaProjectionManager lateinit var binding : ActivityMainBinding lateinit var mainService : MainService var serviceConnection = object : ServiceConnection{ override fun onServiceDisconnected(name: ComponentName?) { showToastAndLv("绑定服务失败") finish() } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { if (service is MainService.MyBinder){ showToastAndLv("绑定服务成功") mainService = service.getService() mainService.mainActivity = this@MainActivity mainService.setStatusListener(object : MainService.OnStatusChangedListener{ override fun onStatusChanged(status: Int) { showToastAndLv("onStatusCHanged " + status) mHandler.post(object : Runnable { override fun run() { showToastAndLv("here" + status) when(status){ 0 -> { binding.mainBtn.text = "开始脚本" } 1 -> { binding.mainBtn.text = "停止脚本" } } } }) } override fun reportCurrentAction(action: String) { } }) return } showToastAndLv("绑定未知的服务") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityInstance = this binding = DataBindingUtil.inflate<ActivityMainBinding>(LayoutInflater.from(this) , R.layout.activity_main , null , false) setContentView(binding.root) binding.mainBtn.text = "开始脚本" bindService(Intent(this , MainService::class.java) , serviceConnection , Context.BIND_AUTO_CREATE) sendCaptureIntent(10086) } fun onMainBtnClick(view: View){ if (binding.mainBtn.text.equals("开始脚本")){ startScript() } else if (binding.mainBtn.text.equals("停止脚本")){ stopScript() } } fun startScript(){ mainService.startScript() } fun stopScript(){ mainService.stopScript() } fun onConfigBtnClick(view: View){ openActivity(ConfigActivity::class.java) } fun onDebugBtn1Click(view: View){ openActivity(TestActivity::class.java) } fun onDebugBtn2Click(view: View){ } lateinit var process : Process lateinit var dataOutputStream : DataOutputStream fun onDebugBtn3Click(view: View){ process = Runtime.getRuntime().exec("su") dataOutputStream = DataOutputStream(process.outputStream) object : Thread(){ override fun run() { } } .start() } fun test(){ launchGF() waitSecond(5) var bitmapCompare = BaseBitmapCompare(startCapture()) bitmapCompare.isCorrectTeamSelected(3) } fun sendCaptureIntent(requestCode: Int) { lv("sendCaptureIntent") mMediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent() , requestCode) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { lv("onActivityResult requestCode : " + requestCode + " resultCode : " + resultCode + " data" + data) super.onActivityResult(requestCode, resultCode, data) when(requestCode){ 10086,10010 -> { if (resultCode != Activity.RESULT_OK){ lv("获取授权错误,错误码 : " + resultCode) showToast("获取授权错误,错误码 : " + resultCode) return } mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data) setUpVirturlDisplay() lv("开始录屏成功") // when (requestCode) { // 10086 -> { // var intent = Intent(this@MainActivity, MainService::class.java) // intent.putExtra("function", "start") // startService(intent) // } // 10010 -> { // test() // } // } } } } private fun setUpVirturlDisplay(){ var metrics : DisplayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(metrics) var mScreenWidth = metrics.widthPixels var mScreenHeight = metrics.heightPixels var mScreenDensity = metrics.densityDpi mImgReader = ImageReader.newInstance(mScreenWidth , mScreenHeight , 0x1 , 2) mVirturlDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture" , mScreenWidth , mScreenHeight , mScreenDensity , DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR , mImgReader.surface , null , null) } }
apache-2.0
630fce30c8a950a8d9b979ef88b67cb0
36.682796
129
0.594093
5.350382
false
false
false
false
bozaro/git-as-svn
src/test/kotlin/svnserver/repository/git/prop/GitEolTest.kt
1
7158
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository.git.prop import org.eclipse.jgit.attributes.Attributes import org.eclipse.jgit.attributes.AttributesRule import org.eclipse.jgit.lib.FileMode import org.testng.Assert import org.testng.annotations.DataProvider import org.testng.annotations.Test import org.tmatesoft.svn.core.SVNProperty import org.tmatesoft.svn.core.internal.wc.SVNFileUtil import svnserver.TestHelper import svnserver.repository.git.RepositoryFormat import svnserver.repository.git.prop.GitAttributesFactory.EolType import java.util.* /** * Tests for GitAttributes. * * @author Artem V. Navrotskiy <[email protected]> */ class GitEolTest { @DataProvider fun eolTypeV5Data(): Array<Array<out Any>> { return arrayOf( arrayOf("", EolType.Autodetect), arrayOf("crlf", EolType.Native), // Be careful here arrayOf("-crlf", EolType.Binary), arrayOf("crlf=input", EolType.LF), arrayOf("eol=lf", EolType.LF), arrayOf("eol=crlf", EolType.CRLF), arrayOf("eol=lf text=auto", EolType.Autodetect), arrayOf("eol=crlf text=auto", EolType.Autodetect), arrayOf("text", EolType.Native), arrayOf("-text", EolType.Binary), arrayOf("text=auto", EolType.Autodetect), // invalid values arrayOf("crlf=invalid", EolType.Autodetect), arrayOf("eol=invalid", EolType.Autodetect), arrayOf("eol", EolType.Autodetect), arrayOf("text=invalid", EolType.Autodetect), ) } @Test(dataProvider = "eolTypeV5Data") fun eolTypeV5(rule: String, expected: EolType) { val attrs = Attributes(*AttributesRule("", rule).attributes.toTypedArray()) val actual = GitAttributesFactory.getEolTypeV5(attrs) Assert.assertEquals(actual, expected) } @DataProvider fun eolTypeV4Data(): Array<Array<out Any>> { return arrayOf( arrayOf("", EolType.Autodetect), arrayOf("eol=lf", EolType.LF), arrayOf("eol=crlf", EolType.CRLF), arrayOf("text", EolType.Native), arrayOf("-text", EolType.Binary), arrayOf("text=auto", EolType.Native), // invalid values arrayOf("eol=invalid", EolType.Autodetect), arrayOf("eol", EolType.Autodetect), arrayOf("text=invalid", EolType.Native), ) } @Test(dataProvider = "eolTypeV4Data") fun eolTypeV4(rule: String, expected: EolType) { val attrs = Attributes(*AttributesRule("", rule).attributes.toTypedArray()) val actual = GitAttributesFactory.getEolTypeV4(attrs) Assert.assertEquals(actual, expected) } @Test(dataProvider = "parseAttributesData") fun parseAttributes(params: Params) { params.check() } class Params internal constructor(private val attr: Array<GitProperty>, private val path: String) { private val expected = TreeMap<String, String>() fun prop(key: String, value: String): Params { expected[key] = value return this } override fun toString(): String { return path } fun check() { val gitProperties = createForPath(attr, path) val svnProperties = HashMap<String, String>() for (prop in gitProperties) { prop.apply(svnProperties) } for ((key, value) in expected) { Assert.assertEquals(svnProperties[key], value, key) } for ((key, value) in svnProperties) { Assert.assertEquals(value, expected[key], key) } } } companion object { @JvmStatic @DataProvider(name = "parseAttributesData") fun parseAttributesData(): Array<Array<out Any>> { val attr: Array<GitProperty> TestHelper.asStream( """ # comment * text *.txt text *.md eol=lf *.dat -text 3.md -text *.bin binary 1.bin text 2.bin text """.trimIndent() ).use { `in` -> attr = GitAttributesFactory().create(`in`, RepositoryFormat.Latest) } val params = arrayOf( Params(attr, "/").prop( SVNProperty.INHERITABLE_AUTO_PROPS, """ *.txt = svn:eol-style=native *.md = svn:eol-style=LF *.dat = svn:mime-type=application/octet-stream 3.md = svn:mime-type=application/octet-stream *.bin = svn:mime-type=application/octet-stream 1.bin = svn:eol-style=native 2.bin = svn:eol-style=native """.trimIndent() ), Params(attr, "README.md").prop(SVNProperty.EOL_STYLE, SVNProperty.EOL_STYLE_LF), Params(attr, "foo.dat").prop(SVNProperty.MIME_TYPE, SVNFileUtil.BINARY_MIME_TYPE), Params(attr, "foo.txt").prop(SVNProperty.EOL_STYLE, SVNProperty.EOL_STYLE_NATIVE), Params(attr, "foo.bin").prop(SVNProperty.MIME_TYPE, SVNFileUtil.BINARY_MIME_TYPE), Params(attr, "1.bin").prop(SVNProperty.EOL_STYLE, SVNProperty.EOL_STYLE_NATIVE), Params(attr, "2.bin").prop(SVNProperty.EOL_STYLE, SVNProperty.EOL_STYLE_NATIVE), Params(attr, "3.md").prop(SVNProperty.MIME_TYPE, SVNFileUtil.BINARY_MIME_TYPE), Params(attr, "changelog").prop(SVNProperty.EOL_STYLE, SVNProperty.EOL_STYLE_NATIVE) ) return params.map { arrayOf(it) }.toTypedArray() } private fun createForPath(baseProps: Array<GitProperty>, path: String): Array<GitProperty> { var props = baseProps val pathItems = path.split("/".toRegex()).toTypedArray() for (i in pathItems.indices) { val name = pathItems[i] if (name.isNotEmpty()) { val mode = if (i == pathItems.size - 1) FileMode.REGULAR_FILE else FileMode.TREE props = createForChild(props, name, mode) } } return props } private fun createForChild(props: Array<GitProperty>, name: String, mode: FileMode): Array<GitProperty> { val result = arrayOfNulls<GitProperty>(props.size) var count = 0 for (prop in props) { val child = prop.createForChild(name, mode) if (child != null) { result[count++] = child } } return Arrays.copyOf(result, count) } } }
gpl-2.0
11f74df0c481c03e2ce4b10f8668967c
36.873016
113
0.583263
4.482154
false
true
false
false
thatJavaNerd/JRAW
lib/src/main/kotlin/net/dean/jraw/databind/NullAwareEnumAdapters.kt
1
3147
package net.dean.jraw.databind import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import net.dean.jraw.models.DistinguishedStatus import net.dean.jraw.models.VoteDirection /** * A NullAwareEnumAdapter is a special JsonAdapter for enums that represent exactly one of its values in JSON as null. * For example, reddit uses "true" for an upvote, "false" for a downvote, and null for no vote. This class takes care of * handling that special case where the value is null and delegates the reset of the work to [read] and [write]. */ sealed class NullAwareEnumAdapter<T : Enum<T>> : JsonAdapter<T>() { /** @inheritDoc */ final override fun fromJson(reader: JsonReader): T { if (reader.peek() == JsonReader.Token.NULL) { reader.nextNull<T>() return nullValue } return read(reader) } /** @inheritDoc */ final override fun toJson(writer: JsonWriter, value: T?) { if (value == nullValue) { writer.nullValue() } else { write(writer, value!!) } } /** The special enum value that is represented as null in the JSON structure */ protected abstract val nullValue: T /** Reads a T from the reader. This T can be any value in the enumeration besides [nullValue]. */ protected abstract fun read(reader: JsonReader): T /** Writes a T to its JSON representation. `value` is guaranteed not to be equal to [nullValue]. */ protected abstract fun write(writer: JsonWriter, value: T) } /** * Handles reading and writing VoteDirections. reddit represents an upvote with "true", a downvote with "false", and no * vote with a null value. */ class VoteDirectionAdapter : NullAwareEnumAdapter<VoteDirection>() { override val nullValue: VoteDirection = VoteDirection.NONE override fun read(reader: JsonReader): VoteDirection { return if (reader.nextBoolean()) VoteDirection.UP else VoteDirection.DOWN } override fun write(writer: JsonWriter, value: VoteDirection) { when (value) { VoteDirection.UP -> writer.value(true) VoteDirection.DOWN -> writer.value(false) else -> throw IllegalStateException("Unknown vote direction: $value") } } } /** * Handles reading and writing DistinguishedStatuses. [DistinguishedStatus.NORMAL] is represented by a null value in * JSON while every other value is represented as the lowercase name. For example, [DistinguishedStatus.ADMIN] is * represented in JSON as the string "admin". */ class DistinguishedStatusAdapter : NullAwareEnumAdapter<DistinguishedStatus>() { override val nullValue: DistinguishedStatus = DistinguishedStatus.NORMAL override fun read(reader: JsonReader): DistinguishedStatus { val value = reader.nextString() return if (value == "gold-auto") DistinguishedStatus.GOLD else DistinguishedStatus.valueOf(value.toUpperCase()) } override fun write(writer: JsonWriter, value: DistinguishedStatus) { writer.value(value.name.toLowerCase()) } }
mit
09df14b570cd24ec770bb1f85a3831bf
36.915663
120
0.692088
4.621145
false
false
false
false
karollewandowski/aem-intellij-plugin
src/main/kotlin/co/nums/intellij/aem/settings/SetAemVersionNotifier.kt
1
2808
package co.nums.intellij.aem.settings import co.nums.intellij.aem.icons.AemIcons import co.nums.intellij.aem.messages.AemPluginBundle import co.nums.intellij.aem.service.jcrRoots import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.* import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity private const val VERSION_NOTIFICATION_DISABLED_PROPERTY_NAME = "aem-intellij-plugin.notifications.version.disabled" class SetAemVersionNotifier : StartupActivity { private val aemPluginNotifications = NotificationGroup("AEM IntelliJ Plugin", NotificationDisplayType.STICKY_BALLOON, false) override fun runActivity(project: Project) { if (project.jcrRoots?.isEmpty() != true && notificationNotShownYet(project)) { showVersionNotification(project) } } private fun notificationNotShownYet(project: Project) = !PropertiesComponent.getInstance(project).getBoolean(VERSION_NOTIFICATION_DISABLED_PROPERTY_NAME) private fun showVersionNotification(project: Project) { val notification = aemPluginNotifications.createNotification( AemPluginBundle.message("plugin.name"), AemPluginBundle.message("notification.aem.version.text", project.aemSettings?.aemVersion), NotificationType.INFORMATION, null) notification .setIcon(AemIcons.AEM_LOGO) .setImportant(true) .addAction(OpenSettings(project, notification)) .addAction(SuppressNotification(project, notification)) .notify(project) } } private class OpenSettings(private val project: Project, private val notification: Notification) : AnAction(AemPluginBundle.message("notification.aem.version.action.change")) { override fun actionPerformed(event: AnActionEvent?) { project.disableVersionNotification() notification.expire() ApplicationManager.getApplication().invokeLater { ShowSettingsUtil.getInstance().showSettingsDialog(project, AemPluginBundle.message("plugin.name")) } } } private class SuppressNotification(private val project: Project, private val notification: Notification) : AnAction(AemPluginBundle.message("notification.action.do.not.show.again")) { override fun actionPerformed(event: AnActionEvent?) { project.disableVersionNotification() notification.expire() } } private fun Project.disableVersionNotification() = PropertiesComponent.getInstance(this).setValue(VERSION_NOTIFICATION_DISABLED_PROPERTY_NAME, true)
gpl-3.0
a5da5d6cc99ee29061d74de02fcc8c76
40.910448
183
0.741809
5.032258
false
false
false
false
oldergod/red
app/src/main/java/com/benoitquenaudon/tvfoot/red/app/domain/matches/MatchesAdapter.kt
1
7156
package com.benoitquenaudon.tvfoot.red.app.domain.matches import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DiffUtil.DiffResult import com.benoitquenaudon.tvfoot.red.R import com.benoitquenaudon.tvfoot.red.app.common.schedulers.BaseSchedulerProvider import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesItemViewHolder.LoadingRowViewHolder import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesItemViewHolder.MatchHeaderViewHolder import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesItemViewHolder.MatchRowViewHolder import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesItemViewHolder.MatchTeamlessRowViewHolder import com.benoitquenaudon.tvfoot.red.app.domain.matches.displayable.HeaderRowDisplayable import com.benoitquenaudon.tvfoot.red.app.domain.matches.displayable.LoadingRowDisplayable import com.benoitquenaudon.tvfoot.red.app.domain.matches.displayable.MatchRowDisplayable import com.benoitquenaudon.tvfoot.red.app.domain.matches.displayable.MatchesItemDisplayable import com.benoitquenaudon.tvfoot.red.app.domain.matches.displayable.MatchesItemDisplayableDiffUtilCallback import com.benoitquenaudon.tvfoot.red.databinding.MatchesRowHeaderBinding import com.benoitquenaudon.tvfoot.red.databinding.MatchesRowMatchBinding import com.benoitquenaudon.tvfoot.red.databinding.MatchesRowTeamlessMatchBinding import com.benoitquenaudon.tvfoot.red.databinding.RowLoadingBinding import com.benoitquenaudon.tvfoot.red.injection.scope.ActivityScope import com.benoitquenaudon.tvfoot.red.util.DataVersion import com.benoitquenaudon.tvfoot.red.util.errorHandlingSubscribe import io.reactivex.disposables.Disposable import io.reactivex.subjects.PublishSubject import javax.inject.Inject @ActivityScope class MatchesAdapter @Inject constructor( private val schedulerProvider: BaseSchedulerProvider ) : androidx.recyclerview.widget.RecyclerView.Adapter<MatchesItemViewHolder<*, *>>() { private var matchesItems = emptyList<MatchesItemDisplayable>() private val matchesObservable: PublishSubject<Triple<List<MatchesItemDisplayable>, List<MatchesItemDisplayable>, DataVersion>> = PublishSubject.create() val matchRowClickObservable: PublishSubject<MatchRowDisplayable> = PublishSubject.create() init { // calling it to enable subscription processItemDiffs() } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): MatchesItemViewHolder<*, *> { val layoutInflater = LayoutInflater.from(parent.context) val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, viewType, parent, false) return when (viewType) { R.layout.matches_row_header -> MatchHeaderViewHolder(binding as MatchesRowHeaderBinding) R.layout.matches_row_match -> MatchRowViewHolder(binding as MatchesRowMatchBinding, this) R.layout.matches_row_teamless_match -> MatchTeamlessRowViewHolder(binding as MatchesRowTeamlessMatchBinding, this) R.layout.row_loading -> LoadingRowViewHolder(binding as RowLoadingBinding) else -> throw UnsupportedOperationException( "don't know how to deal with this viewType: " + viewType ) } } override fun onBindViewHolder( holder: MatchesItemViewHolder<*, *>, position: Int ) { val item: MatchesItemDisplayable = matchesItems[position] return when (holder) { is MatchHeaderViewHolder -> { if (item is HeaderRowDisplayable) { holder.bind(item) } else { throw IllegalStateException("Wrong item for MatchHeaderViewHolder $item") } } is MatchRowViewHolder -> { if (item is MatchRowDisplayable) { holder.bind(item) } else { throw IllegalStateException("Wrong item for MatchRowViewHolder $item") } } is MatchTeamlessRowViewHolder -> { if (item is MatchRowDisplayable) { holder.bind(item) } else { throw IllegalStateException("Wrong item for MatchTeamlessRowViewHolder $item") } } is LoadingRowViewHolder -> { if (item == LoadingRowDisplayable) { holder.bind(LoadingRowDisplayable) } else { throw IllegalStateException("Wrong item for LoadingRowViewHolder $item") } } } } override fun onViewRecycled(holder: MatchesItemViewHolder<*, *>) { holder.unbind() super.onViewRecycled(holder) } override fun getItemCount(): Int { return matchesItems.size } override fun getItemViewType(position: Int): Int = matchesItems[position].let { item -> when (item) { is MatchRowDisplayable -> if (item.homeTeam.name.isNullOrEmpty()) { R.layout.matches_row_teamless_match } else { R.layout.matches_row_match } is HeaderRowDisplayable -> R.layout.matches_row_header LoadingRowDisplayable -> R.layout.row_loading else -> throw UnsupportedOperationException( "Don't know how to deal with this item: $matchesItems[position]" ) } } fun onClick(match: MatchRowDisplayable) { matchRowClickObservable.onNext(match) } // each time data is set, we update this variable so that if DiffUtil calculation returns // after repetitive updates, we can ignore the old calculation private var dataVersion = 0 fun setMatchesItems(newItems: List<MatchesItemDisplayable>) { dataVersion++ when { matchesItems.isEmpty() -> { if (newItems.isEmpty()) return matchesItems = newItems notifyDataSetChanged() } newItems.isEmpty() -> { val oldSize = matchesItems.size matchesItems = newItems notifyItemRangeRemoved(0, oldSize) } else -> matchesObservable.onNext(Triple(matchesItems, newItems, dataVersion)) } } private fun processItemDiffs(): Disposable = matchesObservable .observeOn(schedulerProvider.computation()) .scan(Triple(emptyList(), null, 0)) { _: Triple<List<MatchesItemDisplayable>, DiffResult?, DataVersion>, (oldItems, newItems, startVersion) -> Triple( newItems, DiffUtil.calculateDiff( MatchesItemDisplayableDiffUtilCallback(oldItems, newItems), true ), startVersion ) } .skip(1) .observeOn(schedulerProvider.ui()) .errorHandlingSubscribe { (newItems, diffResult, startVersion) -> if (startVersion != dataVersion) { // ignore update return@errorHandlingSubscribe } matchesItems = newItems diffResult?.dispatchUpdatesTo(this) } fun closestHeaderPosition(position: Int): Int { if (position < 0) throw IllegalStateException("should have a header") return matchesItems[position].let { if (it is HeaderRowDisplayable) position else closestHeaderPosition(position - 1) } } }
apache-2.0
e126995e2479c5b1aa9e2b9661e65980
37.26738
130
0.721213
5.057244
false
false
false
false
android/health-samples
health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/data/HealthConnectManager.kt
1
22949
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.healthconnectsample.data import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.res.Resources.NotFoundException import android.os.Build import androidx.activity.result.contract.ActivityResultContract import androidx.compose.runtime.mutableStateOf import androidx.health.connect.client.HealthConnectClient import androidx.health.connect.client.PermissionController import androidx.health.connect.client.changes.Change import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.DistanceRecord import androidx.health.connect.client.records.ExerciseEventRecord import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.HeartRateRecord import androidx.health.connect.client.records.Record import androidx.health.connect.client.records.SleepSessionRecord import androidx.health.connect.client.records.SleepStageRecord import androidx.health.connect.client.records.SpeedRecord import androidx.health.connect.client.records.StepsRecord import androidx.health.connect.client.records.TotalCaloriesBurnedRecord import androidx.health.connect.client.records.WeightRecord import androidx.health.connect.client.records.metadata.DataOrigin import androidx.health.connect.client.request.AggregateRequest import androidx.health.connect.client.request.ChangesTokenRequest import androidx.health.connect.client.request.ReadRecordsRequest import androidx.health.connect.client.time.TimeRangeFilter import androidx.health.connect.client.units.Energy import androidx.health.connect.client.units.Length import androidx.health.connect.client.units.Mass import androidx.health.connect.client.units.Velocity import com.example.healthconnectsample.R import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import java.io.IOException import java.time.Instant import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import kotlin.random.Random import kotlin.reflect.KClass // The minimum android level that can use Health Connect const val MIN_SUPPORTED_SDK = Build.VERSION_CODES.O_MR1 /** * Demonstrates reading and writing from Health Connect. */ class HealthConnectManager(private val context: Context) { private val healthConnectClient by lazy { HealthConnectClient.getOrCreate(context) } val healthConnectCompatibleApps by lazy { val intent = Intent("androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE") // This call is deprecated in API level 33, however, this app targets a lower level. @Suppress("DEPRECATION") val packages = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL ) packages.associate { val icon = try { context.packageManager.getApplicationIcon(it.activityInfo.packageName) } catch(e: NotFoundException) { null } val label = context.packageManager.getApplicationLabel(it.activityInfo.applicationInfo) .toString() it.activityInfo.packageName to HealthConnectAppInfo( packageName = it.activityInfo.packageName, icon = icon, appLabel = label ) } } var availability = mutableStateOf(HealthConnectAvailability.NOT_SUPPORTED) private set init { checkAvailability() } fun checkAvailability() { availability.value = when { HealthConnectClient.isAvailable(context) -> HealthConnectAvailability.INSTALLED isSupported() -> HealthConnectAvailability.NOT_INSTALLED else -> HealthConnectAvailability.NOT_SUPPORTED } } /** * Determines whether all the specified permissions are already granted. It is recommended to * call [PermissionController.getGrantedPermissions] first in the permissions flow, as if the * permissions are already granted then there is no need to request permissions via * [PermissionController.createRequestPermissionResultContract]. */ suspend fun hasAllPermissions(permissions: Set<HealthPermission>): Boolean { return permissions == healthConnectClient.permissionController.getGrantedPermissions( permissions ) } fun requestPermissionsActivityContract(): ActivityResultContract<Set<HealthPermission>, Set<HealthPermission>> { return PermissionController.createRequestPermissionResultContract() } /** * Obtains a list of [ExerciseSessionRecord]s in a specified time frame. An Exercise Session Record is a * period of time given to an activity, that would make sense to a user, e.g. "Afternoon run" * etc. It does not necessarily mean, however, that the user was *running* for that entire time, * more that conceptually, this was the activity being undertaken. */ suspend fun readExerciseSessions(start: Instant, end: Instant): List<ExerciseSessionRecord> { val request = ReadRecordsRequest( recordType = ExerciseSessionRecord::class, timeRangeFilter = TimeRangeFilter.between(start, end) ) val response = healthConnectClient.readRecords(request) return response.records } /** * Writes an [ExerciseSessionRecord] to Health Connect, and additionally writes underlying data for * the session too, such as [StepsRecord], [DistanceRecord] etc. */ suspend fun writeExerciseSession(start: ZonedDateTime, end: ZonedDateTime) { healthConnectClient.insertRecords( listOf( ExerciseSessionRecord( startTime = start.toInstant(), startZoneOffset = start.offset, endTime = end.toInstant(), endZoneOffset = end.offset, exerciseType = ExerciseSessionRecord.ExerciseType.RUNNING, title = "My Run #${Random.nextInt(0, 60)}" ), StepsRecord( startTime = start.toInstant(), startZoneOffset = start.offset, endTime = end.toInstant(), endZoneOffset = end.offset, count = (1000 + 1000 * Random.nextInt(3)).toLong() ), // Mark a 5 minute pause during the workout ExerciseEventRecord( startTime = start.toInstant().plus(10, ChronoUnit.MINUTES), startZoneOffset = start.offset, endTime = start.toInstant().plus(15, ChronoUnit.MINUTES), endZoneOffset = end.offset, eventType = ExerciseEventRecord.EventType.PAUSE ), DistanceRecord( startTime = start.toInstant(), startZoneOffset = start.offset, endTime = end.toInstant(), endZoneOffset = end.offset, distance = Length.meters((1000 + 100 * Random.nextInt(20)).toDouble()) ), TotalCaloriesBurnedRecord( startTime = start.toInstant(), startZoneOffset = start.offset, endTime = end.toInstant(), endZoneOffset = end.offset, energy = Energy.calories((140 + Random.nextInt(20)) * 0.01) ) ) + buildHeartRateSeries(start, end) + buildSpeedSeries(start, end) ) } /** * Deletes an [ExerciseSessionRecord] and underlying data. */ suspend fun deleteExerciseSession(uid: String) { val exerciseSession = healthConnectClient.readRecord(ExerciseSessionRecord::class, uid) healthConnectClient.deleteRecords( ExerciseSessionRecord::class, recordIdsList = listOf(uid), clientRecordIdsList = emptyList() ) val timeRangeFilter = TimeRangeFilter.between( exerciseSession.record.startTime, exerciseSession.record.endTime ) val rawDataTypes: Set<KClass<out Record>> = setOf( HeartRateRecord::class, SpeedRecord::class, DistanceRecord::class, StepsRecord::class, TotalCaloriesBurnedRecord::class, ExerciseEventRecord::class ) rawDataTypes.forEach { rawType -> healthConnectClient.deleteRecords(rawType, timeRangeFilter) } } /** * Reads aggregated data and raw data for selected data types, for a given [ExerciseSessionRecord]. */ suspend fun readAssociatedSessionData( uid: String ): ExerciseSessionData { val exerciseSession = healthConnectClient.readRecord(ExerciseSessionRecord::class, uid) // Use the start time and end time from the session, for reading raw and aggregate data. val timeRangeFilter = TimeRangeFilter.between( startTime = exerciseSession.record.startTime, endTime = exerciseSession.record.endTime ) val aggregateDataTypes = setOf( ExerciseSessionRecord.ACTIVE_TIME_TOTAL, StepsRecord.COUNT_TOTAL, DistanceRecord.DISTANCE_TOTAL, TotalCaloriesBurnedRecord.ENERGY_TOTAL, HeartRateRecord.BPM_AVG, HeartRateRecord.BPM_MAX, HeartRateRecord.BPM_MIN, SpeedRecord.SPEED_AVG, SpeedRecord.SPEED_MAX, SpeedRecord.SPEED_MIN ) // Limit the data read to just the application that wrote the session. This may or may not // be desirable depending on the use case: In some cases, it may be useful to combine with // data written by other apps. val dataOriginFilter = setOf(exerciseSession.record.metadata.dataOrigin) val aggregateRequest = AggregateRequest( metrics = aggregateDataTypes, timeRangeFilter = timeRangeFilter, dataOriginFilter = dataOriginFilter ) val aggregateData = healthConnectClient.aggregate(aggregateRequest) val speedData = readData<SpeedRecord>(timeRangeFilter, dataOriginFilter) val heartRateData = readData<HeartRateRecord>(timeRangeFilter, dataOriginFilter) return ExerciseSessionData( uid = uid, totalActiveTime = aggregateData[ExerciseSessionRecord.ACTIVE_TIME_TOTAL], totalSteps = aggregateData[StepsRecord.COUNT_TOTAL], totalDistance = aggregateData[DistanceRecord.DISTANCE_TOTAL], totalEnergyBurned = aggregateData[TotalCaloriesBurnedRecord.ENERGY_TOTAL], minHeartRate = aggregateData[HeartRateRecord.BPM_MIN], maxHeartRate = aggregateData[HeartRateRecord.BPM_MAX], avgHeartRate = aggregateData[HeartRateRecord.BPM_AVG], heartRateSeries = heartRateData, speedRecord = speedData, minSpeed = aggregateData[SpeedRecord.SPEED_MIN], maxSpeed = aggregateData[SpeedRecord.SPEED_MAX], avgSpeed = aggregateData[SpeedRecord.SPEED_AVG], ) } /** * Deletes all existing sleep data. */ suspend fun deleteAllSleepData() { val now = Instant.now() healthConnectClient.deleteRecords(SleepStageRecord::class, TimeRangeFilter.before(now)) healthConnectClient.deleteRecords(SleepSessionRecord::class, TimeRangeFilter.before(now)) } /** * Generates a week's worth of sleep data using both a [SleepSessionRecord] to describe the overall * period of sleep, and additionally multiple [SleepStageRecord] periods which cover the entire * [SleepSessionRecord]. For the purposes of this sample, the sleep stage data is generated randomly. */ suspend fun generateSleepData() { val records = mutableListOf<Record>() // Make yesterday the last day of the sleep data val lastDay = ZonedDateTime.now().minusDays(1).truncatedTo(ChronoUnit.DAYS) val notes = context.resources.getStringArray(R.array.sleep_notes_array) // Create 7 days-worth of sleep data for (i in 0..7) { val wakeUp = lastDay.minusDays(i.toLong()) .withHour(Random.nextInt(7, 10)) .withMinute(Random.nextInt(0, 60)) val bedtime = wakeUp.minusDays(1) .withHour(Random.nextInt(19, 22)) .withMinute(Random.nextInt(0, 60)) val sleepSession = SleepSessionRecord( notes = notes[Random.nextInt(0, notes.size)], startTime = bedtime.toInstant(), startZoneOffset = bedtime.offset, endTime = wakeUp.toInstant(), endZoneOffset = wakeUp.offset ) val sleepStages = generateSleepStages(bedtime, wakeUp) records.add(sleepSession) records.addAll(sleepStages) } healthConnectClient.insertRecords(records) } /** * Reads sleep sessions for the previous seven days (from yesterday) to show a week's worth of * sleep data. * * In addition to reading [SleepSessionRecord]s, for each session, the duration is calculated to * demonstrate aggregation, and the underlying [SleepStageRecord] data is also read. */ suspend fun readSleepSessions(): List<SleepSessionData> { val lastDay = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS) .minusDays(1) .withHour(12) val firstDay = lastDay .minusDays(7) val sessions = mutableListOf<SleepSessionData>() val sleepSessionRequest = ReadRecordsRequest( recordType = SleepSessionRecord::class, timeRangeFilter = TimeRangeFilter.between(firstDay.toInstant(), lastDay.toInstant()), ascendingOrder = false ) val sleepSessions = healthConnectClient.readRecords(sleepSessionRequest) sleepSessions.records.forEach { session -> val sessionTimeFilter = TimeRangeFilter.between(session.startTime, session.endTime) val durationAggregateRequest = AggregateRequest( metrics = setOf(SleepSessionRecord.SLEEP_DURATION_TOTAL), timeRangeFilter = sessionTimeFilter ) val aggregateResponse = healthConnectClient.aggregate(durationAggregateRequest) val stagesRequest = ReadRecordsRequest( recordType = SleepStageRecord::class, timeRangeFilter = sessionTimeFilter ) val stagesResponse = healthConnectClient.readRecords(stagesRequest) sessions.add( SleepSessionData( uid = session.metadata.id, title = session.title, notes = session.notes, startTime = session.startTime, startZoneOffset = session.startZoneOffset, endTime = session.endTime, endZoneOffset = session.endZoneOffset, duration = aggregateResponse[SleepSessionRecord.SLEEP_DURATION_TOTAL], stages = stagesResponse.records ) ) } return sessions } /** * Writes [WeightRecord] to Health Connect. */ suspend fun writeWeightInput(weight: WeightRecord) { val records = listOf(weight) healthConnectClient.insertRecords(records) } /** * Reads in existing [WeightRecord]s. */ suspend fun readWeightInputs(start: Instant, end: Instant): List<WeightRecord> { val request = ReadRecordsRequest( recordType = WeightRecord::class, timeRangeFilter = TimeRangeFilter.between(start, end) ) val response = healthConnectClient.readRecords(request) return response.records } /** * Returns the weekly average of [WeightRecord]s. */ suspend fun computeWeeklyAverage(start: Instant, end: Instant): Mass? { val request = AggregateRequest( metrics = setOf(WeightRecord.WEIGHT_AVG), timeRangeFilter = TimeRangeFilter.between(start, end) ) val response = healthConnectClient.aggregate(request) return response[WeightRecord.WEIGHT_AVG] } /** * Deletes a [WeightRecord]s. */ suspend fun deleteWeightInput(uid: String) { healthConnectClient.deleteRecords( WeightRecord::class, recordIdsList = listOf(uid), clientRecordIdsList = emptyList() ) } /** * Obtains a changes token for the specified record types. */ suspend fun getChangesToken(dataTypes: Set<KClass<out Record>>): String { val request = ChangesTokenRequest(dataTypes) return healthConnectClient.getChangesToken(request) } /** * Creates a [Flow] of change messages, using a changes token as a start point. The flow will * terminate when no more changes are available, and the final message will contain the next * changes token to use. */ suspend fun getChanges(token: String): Flow<ChangesMessage> = flow { var nextChangesToken = token do { val response = healthConnectClient.getChanges(nextChangesToken) if (response.changesTokenExpired) { // As described here: https://developer.android.com/guide/health-and-fitness/health-connect/data-and-data-types/differential-changes-api // tokens are only valid for 30 days. It is important to check whether the token has // expired. As well as ensuring there is a fallback to using the token (for example // importing data since a certain date), more importantly, the app should ensure // that the changes API is used sufficiently regularly that tokens do not expire. throw IOException("Changes token has expired") } emit(ChangesMessage.ChangeList(response.changes)) nextChangesToken = response.nextChangesToken } while (response.hasMore) emit(ChangesMessage.NoMoreChanges(nextChangesToken)) } /** * Creates a random list of sleep stages that spans the specified [start] to [end] time. */ private fun generateSleepStages( start: ZonedDateTime, end: ZonedDateTime ): List<SleepStageRecord> { val sleepStages = mutableListOf<SleepStageRecord>() var stageStart = start while (stageStart < end) { val stageEnd = stageStart.plusMinutes(Random.nextLong(30, 120)) val checkedEnd = if (stageEnd > end) end else stageEnd sleepStages.add( SleepStageRecord( stage = randomSleepStage(), startTime = stageStart.toInstant(), startZoneOffset = stageStart.offset, endTime = checkedEnd.toInstant(), endZoneOffset = checkedEnd.offset ) ) stageStart = checkedEnd } return sleepStages } /** * Convenience function to reuse code for reading data. */ private suspend inline fun <reified T : Record> readData( timeRangeFilter: TimeRangeFilter, dataOriginFilter: Set<DataOrigin> = setOf() ): List<T> { val request = ReadRecordsRequest( recordType = T::class, dataOriginFilter = dataOriginFilter, timeRangeFilter = timeRangeFilter ) return healthConnectClient.readRecords(request).records } private fun buildHeartRateSeries( sessionStartTime: ZonedDateTime, sessionEndTime: ZonedDateTime ): HeartRateRecord { val samples = mutableListOf<HeartRateRecord.Sample>() var time = sessionStartTime while (time.isBefore(sessionEndTime)) { samples.add( HeartRateRecord.Sample( time = time.toInstant(), beatsPerMinute = (80 + Random.nextInt(80)).toLong() ) ) time = time.plusSeconds(30) } return HeartRateRecord( startTime = sessionStartTime.toInstant(), startZoneOffset = sessionStartTime.offset, endTime = sessionEndTime.toInstant(), endZoneOffset = sessionEndTime.offset, samples = samples ) } private fun buildSpeedSeries( sessionStartTime: ZonedDateTime, sessionEndTime: ZonedDateTime ) = SpeedRecord( startTime = sessionStartTime.toInstant(), startZoneOffset = sessionStartTime.offset, endTime = sessionEndTime.toInstant(), endZoneOffset = sessionEndTime.offset, samples = listOf( SpeedRecord.Sample( time = sessionStartTime.toInstant(), speed = Velocity.metersPerSecond(2.5) ), SpeedRecord.Sample( time = sessionStartTime.toInstant().plus(5, ChronoUnit.MINUTES), speed = Velocity.metersPerSecond(2.7) ), SpeedRecord.Sample( time = sessionStartTime.toInstant().plus(10, ChronoUnit.MINUTES), speed = Velocity.metersPerSecond(2.9) ) ) ) private fun isSupported() = Build.VERSION.SDK_INT >= MIN_SUPPORTED_SDK // Represents the two types of messages that can be sent in a Changes flow. sealed class ChangesMessage { data class NoMoreChanges(val nextChangesToken: String) : ChangesMessage() data class ChangeList(val changes: List<Change>) : ChangesMessage() } } /** * Health Connect requires that the underlying Healthcore APK is installed on the device. * [HealthConnectAvailability] represents whether this APK is indeed installed, whether it is not * installed but supported on the device, or whether the device is not supported (based on Android * version). */ enum class HealthConnectAvailability { INSTALLED, NOT_INSTALLED, NOT_SUPPORTED }
apache-2.0
840a002aaebf2bdea8bf715038d5a703
41.419593
152
0.649266
5.427862
false
false
false
false
dtarnawczyk/modernlrs
src/main/org/lrs/kmodernlrs/domain/Score.kt
1
279
package org.lrs.kmodernlrs.domain import java.io.Serializable data class Score( var scaled: Double? = null, var raw: Double? = null, var min: Double? = null, var max: Double? = null ) : Serializable { companion object { private val serialVersionUID:Long = 1 } }
apache-2.0
bbae7eb9df339f30ee1bfab6bdc6f161
17.666667
39
0.688172
3.244186
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/HomeGsrBuildingAdapter.kt
1
2817
package com.pennapps.labs.pennmobile.adapters import android.content.Context import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentTransaction import androidx.recyclerview.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentManager import com.pennapps.labs.pennmobile.GsrTabbedFragment import com.pennapps.labs.pennmobile.R import kotlinx.android.synthetic.main.home_gsr_building.view.* class HomeGsrBuildingAdapter(private var buildings: ArrayList<String>) : RecyclerView.Adapter<HomeGsrBuildingAdapter.HomeGsrBuildingViewHolder>() { private lateinit var mContext: Context override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeGsrBuildingViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.home_gsr_building, parent, false) mContext = parent.context return HomeGsrBuildingViewHolder(view) } override fun onBindViewHolder(holder: HomeGsrBuildingViewHolder, position: Int) { val building = buildings[position] holder.itemView.home_gsr_building_tv.text = building holder.itemView.home_gsr_building_iv if (building == "Huntsman Hall") { holder.itemView.home_gsr_building_iv.setImageResource(R.drawable.huntsman) } else { holder.itemView.home_gsr_building_iv.setImageResource(R.drawable.weigle) } holder.itemView.setOnClickListener { fragmentTransact(GsrTabbedFragment(), false) } } override fun getItemCount(): Int { return buildings.size } inner class HomeGsrBuildingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val view = itemView } private fun fragmentTransact(fragment: Fragment?, popBackStack: Boolean) { if (fragment != null) { if (mContext is FragmentActivity) { try { val activity = mContext as FragmentActivity val fragmentManager = activity.supportFragmentManager if (popBackStack) { fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) } fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .addToBackStack("Main Activity") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit() } catch (e: IllegalStateException) { Log.e("HomeAdapter", e.toString()) } } } } }
mit
43e47c43d0b3b7a0f5c616424093b8a9
37.60274
105
0.663827
5.131148
false
false
false
false
exponent/exponent
packages/expo-barcode-scanner/android/src/main/java/expo/modules/barcodescanner/utils/ImageDimensions.kt
2
356
package expo.modules.barcodescanner.utils data class ImageDimensions( private val innerWidth: Int, private val innerHeight: Int, val rotation: Int = 0, val facing: Int = -1 ) { private val isLandscape = rotation % 180 == 90 val width = if (isLandscape) innerHeight else innerWidth val height = if (isLandscape) innerWidth else innerHeight }
bsd-3-clause
5300a50a5ddc0f67b126e0fe9fb72d23
28.666667
59
0.738764
4.091954
false
false
false
false
salRoid/Filmy
app/src/main/java/tech/salroid/filmy/ui/activities/FullCrewActivity.kt
1
2230
package tech.salroid.filmy.ui.activities import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceManager import androidx.recyclerview.widget.LinearLayoutManager import tech.salroid.filmy.R import tech.salroid.filmy.data.local.model.Crew import tech.salroid.filmy.databinding.ActivityFullCastBinding import tech.salroid.filmy.ui.adapters.CrewAdapter class FullCrewActivity : AppCompatActivity() { private var nightMode = false private lateinit var binding: ActivityFullCastBinding override fun onCreate(savedInstanceState: Bundle?) { val sp = PreferenceManager.getDefaultSharedPreferences(this) nightMode = sp.getBoolean("dark", false) if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base) super.onCreate(savedInstanceState) binding = ActivityFullCastBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) binding.fullCastRecycler.layoutManager = LinearLayoutManager(this@FullCrewActivity) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = intent.getStringExtra("toolbar_title") val crewList = intent?.getSerializableExtra("crew_list") as? ArrayList<Crew> val fullCrewAdapter = crewList?.let { CrewAdapter(it, false) { crewMember, _, _ -> val intent = Intent(this, CharacterDetailsActivity::class.java) intent.putExtra("id", crewMember.id.toString()) startActivity(intent) } } binding.fullCastRecycler.adapter = fullCrewAdapter } override fun onResume() { super.onResume() val sp = PreferenceManager.getDefaultSharedPreferences(this) val nightModeNew = sp.getBoolean("dark", false) if (nightMode != nightModeNew) recreate() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } }
apache-2.0
1c026a901f7503f4acd57a58456b7427
36.183333
96
0.701345
4.966592
false
false
false
false
donglua/GithubContributionsWidget
app/src/main/kotlin/org/droiders/githubwidget/data/ContributionsProvider.kt
1
1758
package org.droiders.githubwidget.data import android.content.ContentProvider import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE import android.net.Uri import org.droiders.githubwidget.data.DBHelper.Companion.TABLE_NAME /** * ContributionsProvider * * Created by donglua on 2016/12/28. */ class ContributionsProvider : ContentProvider() { var db: SQLiteDatabase? = null override fun onCreate(): Boolean { db = DBHelper(context).getDb() return true } override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? { return db?.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder) } override fun getType(uri: Uri): String? { return null } override fun insert(uri: Uri, values: ContentValues?): Uri? { val row = db?.insertWithOnConflict(TABLE_NAME, null, values, CONFLICT_REPLACE)!! if (row > 0) context.contentResolver.notifyChange(uri, null) return uri } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { val count = db?.delete(TABLE_NAME, selection, selectionArgs) ?:0 if(count > 0) context.contentResolver.notifyChange(uri, null) return count } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { val count = db?.update(TABLE_NAME, values, selection, selectionArgs)!! if (count > 0) context.contentResolver.notifyChange(uri, null) return count } }
apache-2.0
a811250e13f0b325d0520134baa7a626
28.79661
115
0.69397
4.308824
false
false
false
false
TeamWizardry/LibrarianLib
modules/glitter/src/test/kotlin/com/teamwizardry/librarianlib/glitter/test/systems/WorldLitSystem.kt
1
2213
package com.teamwizardry.librarianlib.glitter.test.systems import com.teamwizardry.librarianlib.glitter.bindings.ConstantBinding import com.teamwizardry.librarianlib.glitter.modules.BasicPhysicsUpdateModule import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderModule import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderOptions import net.minecraft.entity.Entity import net.minecraft.util.Identifier object WorldLitSystem : TestSystem(Identifier("liblib-glitter-test:world_lit")) { override fun configure() { val position = bind(3) val previousPosition = bind(3) val velocity = bind(3) updateModules.add( BasicPhysicsUpdateModule( position = position, previousPosition = previousPosition, velocity = velocity, enableCollision = true, gravity = ConstantBinding(0.02), bounciness = ConstantBinding(0.8), friction = ConstantBinding(0.02), damping = ConstantBinding(0.01) ) ) renderModules.add( SpriteRenderModule.build( SpriteRenderOptions.build(Identifier("minecraft", "textures/item/snowball.png")) .worldLight(true) .build(), position, ) .previousPosition(previousPosition) .size(0.25) .build() ) } override fun spawn(player: Entity) { val eyePos = player.getCameraPosVec(1f) val look = player.rotationVector val spawnDistance = 2 val spawnVelocity = 0.2 this.addParticle( 200, // position eyePos.x + look.x * spawnDistance, eyePos.y + look.y * spawnDistance, eyePos.z + look.z * spawnDistance, // previous position eyePos.x + look.x * spawnDistance, eyePos.y + look.y * spawnDistance, eyePos.z + look.z * spawnDistance, // velocity look.x * spawnVelocity, look.y * spawnVelocity, look.z * spawnVelocity, ) } }
lgpl-3.0
bd1b8feea828776cf919982a5a03664c
33.061538
96
0.586534
5.006787
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/String.kt
3
4358
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import androidx.compose.ui.text.intl.Locale import androidx.compose.ui.text.intl.LocaleList import androidx.compose.ui.text.intl.PlatformLocale import androidx.compose.ui.text.platform.ActualStringDelegate /** * Interface for providing platform dependent string related operations. */ internal interface PlatformStringDelegate { /** * Implementation must return uppercase transformed String. * * @param string an input string * @param locale a locale object * @return a transformed string */ fun toUpperCase(string: String, locale: PlatformLocale): String /** * Implementation must return lowercase transformed String. * * @param string an input string * @param locale a locale object * @return a transformed string */ fun toLowerCase(string: String, locale: PlatformLocale): String /** * Implementation must return capitalized String. * * @param string an input string * @param locale a locale object * @return a transformed string */ fun capitalize(string: String, locale: PlatformLocale): String /** * Implementation must return decapitalized String. * * @param string an input string * @param locale a locale object * @return a transformed string */ fun decapitalize(string: String, locale: PlatformLocale): String } /** * Returns uppercase transformed String. * * @param locale a locale object * @return a transformed text */ fun String.toUpperCase(locale: Locale): String = stringDelegate.toUpperCase(this, locale.platformLocale) /** * Returns lowercase transformed String. * * @param locale a locale object * @return a transformed text */ fun String.toLowerCase(locale: Locale): String = stringDelegate.toLowerCase(this, locale.platformLocale) /** * Returns capitalized String. * * @param locale a locale object * @return a transformed text */ fun String.capitalize(locale: Locale): String = stringDelegate.capitalize(this, locale.platformLocale) /** * Returns decapitalized String. * * @param locale a locale object * @return a transformed text */ fun String.decapitalize(locale: Locale): String = stringDelegate.decapitalize(this, locale.platformLocale) /** * Returns uppercase transformed String. * * @param localeList a locale list object. If empty locale list object is passed, use current locale * instead. * @return a transformed text */ fun String.toUpperCase(localeList: LocaleList): String = if (localeList.isEmpty()) toUpperCase(Locale.current) else toUpperCase(localeList[0]) /** * Returns lowercase transformed String. * * @param localeList a locale list object. If empty locale list object is passed, use current locale * instead. * @return a transformed text */ fun String.toLowerCase(localeList: LocaleList): String = if (localeList.isEmpty()) toLowerCase(Locale.current) else toLowerCase(localeList[0]) /** * Returns capitalized String. * * @param localeList a locale list object. If empty locale list object is passed, use current locale * instead. * @return a transformed text */ fun String.capitalize(localeList: LocaleList): String = if (localeList.isEmpty()) capitalize(Locale.current) else capitalize(localeList[0]) /** * Returns decapitalized String. * * @param localeList a locale list object. If empty locale list object is passed, use current locale * instead. */ fun String.decapitalize(localeList: LocaleList): String = if (localeList.isEmpty()) decapitalize(Locale.current) else decapitalize(localeList[0]) private val stringDelegate = ActualStringDelegate()
apache-2.0
f9636f79f15843434d1c349591a68da6
30.586957
100
0.715925
4.516062
false
false
false
false
advantys/workflowgen-templates
integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/android/app/src/main/java/com/workflowgenexample/modules/CodeGenerator.kt
1
1371
package com.workflowgenexample.modules import android.util.Base64 import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import java.security.MessageDigest import java.security.SecureRandom import java.util.* class CodeGenerator constructor( reactContext: ReactApplicationContext ) : ReactContextBaseJavaModule(reactContext) { override fun getName() = "CodeGenerator" @ReactMethod @Suppress("UNUSED") fun generateUUID(promise: Promise) = promise.resolve(UUID.randomUUID().toString()) @ReactMethod @Suppress("UNUSED") fun generateCodeVerifier(promise: Promise) { val sr = SecureRandom() val code = ByteArray(size = 32) sr.nextBytes(code) promise.resolve(Base64.encodeToString(code, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)) } @ReactMethod @Suppress("UNUSED") fun generateCodeChallenge(codeVerifier: String, promise: Promise) { val bytes = codeVerifier.toByteArray(charset = Charsets.US_ASCII) val md = MessageDigest.getInstance("SHA-256") md.update(bytes, 0, bytes.size) promise.resolve(Base64.encodeToString(md.digest(), Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)) } }
mit
667fe845abcb30f0fcc5529ba67fe0b9
33.3
115
0.737418
4.218462
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/widgets/ExtendedEditTextView.kt
1
3256
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.views.widgets import android.support.v7.widget.* import android.text.* import android.view.* import android.view.inputmethod.* import com.commonsense.android.kotlin.views.extensions.* /** * Created by kasper on 10/07/2017. */ class ExtendedEditTextView : AppCompatEditText { constructor(context: android.content.Context) : super(context) { afterInit() } constructor(context: android.content.Context, attrs: android.util.AttributeSet) : super(context, attrs) { afterInit() } constructor(context: android.content.Context, attrs: android.util.AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { afterInit() } private fun afterInit() { } private val internalListOfListeners = mutableListOf<TextWatcher>() private var backspaceDetectedCallback: ((view: ExtendedEditTextView, isEmpty: Boolean) -> Unit)? = null fun setTextChangeListener(listener: TextWatcher) { clearTextChangeListeners() addTextChangedListener(listener) internalListOfListeners.add(listener) } fun clearTextChangeListeners() { internalListOfListeners.forEach { super.removeTextChangedListener(it) } internalListOfListeners.clear() } override fun removeTextChangedListener(watcher: TextWatcher?) { super.removeTextChangedListener(watcher) internalListOfListeners.remove(watcher) } override fun onCreateInputConnection(outAttrs: EditorInfo?): InputConnection { if (outAttrs == null) { throw RuntimeException("Bad editor info supplied;" + "\n You have properly added the focusAble attribute to this view in the xml), just remove it. " + "\n (reason for throwing: super call will fail with unhelpful exception in android code.)") } return KeyboardConnection(super.onCreateInputConnection(outAttrs), true, this::onKeyboardEvent) } //TODO listen for custom sequences ? (hmm ) would avoid opening this func. private fun onKeyboardEvent(event: KeyEvent): Boolean { if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_DEL) { backspaceDetectedCallback?.invoke(this, isEmpty) } return false } fun setOnBackSpaceDetected(callback: (view: ExtendedEditTextView, isEmpty: Boolean) -> Unit) { backspaceDetectedCallback = callback } //hardware keyboard override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (event != null && onKeyboardEvent(event)) { return true } return super.onKeyDown(keyCode, event) } } typealias onKeyboardEvent = (KeyEvent) -> Boolean private class KeyboardConnection(target: InputConnection, mutable: Boolean, val callback: onKeyboardEvent) : InputConnectionWrapper(target, mutable) { override fun sendKeyEvent(event: KeyEvent?): Boolean { if (event != null && callback(event)) { return true } return super.sendKeyEvent(event) } }
mit
99e3cfe792b181f5111ffd7263813877
32.57732
142
0.674754
4.911011
false
false
false
false
0x1bad1d3a/Kaku
app/src/main/java/ca/fuwafuwa/kaku/TutorialFragment.kt
2
5962
package ca.fuwafuwa.kaku import android.net.Uri import android.os.Bundle import android.util.Log import android.view.* import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.Button import android.widget.LinearLayout import android.widget.VideoView import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import ca.fuwafuwa.kaku.Dialogs.TutorialExplainDialogFragment class TutorialFragment : Fragment() { private lateinit var mRootView : View private lateinit var mVideoView : VideoView private lateinit var mButtonLayout : LinearLayout private lateinit var mExplainButton: Button private var mPos : Int = -1 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mRootView = inflater.inflate(R.layout.fragment_tutorial, container, false) mVideoView = mRootView.findViewById(R.id.instruction_video_view) as VideoView mButtonLayout = mRootView.findViewById(R.id.tutorial_buttons) as LinearLayout mExplainButton = mRootView.findViewById(R.id.tutorial_button_explain) mPos = arguments?.getInt(ARG_SECTION_NUMBER)!! mExplainButton.setOnClickListener { getExplainDialogForFragment(mPos).show(fragmentManager!!, "ExplainDialog$mPos") } Log.d(TAG, "onCreateView $mPos") return mRootView } override fun onStart() { super.onStart() mButtonLayout.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { val drawableHeight = mButtonLayout.y.toInt() val params = LinearLayout.LayoutParams(WRAP_CONTENT, drawableHeight - dpToPx(context!!, 20)) params.gravity = Gravity.CENTER_HORIZONTAL params.setMargins(0, dpToPx(context!!, 20), 0, 0) mVideoView.layoutParams = params mVideoView.requestLayout() mButtonLayout.viewTreeObserver.removeOnGlobalLayoutListener(this) } }) } override fun onResume() { super.onResume() mVideoView.setVideoURI(Uri.parse("android.resource://ca.fuwafuwa.kaku/${getVideoForSectionNumber(mPos)}")) mVideoView.setOnPreparedListener { it.isLooping = true } mVideoView.start() } private fun getExplainDialogForFragment(num: Int) : DialogFragment { return TutorialExplainDialogFragment.newInstance(getTitleTextForSectionNumber(num), getTextForSectionNumber(num)) } private fun getVideoForSectionNumber(num: Int): Int { when (num){ 1 -> return R.raw.tut1 2 -> return R.raw.tut2 3 -> return R.raw.tut3 4 -> return R.raw.tut4 5 -> return R.raw.tut5 6 -> return R.raw.tut6 7 -> return R.raw.tut7 8 -> return R.raw.tut8 9 -> return R.raw.tut9 } return 0 } private fun getTitleTextForSectionNumber(num: Int): String { when (num){ 1 -> return "BASIC USAGE" 2 -> return "INSTANT MODE" 3 -> return "QUICK IMAGE ACTION - FILTER" 4 -> return "QUICK TEXT ACTION - SWAP" 5 -> return "QUICK TEXT ACTION - EDIT" 6 -> return "QUICK TEXT ACTION - DELETE" 7 -> return "SEND TO GOOGLE TRANSLATE" 8 -> return "NOTIFICATION CONTROLS" 9 -> return "SELECT TO LOOKUP" } return "" } private fun getTextForSectionNumber(num: Int): String { when (num){ 1 -> return "Drag the capture window to move the window. Drag the bottom right corner to resize. Double tap to start OCR and recognize text. Tip: resize area is inside the capture window." 2 -> return "If instant mode is turned on in the settings and the capture window is fairly small, OCR will start immediately. This mode was intended to recognize words, not sentences." 3 -> return "If the background of the text you want to recognize is translucent, you can try adjusting the image filter settings by doing a long press, then dragging left or right. Note: image filter setting must be turned on." 4 -> return "Sometimes Kaku misrecognizes the kanji but can be easily corrected. Perform a quick swipe downward on the kanji for possible alternate recognitions." 5 -> return "In the case that the correct kanji was not present in the swap quick action, perform a quick swipe to the upper-left to manually input the kanji. For manual correction, you must have a handwriting keyboard installed - for example, Gboard w/ Japanese Handwriting by Google." 6 -> return "If you need to delete any extraneous characters, swipe to the upper right. For all text quick actions, the swipe direction may be reversed in instant mode when there is not enough screen space." 7 -> return "Tap and hold on any kanji to copy recognized text to the clipboard. If you have \"Tap to Translate\" enabled in the Google Translate app, that will also be brought up." 8 -> return "Quickly show/hide Kaku or change Kaku's settings through the notification." 9 -> return "In the case that you can select the text and don't need OCR, simply select the text and send it to Kaku to bring up the dictionary." } return "" } companion object { private val TAG = TutorialFragment::class.java.name private val ARG_SECTION_NUMBER = "section_number" fun newInstance(sectionNumber: Int): TutorialFragment { val fragment = TutorialFragment() val args = Bundle() args.putInt(ARG_SECTION_NUMBER, sectionNumber) fragment.arguments = args return fragment } } }
bsd-3-clause
bb7d5ae4fdbcfac3b72484d13663a504
40.992958
298
0.661858
4.886885
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/notifications/dto/NotificationsFeedback.kt
1
2346
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.notifications.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.base.dto.BaseGeo import com.vk.sdk.api.base.dto.BaseLikesInfo import com.vk.sdk.api.wall.dto.WallWallpostAttachment import kotlin.Int import kotlin.String import kotlin.collections.List /** * @param attachments * @param fromId - Reply author's ID * @param geo * @param id - Item ID * @param likes * @param text - Reply text * @param toId - Wall owner's ID */ data class NotificationsFeedback( @SerializedName("attachments") val attachments: List<WallWallpostAttachment>? = null, @SerializedName("from_id") val fromId: Int? = null, @SerializedName("geo") val geo: BaseGeo? = null, @SerializedName("id") val id: Int? = null, @SerializedName("likes") val likes: BaseLikesInfo? = null, @SerializedName("text") val text: String? = null, @SerializedName("to_id") val toId: Int? = null )
mit
2276a44dc7ca1aed90bf39d63a9f5327
36.83871
81
0.684569
4.211849
false
false
false
false
revbingo/SPIFF
src/main/java/com/revbingo/spiff/datatypes/DataTypes.kt
1
4193
package com.revbingo.spiff.datatypes import com.revbingo.spiff.ExecutionException import com.revbingo.spiff.evaluator.Evaluator import com.revbingo.spiff.events.EventListener import com.revbingo.spiff.instructions.AdfInstruction import java.io.ByteArrayOutputStream import java.nio.ByteBuffer import java.nio.charset.Charset import java.util.* abstract class Datatype(val name: String): AdfInstruction() { var address: Int? = null var value: Any? = null override fun execute(buffer: ByteBuffer, eventDispatcher: EventListener, evaluator: Evaluator): Unit { address = buffer.position() value = this.evaluate(buffer, evaluator) evaluator.addVariable(name, value!!) evaluator.addVariable("${name}_address", address!!) eventDispatcher.notifyData(this) } abstract fun evaluate(buffer: ByteBuffer, evaluator: Evaluator): Any } abstract class StringInstruction(name: String, val expression: String, charsetName: String): Datatype(name) { val encoding: Charset init { try { encoding = Charset.forName(charsetName) } catch(e: Exception) { throw ExecutionException("Unknown or unsupported charset : $charsetName") } } override fun evaluate(buffer: ByteBuffer, evaluator: Evaluator): Any { val bytes = getBytes(buffer, evaluator) val result = String(bytes, encoding) return result.trim({ char -> char.isWhitespace() or (char == 0x00.toChar()) }) } abstract fun getBytes(buffer: ByteBuffer, evaluator: Evaluator): ByteArray } class FixedLengthString(name: String, expression: String, charsetName: String) : StringInstruction(name, expression, charsetName) { override fun getBytes(buffer: ByteBuffer, evaluator: Evaluator): ByteArray { val length = (evaluator.evaluate(expression) as Number).toInt() val bytes = ByteArray(length) buffer.get(bytes) return bytes } } class TerminatedString(name: String, charsetName: String) : StringInstruction(name, "", charsetName) { override fun getBytes(buffer: ByteBuffer, evaluator: Evaluator) : ByteArray { val baos = ByteArrayOutputStream() while(true) { val nextByte = buffer.get() if(nextByte.toInt() == 0x00) break; baos.write(nextByte.toInt()) } return baos.toByteArray() } } class LiteralStringInstruction(name: String, expression: String, charsetName: String) : StringInstruction(name, expression, charsetName) { override fun getBytes(buffer: ByteBuffer, evaluator: Evaluator) : ByteArray { val expectedBytes = expression.toByteArray(encoding) val actualBytes = ByteArray(expectedBytes.size) buffer.get(actualBytes) if(Arrays.equals(expectedBytes, actualBytes)) { return actualBytes } else { throw ExecutionException("Expected literal string ${expression} but got ${String(actualBytes, encoding)}") } } } class BytesInstruction(name: String): Datatype(name) { var lengthExpr: String? = null override fun evaluate(buffer: ByteBuffer, evaluator: Evaluator): Any { val length = evaluator.evaluate(lengthExpr!!, Int::class.java) val bytes = ByteArray(length) buffer.get(bytes) return bytes } } class BitsInstruction(name: String): Datatype(name) { var numberOfBitsExpr: String? = null override fun evaluate(buffer: ByteBuffer, evaluator: Evaluator): Any { val numberOfBits = evaluator.evaluate(numberOfBitsExpr!!, Int::class.java) val bytesToGet = Math.ceil(numberOfBits/8.0).toInt() val bytes = ByteArray(bytesToGet) buffer.get(bytes) val result = BooleanArray(numberOfBits) bytes.forEachIndexed { i, byte -> var tempByte = byte.toInt() for(j in 7 downTo 0) { val b: Int = tempByte and 0x01 val bitIndex = (i * 8) + j if(bitIndex < numberOfBits) { result[bitIndex] = (b == 1) } tempByte = tempByte shr 1 } } return result } }
mit
7af732281c6e01ec9d4d534e61ada24d
31.511628
138
0.657763
4.567538
false
false
false
false
google/cross-device-sdk
crossdevice/src/main/kotlin/com/google/ambient/crossdevice/sessions/ReceivingSession.kt
1
2665
/* * Copyright 2022 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 * * 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.google.ambient.crossdevice.sessions import android.os.Build import androidx.annotation.RequiresApi import com.google.common.util.concurrent.ListenableFuture import kotlinx.coroutines.MainScope import kotlinx.coroutines.guava.future /** * Describes a Session that is in the process of being transferred to another device. The receiver * of the Session will use this class to initialize the application. */ @RequiresApi(Build.VERSION_CODES.O) interface ReceivingSession : TransferrableSession { /** * Called when the receiving device is initialized and ready to run the Session. After this call, * all methods will throw [SessionException] with [HANDLE_INVALIDATED] * [SessionException.HANDLE_INVALIDATED]. * * @return The [SessionId] that was received. * * @throws SessionException if the transfer cannot be completed for any reason: * - Session transfer is cancelled already (by either originating or receiving device) * - Handle is invalidated * - Internal error */ @Throws(SessionException::class) suspend fun onComplete(): SessionId /** Java-compatible version of [onComplete]. */ fun onCompleteFuture(): ListenableFuture<SessionId> } @RequiresApi(Build.VERSION_CODES.O) internal class ReceivingSessionImpl( private val session: TransferrableSessionInterface, private val handleId: String ) : ReceivingSession { override val sessionId = session.sessionId private val transferrableSession = TransferrableSessionImpl(session, handleId) private val futureScope = MainScope() override fun getStartupRemoteConnection(): SessionRemoteConnection = transferrableSession.getStartupRemoteConnection() override suspend fun cancelTransfer() = transferrableSession.cancelTransfer() override fun cancelTransferFuture(): ListenableFuture<Unit> = transferrableSession.cancelTransferFuture() override suspend fun onComplete(): SessionId { return session.completeTransfer(handleId) } override fun onCompleteFuture(): ListenableFuture<SessionId> = futureScope.future { onComplete() } }
apache-2.0
84721231701c1ecd9f0633311876236f
36.535211
100
0.771107
4.73357
false
false
false
false
kohesive/klutter
binder/src/main/kotlin/uy/klutter/binder/ProvidedValue.kt
2
3604
package uy.klutter.binder sealed class ProvidedValue<out T>(val value: T) { companion object { fun <T> of(value: T): ProvidedValue<T> = Present.of(value) fun nested(subprovider: NamedValueProvider): NestedNamedValueProvider = NestedNamedValueProvider.of(subprovider) fun nested(subprovider: OrderedValueProvider): NestedOrderedValueProvider = NestedOrderedValueProvider.of(subprovider) fun <O, T> coerced(original: ProvidedValue<O>, value: T): ProvidedValue<T> = Coerced.of(original, value) fun absent(): ProvidedValue<Unit> = Absent.of() } open class Present<out T> protected constructor (value: T): ProvidedValue<T>(value) { companion object { fun <T> of(value: T): Present<T> = Present(value) } override fun toString(): String = "[Present ${value}]" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Present<*>) return false return value == other.value } override fun hashCode(): Int { return value?.hashCode() ?: 4314 } } class Coerced<out O, out T> private constructor (val original: ProvidedValue<O>, value: T): Present<T>(value) { companion object { fun <O, T> of(original: ProvidedValue<O>, value: T): Coerced<O, T> = Coerced(original, value) } override fun toString(): String = "[Coerced ${value} from ${original}]" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Coerced<*, *>) return false return original == other.original && value == other.value } override fun hashCode(): Int { return value?.hashCode() ?: 9911 } } class NestedNamedValueProvider private constructor (subprovider: NamedValueProvider): ProvidedValue<NamedValueProvider>(subprovider) { companion object { fun of(subprovider: NamedValueProvider): NestedNamedValueProvider = NestedNamedValueProvider(subprovider) } override fun toString(): String = "[NestedNamedValueProvider ${value}]" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is NestedNamedValueProvider) return false return value == other.value } override fun hashCode(): Int { return value.hashCode() * 49 } } class NestedOrderedValueProvider private constructor (subprovider: OrderedValueProvider): ProvidedValue<OrderedValueProvider>(subprovider) { companion object { fun of(subprovider: OrderedValueProvider): NestedOrderedValueProvider = NestedOrderedValueProvider(subprovider) } override fun toString(): String = "[NestedOrderedValueProvider ${value}]" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is NestedOrderedValueProvider) return false return value == other.value } override fun hashCode(): Int { return value.hashCode() * 49 } } class Absent private constructor (): ProvidedValue<Unit>(Unit) { companion object { private val instance = Absent() @Suppress("UNCHECKED_CAST") fun of(): Absent = instance } override fun toString(): String = "[Absent]" override fun equals(other: Any?): Boolean = this === other override fun hashCode(): Int = 999 } }
mit
65be3604cc27f91247777ce2114a6d10
37.763441
145
0.617092
5.155937
false
false
false
false
alangibson27/plus-f
plus-f/src/main/kotlin/com/socialthingy/plusf/sound/Beeper.kt
1
1376
package com.socialthingy.plusf.sound import com.jsyn.data.FloatSample import com.jsyn.unitgen.* import com.socialthingy.plusf.spectrum.Model open class Beeper(private val sampler: VariableRateMonoReader) { var updatePeriod: Double = 3500000.0 / sampler.rate.get() private val beeperStates = FloatArray(901) private var beeperIdx = 0 private var allStatesHigh = true private var isEnabled = false fun setModel(model: Model) { updatePeriod = model.clockFrequencyHz / sampler.rate.get() } fun setEnabled(enabled: Boolean) { isEnabled = enabled if (!enabled) { beeperIdx = 0 } } fun update(state: Boolean) { if (isEnabled) { beeperStates[beeperIdx] = if (state) 1.0F else 0.0F beeperIdx++ allStatesHigh = allStatesHigh && state } } fun play() { if (beeperIdx == 0) { sampler.dataQueue.clear() } else { if (!isEnabled || allStatesHigh) { sampler.dataQueue.clear() } else { val sample = FloatSample() sample.allocate(beeperIdx, 1) sample.write(0, beeperStates, 0, beeperIdx) sampler.dataQueue.queue(sample) } beeperIdx = 0 allStatesHigh = true } } }
mit
b88b69a437c51f636987e142c9b35136
25.980392
66
0.571948
4.220859
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course_search/analytic/CourseContentSearchResultClicked.kt
1
1081
package org.stepik.android.domain.course_search.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent import ru.nobird.android.core.model.mapOfNotNull class CourseContentSearchResultClicked( val courseId: Long, val courseTitle: String, val query: String, val suggestion: String?, val type: String, val stepId: Long? ) : AnalyticEvent { companion object { private const val PARAM_COURSE = "course" private const val PARAM_TITLE = "title" private const val PARAM_QUERY = "query" private const val PARAM_SUGGESTION = "suggestion" private const val PARAM_TYPE = "type" private const val PARAM_STEP = "step" } override val name: String = "Course content search result clicked" override val params: Map<String, Any> = mapOfNotNull( PARAM_COURSE to courseId, PARAM_TITLE to courseTitle, PARAM_QUERY to query, PARAM_SUGGESTION to suggestion, PARAM_TYPE to type, PARAM_STEP to stepId ) }
apache-2.0
e7c799bac32d4164ad546ab593114be9
30.823529
60
0.652174
4.504167
false
false
false
false
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/KotlinObjCClassInfoGenerator.kt
1
6488
/* * 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 org.jetbrains.kotlin.backend.konan.llvm import llvm.LLVMStoreSizeOfType import llvm.LLVMValueRef import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.descriptors.contributedMethods import org.jetbrains.kotlin.backend.konan.descriptors.getStringValue import org.jetbrains.kotlin.backend.konan.descriptors.getStringValueOrNull import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.isFinalClass import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces internal class KotlinObjCClassInfoGenerator(override val context: Context) : ContextUtils { fun generate(irClass: IrClass) { val descriptor = irClass.descriptor assert(descriptor.isFinalClass) val objCLLvmDeclarations = context.llvmDeclarations.forClass(descriptor).objCDeclarations!! val instanceMethods = generateInstanceMethodDescs(irClass) val companionObjectDescriptor = descriptor.companionObjectDescriptor val classMethods = companionObjectDescriptor?.generateOverridingMethodDescs() ?: emptyList() val superclassName = descriptor.getSuperClassNotAny()!!.name.asString() val protocolNames = descriptor.getSuperInterfaces().map { it.name.asString().removeSuffix("Protocol") } val bodySize = LLVMStoreSizeOfType(llvmTargetData, context.llvmDeclarations.forClass(descriptor).bodyType).toInt() val className = selectClassName(descriptor)?.let { staticData.cStringLiteral(it) } ?: NullPointer(int8Type) val info = Struct(runtime.kotlinObjCClassInfo, className, staticData.cStringLiteral(superclassName), staticData.placeGlobalConstArray("", int8TypePtr, protocolNames.map { staticData.cStringLiteral(it) } + NullPointer(int8Type)), staticData.placeGlobalConstArray("", runtime.objCMethodDescription, instanceMethods), Int32(instanceMethods.size), staticData.placeGlobalConstArray("", runtime.objCMethodDescription, classMethods), Int32(classMethods.size), Int32(bodySize), objCLLvmDeclarations.bodyOffsetGlobal.pointer, descriptor.typeInfoPtr, companionObjectDescriptor?.typeInfoPtr ?: NullPointer(runtime.typeInfoType), objCLLvmDeclarations.classPointerGlobal.pointer ) objCLLvmDeclarations.classInfoGlobal.setInitializer(info) objCLLvmDeclarations.classPointerGlobal.setInitializer(NullPointer(int8Type)) objCLLvmDeclarations.bodyOffsetGlobal.setInitializer(Int32(0)) } private fun generateInstanceMethodDescs( irClass: IrClass ): List<ObjCMethodDesc> = mutableListOf<ObjCMethodDesc>().apply { val descriptor = irClass.descriptor addAll(descriptor.generateOverridingMethodDescs()) addAll(irClass.generateImpMethodDescs()) val allImplementedSelectors = this.map { it.selector }.toSet() assert(descriptor.getSuperClassNotAny()!!.isExternalObjCClass()) val allInitMethodsInfo = descriptor.getSuperClassNotAny()!!.constructors .mapNotNull { it.getObjCInitMethod()?.getExternalObjCMethodInfo() } .filter { it.selector !in allImplementedSelectors } .distinctBy { it.selector } allInitMethodsInfo.mapTo(this) { ObjCMethodDesc(it.selector, it.encoding, context.llvm.missingInitImp) } } private fun selectClassName(descriptor: ClassDescriptor): String? { val exportObjCClassAnnotation = descriptor.annotations.findAnnotation(context.interopBuiltIns.exportObjCClass.fqNameSafe) return if (exportObjCClassAnnotation != null) { exportObjCClassAnnotation.getStringValueOrNull("name") ?: descriptor.name.asString() } else if (descriptor.isExported()) { descriptor.fqNameSafe.asString() } else { null // Generate as anonymous. } } private inner class ObjCMethodDesc( val selector: String, val encoding: String, val impFunction: LLVMValueRef ) : Struct( runtime.objCMethodDescription, staticData.cStringLiteral(selector), staticData.cStringLiteral(encoding), constPointer(impFunction).bitcast(int8TypePtr) ) private fun generateMethodDesc(info: ObjCMethodInfo) = ObjCMethodDesc( info.selector, info.encoding, context.llvm.externalFunction(info.imp, functionType(voidType)) ) private fun ClassDescriptor.generateOverridingMethodDescs(): List<ObjCMethodDesc> = this.unsubstitutedMemberScope.contributedMethods.filter { it.kind.isReal && it !is ConstructorDescriptor }.mapNotNull { it.getObjCMethodInfo() }.map { generateMethodDesc(it) } private fun IrClass.generateImpMethodDescs(): List<ObjCMethodDesc> = this.declarations .filterIsInstance<IrSimpleFunction>() .mapNotNull { val annotation = it.descriptor.annotations.findAnnotation(context.interopBuiltIns.objCMethodImp.fqNameSafe) ?: return@mapNotNull null ObjCMethodDesc( annotation.getStringValue("selector"), annotation.getStringValue("encoding"), it.descriptor.llvmFunction ) } }
apache-2.0
c6b135dd35767e45ddcbb9c597135188
43.142857
117
0.700832
5.379768
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonConfig.kt
1
1909
package eu.kanade.tachiyomi.ui.reader.viewer.webtoon import com.f2prateek.rx.preferences.Preference import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.util.addTo import rx.subscriptions.CompositeSubscription import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * Configuration used by webtoon viewers. */ class WebtoonConfig(preferences: PreferencesHelper = Injekt.get()) { private val subscriptions = CompositeSubscription() var imagePropertyChangedListener: (() -> Unit)? = null var tappingEnabled = true private set var longTapEnabled = true private set var volumeKeysEnabled = false private set var volumeKeysInverted = false private set var imageCropBorders = false private set var doubleTapAnimDuration = 500 private set init { preferences.readWithTapping() .register({ tappingEnabled = it }) preferences.readWithLongTap() .register({ longTapEnabled = it }) preferences.cropBordersWebtoon() .register({ imageCropBorders = it }, { imagePropertyChangedListener?.invoke() }) preferences.doubleTapAnimSpeed() .register({ doubleTapAnimDuration = it }) preferences.readWithVolumeKeys() .register({ volumeKeysEnabled = it }) preferences.readWithVolumeKeysInverted() .register({ volumeKeysInverted = it }) } fun unsubscribe() { subscriptions.unsubscribe() } private fun <T> Preference<T>.register( valueAssignment: (T) -> Unit, onChanged: (T) -> Unit = {} ) { asObservable() .doOnNext(valueAssignment) .skip(1) .distinctUntilChanged() .doOnNext(onChanged) .subscribe() .addTo(subscriptions) } }
apache-2.0
63e1f248b15cf4de6f4d3f1dd3be0050
24.797297
92
0.641697
5.036939
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/CGMSHistoryEntryType.kt
1
2817
package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.cgms /** * This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes * management and modified/extended for AAPS. * * Author: Andy {[email protected]} */ enum class CGMSHistoryEntryType(val code: Int, val description: String, val headLength: Int, val dateLength: Int, val bodyLength: Int, dateType: DateType) { None(0, "None", 1, 0, 0, DateType.None), // DataEnd(0x01, "DataEnd", 1, 0, 0, DateType.PreviousTimeStamp), // SensorWeakSignal(0x02, "SensorWeakSignal", 1, 0, 0, DateType.PreviousTimeStamp), // SensorCal(0x03, "SensorCal", 1, 0, 1, DateType.PreviousTimeStamp), // SensorPacket(0x04, "SensorPacket", 1, 0, 1, DateType.PreviousTimeStamp), SensorError(0x05, "SensorError", 1, 0, 1, DateType.PreviousTimeStamp), SensorDataLow(0x06, "SensorDataLow", 1, 0, 1, DateType.PreviousTimeStamp), SensorDataHigh(0x07, "SensorDataHigh", 1, 0, 1, DateType.PreviousTimeStamp), SensorTimestamp(0x08, "SensorTimestamp", 1, 4, 0, DateType.MinuteSpecific), // BatteryChange(0x0a, "BatteryChange", 1, 4, 0, DateType.MinuteSpecific), // SensorStatus(0x0b, "SensorStatus", 1, 4, 0, DateType.MinuteSpecific), // DateTimeChange(0x0c, "DateTimeChange", 1, 4, 0, DateType.SecondSpecific), // SensorSync(0x0d, "SensorSync',packet_size=4", 1, 4, 0, DateType.MinuteSpecific), // CalBGForGH(0x0e, "CalBGForGH',packet_size=5", 1, 4, 1, DateType.MinuteSpecific), // SensorCalFactor(0x0f, "SensorCalFactor", 1, 4, 2, DateType.MinuteSpecific), // Something10(0x10, "10-Something", 1, 4, 0, DateType.MinuteSpecific), // Something19(0x13, "19-Something", 1, 0, 0, DateType.PreviousTimeStamp), GlucoseSensorData(0xFF, "GlucoseSensorData", 1, 0, 0, DateType.PreviousTimeStamp), UnknownOpCode(0xFF, "Unknown", 0, 0, 0, DateType.None); companion object { private val opCodeMap: MutableMap<Int, CGMSHistoryEntryType> = mutableMapOf() fun getByCode(opCode: Int): CGMSHistoryEntryType { return if (opCodeMap.containsKey(opCode)) opCodeMap[opCode]!! else UnknownOpCode } init { for (type in values()) { opCodeMap[type.code] = type } } } var schemaSet: Boolean val totalLength: Int val dateType: DateType fun hasDate(): Boolean { return dateType == DateType.MinuteSpecific || dateType == DateType.SecondSpecific } enum class DateType { None, // MinuteSpecific, // SecondSpecific, // PreviousTimeStamp // } init { totalLength = headLength + dateLength + bodyLength schemaSet = true this.dateType = dateType } }
agpl-3.0
8d8dd76fa0e55ed3e1c082eb8840253a
43.03125
379
0.661342
3.682353
false
false
false
false
realm/realm-java
realm-transformer/src/main/kotlin/io/realm/transformer/build/FullBuild.kt
1
6657
/* * Copyright 2018 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.transformer.build import com.android.build.api.transform.Format import com.android.build.api.transform.TransformInput import com.android.build.api.transform.TransformOutputProvider import io.realm.transformer.BytecodeModifier import io.realm.transformer.ProjectMetaData import io.realm.transformer.RealmTransformer import io.realm.transformer.ext.safeSubtypeOf import io.realm.transformer.logger import javassist.CtClass import javassist.CtField import java.io.File import java.util.jar.JarFile class FullBuild(metadata: ProjectMetaData, outputProvider: TransformOutputProvider, transformer: RealmTransformer) : BuildTemplate(metadata, outputProvider, transformer) { private val allModelClasses: ArrayList<CtClass> = arrayListOf() override fun prepareOutputClasses(inputs: MutableCollection<TransformInput>) { this.inputs = inputs; categorizeClassNames(inputs, outputClassNames, outputReferencedClassNames) logger.debug("Full build. Files being processed: ${outputClassNames.size}.") } override fun categorizeClassNames(inputs: Collection<TransformInput>, directoryFiles: MutableSet<String>, jarFiles: MutableSet<String>) { inputs.forEach { it.directoryInputs.forEach { val dirPath: String = it.file.absolutePath // Non-incremental build: Include all files it.file.walkTopDown().forEach { if (it.isFile) { if (it.absolutePath.endsWith(DOT_CLASS)) { val className: String = it.absolutePath .substring(dirPath.length + 1, it.absolutePath.length - DOT_CLASS.length) .replace(File.separatorChar, '.') directoryFiles.add(className) } } } } it.jarInputs.forEach { val jarFile = JarFile(it.file) jarFile.entries() .toList() .filter { !it.isDirectory && it.name.endsWith(DOT_CLASS) } .forEach { val path: String = it.name // The jar might not using File.separatorChar as the path separator. So we just replace both `\` and // `/`. It depends on how the jar file was created. // See http://stackoverflow.com/questions/13846000/file-separators-of-path-name-of-zipentry val className: String = path .substring(0, path.length - DOT_CLASS.length) .replace('/', '.') .replace('\\', '.') jarFiles.add(className) } jarFile.close() // Crash transformer if this fails } } } override fun findModelClasses(classNames: Set<String>): Collection<CtClass> { val realmObjectProxyInterface: CtClass = classPool.get("io.realm.internal.RealmObjectProxy") // For full builds, we are currently finding model classes by assuming that only // the annotation processor is generating files ending with `RealmProxy`. This is // a lot faster as we only need to compare the name of the type before we load // the CtClass. // Find the model classes return classNames // Quick and loose filter where we assume that classes ending with RealmProxy are // a Realm model proxy class generated by the annotation processor. This can // produce false positives: https://github.com/realm/realm-java/issues/3709 .filter { it.endsWith("RealmProxy") } .mapNotNull { // Verify the file is in fact a proxy class, in which case the super // class is always present and is the real model class. val clazz: CtClass = classPool.getCtClass(it) if (clazz.safeSubtypeOf(realmObjectProxyInterface)) { return@mapNotNull clazz.superclass; } else { return@mapNotNull null } } } override fun filterForModelClasses(classNames: Set<String>, extraClassNames: Set<String>) { val allClassNames: Set<String> = merge(classNames, extraClassNames) allModelClasses.addAll(findModelClasses(allClassNames)) outputModelClasses.addAll(allModelClasses.filter { outputClassNames.contains(it.name) }) } override fun transformDirectAccessToModelFields() { // Populate a list of the fields that need to be managed with bytecode manipulation val allManagedFields: ArrayList<CtField> = arrayListOf() allModelClasses.forEach { allManagedFields.addAll(it.declaredFields.filter { BytecodeModifier.isModelField(it) }) } logger.debug("Managed Fields: ${allManagedFields.joinToString(",") { it.name }}") // Use accessors instead of direct field access outputClassNames.forEach { logger.debug("Modifying accessors in class: $it") try { val ctClass: CtClass = classPool.getCtClass(it) BytecodeModifier.useRealmAccessors(classPool, ctClass, allManagedFields) ctClass.writeFile(getOutputFile(outputProvider, Format.DIRECTORY).canonicalPath) } catch (e: Exception) { throw RuntimeException("Failed to transform $it.", e) } } } private fun merge(set1: Set<String>, set2: Set<String>): Set<String> { val merged: MutableSet<String> = hashSetOf() merged.addAll(set1) merged.addAll(set2) return merged } }
apache-2.0
f4d448ca035567a4cf684f4358a9416b
43.092715
128
0.602373
5.116833
false
false
false
false
square/wire
wire-library/wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt
1
19528
/* * Copyright 2018 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema import com.squareup.javapoet.JavaFile import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.TypeSpec import com.squareup.wire.WireCompiler import com.squareup.wire.java.JavaGenerator import com.squareup.wire.kotlin.KotlinGenerator import com.squareup.wire.kotlin.RpcCallStyle import com.squareup.wire.kotlin.RpcRole import com.squareup.wire.swift.SwiftGenerator import okio.Path import java.io.IOException import java.io.Serializable import io.outfoxx.swiftpoet.FileSpec as SwiftFileSpec sealed class Target : Serializable { /** * Proto types to include generated sources for. Types listed here will be generated for this * target and not for subsequent targets in the task. * * This list should contain package names (suffixed with `.*`) and type names only. It should * not contain member names. */ abstract val includes: List<String> /** * Proto types to excluded generated sources for. Types listed here will not be generated for this * target. * * This list should contain package names (suffixed with `.*`) and type names only. It should * not contain member names. */ abstract val excludes: List<String> /** * True if types emitted for this target should not also be emitted for other targets. Use this * to cause multiple outputs to be emitted for the same input type. */ abstract val exclusive: Boolean /** * Directory where this target will write its output. * * In Gradle, when this class is serialized, this is relative to the project to improve build * cacheability. Callers must use [copyTarget] to resolve it to real path prior to use. */ abstract val outDirectory: String /** * Returns a new Target object that is a copy of this one, but with the given fields updated. */ // TODO(Benoit) We're only ever copying outDirectory, maybe we can remove other fields and rename // the method? abstract fun copyTarget( includes: List<String> = this.includes, excludes: List<String> = this.excludes, exclusive: Boolean = this.exclusive, outDirectory: String = this.outDirectory, ): Target abstract fun newHandler(): SchemaHandler } // TODO(Benoit) Get JavaGenerator to expose a factory from its module. Code should not be here. /** Generate `.java` sources. */ data class JavaTarget( override val includes: List<String> = listOf("*"), override val excludes: List<String> = listOf(), override val exclusive: Boolean = true, override val outDirectory: String, /** True for emitted types to implement `android.os.Parcelable`. */ val android: Boolean = false, /** True to enable the `androidx.annotation.Nullable` annotation where applicable. */ val androidAnnotations: Boolean = false, /** * True to emit code that uses reflection for reading, writing, and toString methods which are * normally implemented with generated code. */ val compact: Boolean = false, /** True to emit types for options declared on messages, fields, etc. */ val emitDeclaredOptions: Boolean = true, /** True to emit annotations for options applied on messages, fields, etc. */ val emitAppliedOptions: Boolean = true, /** If true, the constructor of all generated types will be non-public. */ val buildersOnly : Boolean = false, ) : Target() { override fun newHandler(): SchemaHandler { return object : SchemaHandler() { private lateinit var javaGenerator: JavaGenerator override fun handle(schema: Schema, context: Context) { val profileName = if (android) "android" else "java" val profile = context.profileLoader!!.loadProfile(profileName, schema) javaGenerator = JavaGenerator.get(schema) .withProfile(profile) .withAndroid(android) .withAndroidAnnotations(androidAnnotations) .withCompact(compact) .withOptions(emitDeclaredOptions, emitAppliedOptions) .withBuildersOnly(buildersOnly) context.fileSystem.createDirectories(context.outDirectory) super.handle(schema, context) } override fun handle(type: Type, context: Context): Path? { if (JavaGenerator.builtInType(type.type)) return null val typeSpec = javaGenerator.generateType(type) val javaTypeName = javaGenerator.generatedTypeName(type) return write(javaTypeName, typeSpec, type.type, type.location, context) } override fun handle(service: Service, context: Context): List<Path> { // Service handling isn't supporting in Java. return emptyList() } override fun handle(extend: Extend, field: Field, context: Context): Path? { val typeSpec = javaGenerator.generateOptionType(extend, field) ?: return null val javaTypeName = javaGenerator.generatedTypeName(extend.member(field)) return write(javaTypeName, typeSpec, field.qualifiedName, field.location, context) } private fun write( javaTypeName: com.squareup.javapoet.ClassName, typeSpec: com.squareup.javapoet.TypeSpec, source: Any, location: Location, context: Context, ): Path { val outDirectory = context.outDirectory val javaFile = JavaFile.builder(javaTypeName.packageName(), typeSpec) .addFileComment("\$L", WireCompiler.CODE_GENERATED_BY_WIRE) .addFileComment("\nSource: \$L in \$L", source, location.withPathOnly()) .build() val filePath = outDirectory / javaFile.packageName.replace(".", "/") / "${javaTypeName.simpleName()}.java" context.logger.artifactHandled( outDirectory, "${javaFile.packageName}.${javaFile.typeSpec.name}", "Java" ) try { context.fileSystem.createDirectories(filePath.parent!!) context.fileSystem.write(filePath) { writeUtf8(javaFile.toString()) } } catch (e: IOException) { throw IOException( "Error emitting ${javaFile.packageName}.${javaFile.typeSpec.name} to $outDirectory", e ) } return filePath } } } override fun copyTarget( includes: List<String>, excludes: List<String>, exclusive: Boolean, outDirectory: String ): Target { return copy( includes = includes, excludes = excludes, exclusive = exclusive, outDirectory = outDirectory, ) } } // TODO(Benoit) Get kotlinGenerator to expose a factory from its module. Code should not be here. /** Generate `.kt` sources. */ data class KotlinTarget( override val includes: List<String> = listOf("*"), override val excludes: List<String> = listOf(), override val exclusive: Boolean = true, override val outDirectory: String, /** True for emitted types to implement `android.os.Parcelable`. */ val android: Boolean = false, /** True for emitted types to implement APIs for easier migration from the Java target. */ val javaInterop: Boolean = false, /** True to emit types for options declared on messages, fields, etc. */ val emitDeclaredOptions: Boolean = true, /** True to emit annotations for options applied on messages, fields, etc. */ val emitAppliedOptions: Boolean = true, /** Blocking or suspending. */ val rpcCallStyle: RpcCallStyle = RpcCallStyle.SUSPENDING, /** Client or server. */ val rpcRole: RpcRole = RpcRole.CLIENT, /** True for emitted services to implement one interface per RPC. */ val singleMethodServices: Boolean = false, /** * If a oneof has more than or [boxOneOfsMinSize] fields, it will be generated using boxed oneofs * as defined in [OneOf][com.squareup.wire.OneOf]. */ val boxOneOfsMinSize: Int = 5_000, /** True to also generate gRPC server-compatible classes. Experimental feature. */ val grpcServerCompatible: Boolean = false, /** * If present, generated services classes will use this as a suffix instead of inferring one * from the [rpcRole]. */ val nameSuffix: String? = null, /** * If true, the constructor of all generated types will be non-public, and they will be * instantiable via their builders, regardless of the value of [javaInterop]. */ val buildersOnly : Boolean = false, ) : Target() { override fun newHandler(): SchemaHandler { return object : SchemaHandler() { private lateinit var kotlinGenerator: KotlinGenerator override fun handle(schema: Schema, context: Context) { val profileName = if (android) "android" else "java" val profile = context.profileLoader!!.loadProfile(profileName, schema) kotlinGenerator = KotlinGenerator( schema = schema, profile = profile, emitAndroid = android, javaInterop = javaInterop, emitDeclaredOptions = emitDeclaredOptions, emitAppliedOptions = emitAppliedOptions, rpcCallStyle = rpcCallStyle, rpcRole = rpcRole, boxOneOfsMinSize = boxOneOfsMinSize, grpcServerCompatible = grpcServerCompatible, nameSuffix = nameSuffix, buildersOnly = buildersOnly, singleMethodServices = singleMethodServices, ) context.fileSystem.createDirectories(context.outDirectory) super.handle(schema, context) } override fun handle(type: Type, context: Context): Path? { if (KotlinGenerator.builtInType(type.type)) return null val typeSpec = kotlinGenerator.generateType(type) val className = kotlinGenerator.generatedTypeName(type) return write(className, typeSpec, type.type, type.location, context) } override fun handle(service: Service, context: Context): List<Path> { if (rpcRole === RpcRole.NONE) return emptyList() val generatedPaths = mutableListOf<Path>() if (singleMethodServices) { service.rpcs.forEach { rpc -> val map = kotlinGenerator.generateServiceTypeSpecs(service, rpc) for ((className, typeSpec) in map) { generatedPaths.add( write(className, typeSpec, service.type, service.location, context) ) } } } else { val map = kotlinGenerator.generateServiceTypeSpecs(service, null) for ((className, typeSpec) in map) { generatedPaths.add(write(className, typeSpec, service.type, service.location, context)) } } return generatedPaths } override fun handle(extend: Extend, field: Field, context: Context): Path? { val typeSpec = kotlinGenerator.generateOptionType(extend, field) ?: return null val name = kotlinGenerator.generatedTypeName(extend.member(field)) return write(name, typeSpec, field.qualifiedName, field.location, context) } private fun write( name: ClassName, typeSpec: TypeSpec, source: Any, location: Location, context: Context, ): Path { val modulePath = context.outDirectory val kotlinFile = FileSpec.builder(name.packageName, name.simpleName) .addFileComment(WireCompiler.CODE_GENERATED_BY_WIRE) .addFileComment("\nSource: %L in %L", source, location.withPathOnly()) .addType(typeSpec) .build() val filePath = modulePath / kotlinFile.packageName.replace(".", "/") / "${kotlinFile.name}.kt" context.logger.artifactHandled( modulePath, "${kotlinFile.packageName}.${(kotlinFile.members.first() as TypeSpec).name}", "Kotlin" ) try { context.fileSystem.createDirectories(filePath.parent!!) context.fileSystem.write(filePath) { writeUtf8(kotlinFile.toString()) } } catch (e: IOException) { throw IOException("Error emitting ${kotlinFile.packageName}.$source to $outDirectory", e) } return filePath } } } override fun copyTarget( includes: List<String>, excludes: List<String>, exclusive: Boolean, outDirectory: String ): Target { return copy( includes = includes, excludes = excludes, exclusive = exclusive, outDirectory = outDirectory, ) } } // TODO(Benoit) Get SwiftGenerator to expose a factory from its module. Code should not be here. data class SwiftTarget( override val includes: List<String> = listOf("*"), override val excludes: List<String> = listOf(), override val exclusive: Boolean = true, override val outDirectory: String ) : Target() { override fun newHandler(): SchemaHandler { return object : SchemaHandler() { private lateinit var generator: SwiftGenerator override fun handle(schema: Schema, context: Context) { generator = SwiftGenerator(schema, context.module?.upstreamTypes ?: mapOf()) context.fileSystem.createDirectories(context.outDirectory) super.handle(schema, context) } override fun handle(type: Type, context: Context): Path? { if (SwiftGenerator.builtInType(type.type)) return null val modulePath = context.outDirectory val typeName = generator.generatedTypeName(type) val swiftFile = SwiftFileSpec.builder(typeName.moduleName, typeName.simpleName) .addComment(WireCompiler.CODE_GENERATED_BY_WIRE) .addComment("\nSource: %L in %L", type.type, type.location.withPathOnly()) .indent(" ") .apply { generator.generateTypeTo(type, this) } .build() val filePath = modulePath / "${swiftFile.name}.swift" try { context.fileSystem.write(filePath) { writeUtf8(swiftFile.toString()) } } catch (e: IOException) { throw IOException( "Error emitting ${swiftFile.moduleName}.${typeName.canonicalName} to $modulePath", e ) } context.logger.artifactHandled( modulePath, "${swiftFile.moduleName}.${typeName.canonicalName}", "Swift" ) return filePath } override fun handle(service: Service, context: Context) = emptyList<Path>() override fun handle( extend: Extend, field: Field, context: Context ): Path? = null } } override fun copyTarget( includes: List<String>, excludes: List<String>, exclusive: Boolean, outDirectory: String ): Target { return copy( includes = includes, excludes = excludes, exclusive = exclusive, outDirectory = outDirectory, ) } } data class ProtoTarget( override val outDirectory: String ) : Target() { override val includes: List<String> = listOf() override val excludes: List<String> = listOf() override val exclusive: Boolean = false override fun newHandler(): SchemaHandler { return object : SchemaHandler() { override fun handle(schema: Schema, context: Context) { context.fileSystem.createDirectories(context.outDirectory) val outDirectory = context.outDirectory for (protoFile in schema.protoFiles) { if (!context.inSourcePath(protoFile) || protoFile.isEmpty()) continue val relativePath = protoFile.location.path .substringBeforeLast("/", missingDelimiterValue = ".") val outputDirectory = outDirectory / relativePath val outputFilePath = outputDirectory / "${protoFile.name()}.proto" context.logger.artifactHandled(outputDirectory, protoFile.location.path, "Proto") try { context.fileSystem.createDirectories(outputFilePath.parent!!) context.fileSystem.write(outputFilePath) { writeUtf8(protoFile.toSchema()) } } catch (e: IOException) { throw IOException("Error emitting $outputFilePath to $outDirectory", e) } } } private fun ProtoFile.isEmpty() = types.isEmpty() && services.isEmpty() && extendList.isEmpty() override fun handle(type: Type, context: Context): Path? = null override fun handle(service: Service, context: Context): List<Path> = listOf() override fun handle(extend: Extend, field: Field, context: Context): Path? = null } } override fun copyTarget( includes: List<String>, excludes: List<String>, exclusive: Boolean, outDirectory: String ): Target { return copy( outDirectory = outDirectory, ) } } data class CustomTarget( override val includes: List<String> = listOf("*"), override val excludes: List<String> = listOf(), override val exclusive: Boolean = true, override val outDirectory: String, val schemaHandlerFactory: SchemaHandler.Factory, ) : Target() { override fun copyTarget( includes: List<String>, excludes: List<String>, exclusive: Boolean, outDirectory: String ): Target { return this.copy( includes = includes, excludes = excludes, exclusive = exclusive, outDirectory = outDirectory, ) } override fun newHandler(): SchemaHandler { return schemaHandlerFactory.create() } } /** * Create and return an instance of [SchemaHandler.Factory]. * * @param schemaHandlerFactoryClass a fully qualified class name for a class that implements * [SchemaHandler.Factory]. The class must have a no-arguments public constructor. */ fun newSchemaHandler(schemaHandlerFactoryClass: String): SchemaHandler.Factory { return ClassNameSchemaHandlerFactory(schemaHandlerFactoryClass) } /** * This schema handler factory is serializable (so Gradle can cache targets that use it). It works * even if the delegate handler class is itself not serializable. */ private class ClassNameSchemaHandlerFactory( private val schemaHandlerFactoryClass: String ) : SchemaHandler.Factory { @Transient private var cachedDelegate: SchemaHandler.Factory? = null private val delegate: SchemaHandler.Factory get() { val cachedResult = cachedDelegate if (cachedResult != null) return cachedResult val schemaHandlerType = try { Class.forName(schemaHandlerFactoryClass) } catch (exception: ClassNotFoundException) { throw IllegalArgumentException("Couldn't find SchemaHandlerClass '$schemaHandlerFactoryClass'") } val constructor = try { schemaHandlerType.getConstructor() } catch (exception: NoSuchMethodException) { throw IllegalArgumentException("No public constructor on $schemaHandlerFactoryClass") } val result = constructor.newInstance() as? SchemaHandler.Factory ?: throw IllegalArgumentException("$schemaHandlerFactoryClass does not implement SchemaHandler.Factory") this.cachedDelegate = result return result } override fun create(): SchemaHandler { return delegate.create() } }
apache-2.0
0f498471c76a97b624ba2e84abc486f3
33.685613
112
0.673136
4.825303
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeEntityImpl.kt
2
11664
package com.intellij.workspaceModel.storage.entities.test.api 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.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.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent 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 TreeEntityImpl: TreeEntity, WorkspaceEntityBase() { companion object { internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( CHILDREN_CONNECTION_ID, PARENTENTITY_CONNECTION_ID, ) } @JvmField var _data: String? = null override val data: String get() = _data!! override val children: List<TreeEntity> get() = snapshot.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override val parentEntity: TreeEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: TreeEntityData?): ModifiableWorkspaceEntityBase<TreeEntity>(), TreeEntity.Builder { constructor(): this(TreeEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity TreeEntity 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().isDataInitialized()) { error("Field TreeEntity#data should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field TreeEntity#entitySource should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field TreeEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field TreeEntity#children should be initialized") } } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field TreeEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field TreeEntity#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } // List of non-abstract referenced types var _children: List<TreeEntity>? = emptyList() override var children: List<TreeEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override var parentEntity: TreeEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity } } 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, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_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(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): TreeEntityData = result ?: super.getEntityData() as TreeEntityData override fun getEntityClass(): Class<TreeEntity> = TreeEntity::class.java } } class TreeEntityData : WorkspaceEntityData<TreeEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<TreeEntity> { val modifiable = TreeEntityImpl.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): TreeEntity { val entity = TreeEntityImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return TreeEntity::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 TreeEntityData if (this.data != other.data) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as TreeEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
apache-2.0
679e5a55fd493de50bb21ab092c4859b
42.04428
202
0.596879
5.864253
false
false
false
false
laminr/aeroknow
app/src/main/java/biz/eventually/atpl/ui/questions/QuestionRepository.kt
1
3927
package biz.eventually.atpl.ui.questions import android.annotation.SuppressLint import biz.eventually.atpl.data.DataProvider import biz.eventually.atpl.data.NetworkStatus import biz.eventually.atpl.data.dao.LastCallDao import biz.eventually.atpl.data.dao.QuestionDao import biz.eventually.atpl.data.db.LastCall import biz.eventually.atpl.data.db.Question import biz.eventually.atpl.ui.BaseRepository import biz.eventually.atpl.utils.hasInternetConnection import com.google.firebase.perf.metrics.AddTrace import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import timber.log.Timber import java.util.* import javax.inject.Inject import javax.inject.Singleton /** * Created by Thibault de Lambilly on 20/03/17. * */ @Singleton class QuestionRepository @Inject constructor(private val dataProvider: DataProvider, private val dao: QuestionDao, private val lastCallDao: LastCallDao) : BaseRepository() { @AddTrace(name = "launchTest", enabled = true) fun getQuestions(topicId: Long, starFist: Boolean, then: (data: List<Question>) -> Unit) { // has Network: request data if (hasInternetConnection()) { getWebData(topicId, starFist) { data -> then(data) } } // No network: taking in database else { doAsync { val data = getDataFromDb(topicId) uiThread { then(data) } } } } @SuppressLint("CheckResult") fun getWebData(topicId: Long, starFist: Boolean, fromScratch: Boolean = false, silent: Boolean = false, then: (data: List<Question>) -> Unit) { doAsync { val lastCall = if (fromScratch) 0L else lastCallDao.findByType("${LastCall.TYPE_TOPIC}_$topicId")?.updatedAt ?: 0L uiThread { if (!silent) status.postValue(NetworkStatus.LOADING) dataProvider .dataGetTopicQuestions(topicId, starFist, lastCall) .subscribeOn(scheduler.network) .map { question -> analyseData(topicId, question) } .map { getDataFromDb(topicId) } .observeOn(scheduler.main) .subscribe({ data -> if (!silent) status.postValue(NetworkStatus.SUCCESS) then(data) }, { e -> if (!silent) status.postValue(NetworkStatus.ERROR) Timber.d("launchTest -> WebData: $e") }) } } } fun getTopicQuestionWithImage(topicId: Long): List<Question> { return dao.getQuestionWithImage(topicId) } private fun getDataFromDb(topicId: Long): List<Question> { return dao.findByTopicId(topicId).map { Question( it.question.idWeb, topicId, it.question.label, it.question.img ).apply { answers = it.answers ?: listOf() } } } private fun analyseData(topicId: Long, questionsWeb: List<Question>) { val questionsId = dao.getIds() questionsWeb.forEach { qWeb -> // Update if (qWeb.idWeb in questionsId) { dao.findById(qWeb.idWeb)?.let { it.label = qWeb.label it.img = qWeb.img dao.updateQuestionAndAnswers(it) } } // New else { qWeb.topicId = topicId dao.insertQuestionAndAnswers(qWeb) } } // update time reference if (questionsWeb.isNotEmpty()) { lastCallDao.updateOrInsert(LastCall("${LastCall.TYPE_TOPIC}_$topicId", Date().time)) } } }
mit
b70b5fd3b0590361b799594c60cab653
33.156522
173
0.564553
4.8125
false
false
false
false
PolymerLabs/arcs
java/arcs/android/crdt/RawEntityProto.kt
1
1423
package arcs.android.crdt import android.os.Parcel import arcs.android.util.readProto import arcs.core.data.RawEntity /** Constructs a [RawEntity] from the given [RawEntityProto]. */ fun RawEntityProto.toRawEntity(): RawEntity { val singletons = singletonMap.mapValues { (_, referencable) -> referencable.toReferencable() } val collections = collectionMap.mapValues { (_, referencable) -> referencable.referencableList.mapTo(mutableSetOf()) { it.toReferencable()!! } } return RawEntity( id = id, singletons = singletons, collections = collections, creationTimestamp = creationTimestampMs, expirationTimestamp = expirationTimestampMs ) } /** Serializes a [RawEntity] to its proto form. */ fun RawEntity.toProto(): RawEntityProto = RawEntityProto.newBuilder() .setId(id) .putAllSingleton( singletons.mapValues { (_, referencable) -> referencable?.toProto() ?: ReferencableProto.getDefaultInstance() } ) .putAllCollection( collections.mapValues { (_, referencables) -> ReferencableSetProto.newBuilder() .addAllReferencable(referencables.map { it.toProto() }) .build() } ) .setCreationTimestampMs(creationTimestamp) .setExpirationTimestampMs(expirationTimestamp) .build() /** Reads a [RawEntity] out of a [Parcel]. */ fun Parcel.readRawEntity(): RawEntity? = readProto(RawEntityProto.getDefaultInstance())?.toRawEntity()
bsd-3-clause
3f99f24df972b9f1d28a3e7bceef2096
30.622222
81
0.718904
4.590323
false
false
false
false
ThoseGrapefruits/intellij-rust
src/main/kotlin/org/rust/lang/commenter/RustCommenter.kt
1
436
package org.rust.lang.commenter import com.intellij.lang.Commenter class RustCommenter : Commenter { override fun getLineCommentPrefix(): String = "//" override fun getBlockCommentPrefix(): String = "/*" override fun getBlockCommentSuffix(): String = "*/" // for nested comments override fun getCommentedBlockCommentPrefix(): String = "*//*" override fun getCommentedBlockCommentSuffix(): String = "*//*" }
mit
a58abd9738a20cd79076b9822869ffa1
28.066667
66
0.706422
5.069767
false
false
false
false
ingokegel/intellij-community
platform/diff-impl/tests/testSrc/com/intellij/diff/comparison/ComparisonMergeUtilTestBase.kt
8
7050
// 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.diff.comparison import com.intellij.diff.DiffTestCase import com.intellij.diff.fragments.MergeLineFragment import com.intellij.diff.util.MergeRange import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Couple import com.intellij.util.IntPair import java.util.* abstract class ComparisonMergeUtilTestBase : DiffTestCase() { private fun doCharTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?) { val iterable1 = ByCharRt.compare(texts.data2.charsSequence, texts.data1.charsSequence, CANCELLATION) val iterable2 = ByCharRt.compare(texts.data2.charsSequence, texts.data3.charsSequence, CANCELLATION) val fragments = ComparisonMergeUtil.buildSimple(iterable1, iterable2, CANCELLATION) val actual = convertDiffFragments(fragments) checkConsistency(actual, texts) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun doLineDiffTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?, policy: ComparisonPolicy) { val fragments = MANAGER.compareLines(texts.data1.charsSequence, texts.data2.charsSequence, texts.data3.charsSequence, policy, INDICATOR) val actual = convertMergeFragments(fragments) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun doLineMergeTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?, policy: ComparisonPolicy) { val fragments = MANAGER.mergeLines(texts.data1.charsSequence, texts.data2.charsSequence, texts.data3.charsSequence, policy, INDICATOR) val actual = convertMergeFragments(fragments) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun checkConsistency(actual: List<Change>, texts: Trio<Document>) { var lasts = Trio(-1, -1, -1) for (change in actual) { val starts = change.starts val ends = change.ends var empty = true var squashed = true ThreeSide.values().forEach { val start = starts(it) val end = ends(it) val last = lasts(it) assertTrue(last <= start) assertTrue(start <= end) empty = empty && (start == end) squashed = squashed && (start == last) } assertTrue(!empty) assertTrue(!squashed) lasts = ends } } private fun checkDiffChanges(actual: List<Change>, expected: List<Change>) { assertOrderedEquals(expected, actual) } private fun checkDiffMatching(changes: List<Change>, matchings: Trio<BitSet>) { val sets = Trio(BitSet(), BitSet(), BitSet()) for (change in changes) { sets.forEach { set: BitSet, side: ThreeSide -> set.set(change.start(side), change.end(side)) } } assertSetsEquals(matchings.data1, sets.data1, "Left") assertSetsEquals(matchings.data2, sets.data2, "Base") assertSetsEquals(matchings.data3, sets.data3, "Right") } private fun convertDiffFragments(fragments: List<MergeRange>): List<Change> { return fragments.map { Change( it.start1, it.end1, it.start2, it.end2, it.start3, it.end3) } } private fun convertMergeFragments(fragments: List<MergeLineFragment>): List<Change> { return fragments.map { Change( it.getStartLine(ThreeSide.LEFT), it.getEndLine(ThreeSide.LEFT), it.getStartLine(ThreeSide.BASE), it.getEndLine(ThreeSide.BASE), it.getStartLine(ThreeSide.RIGHT), it.getEndLine(ThreeSide.RIGHT)) } } internal enum class TestType { CHAR, LINE_DIFF, LINE_MERGE } internal inner class MergeTestBuilder(val type: TestType) { private var isExecuted: Boolean = false private var texts: Trio<Document>? = null private var changes: List<Change>? = null private var matching: Trio<BitSet>? = null fun assertExecuted() { assertTrue(isExecuted) } fun test() { test(ComparisonPolicy.DEFAULT) } fun test(policy: ComparisonPolicy) { isExecuted = true assertTrue(changes != null || matching != null) when (type) { TestType.CHAR -> { assertEquals(policy, ComparisonPolicy.DEFAULT) doCharTest(texts!!, changes, matching) } TestType.LINE_DIFF -> { doLineDiffTest(texts!!, changes, matching, policy) } TestType.LINE_MERGE -> { doLineMergeTest(texts!!, changes, matching, policy) } } } operator fun String.minus(v: String): Couple<String> { return Couple(this, v) } operator fun Couple<String>.minus(v: String): Helper { return Helper(Trio(this.first, this.second, v)) } inner class Helper(val matchTexts: Trio<String>) { init { if (texts == null) { texts = matchTexts.map { it -> DocumentImpl(parseSource(it)) } } } fun matching() { assertNull(matching) if (type != TestType.CHAR) { matching = matchTexts.map { it, side -> parseLineMatching(it, texts!!(side)) } } else { matching = matchTexts.map { it, side -> parseMatching(it, texts!!(side)) } } } } fun changes(vararg expected: Change) { assertNull(changes) changes = listOf(*expected) } fun mod(line1: Int, line2: Int, line3: Int, count1: Int, count2: Int, count3: Int): Change { return Change(line1, line1 + count1, line2, line2 + count2, line3, line3 + count3) } } internal fun chars(f: MergeTestBuilder.() -> Unit) { doTest(TestType.CHAR, f) } internal fun lines_diff(f: MergeTestBuilder.() -> Unit) { doTest(TestType.LINE_DIFF, f) } internal fun lines_merge(f: MergeTestBuilder.() -> Unit) { doTest(TestType.LINE_MERGE, f) } internal fun doTest(type: TestType, f: MergeTestBuilder.() -> Unit) { val builder = MergeTestBuilder(type) builder.f() builder.assertExecuted() } class Change(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int) : Trio<IntPair>(IntPair(start1, end1), IntPair(start2, end2), IntPair(start3, end3)) { val start1 = start(ThreeSide.LEFT) val start2 = start(ThreeSide.BASE) val start3 = start(ThreeSide.RIGHT) val end1 = end(ThreeSide.LEFT) val end2 = end(ThreeSide.BASE) val end3 = end(ThreeSide.RIGHT) val starts = Trio(start1, start2, start3) val ends = Trio(end1, end2, end3) fun start(side: ThreeSide): Int = this(side).first fun end(side: ThreeSide): Int = this(side).second override fun toString(): String { return "($start1, $end1) - ($start2, $end2) - ($start3, $end3)" } } }
apache-2.0
8c954938832c81268ccf1f32deef88cd
30.333333
140
0.666241
4.030875
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/KlibMetaFileIndex.kt
1
1351
// 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.vfilefinder import com.intellij.util.indexing.DefaultFileTypeSpecificInputFilter import org.jetbrains.kotlin.idea.base.psi.fileTypes.KlibMetaFileType import org.jetbrains.kotlin.idea.klib.KlibLoadingMetadataCache import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf import org.jetbrains.kotlin.name.FqName object KlibMetaFileIndex : KotlinFileIndexBase<KlibMetaFileIndex>(KlibMetaFileIndex::class.java) { override fun getIndexer() = INDEXER override fun getInputFilter() = DefaultFileTypeSpecificInputFilter(KlibMetaFileType) override fun getVersion() = VERSION // This is to express intention to index all Kotlin/Native metadata files irrespectively to file size: override fun getFileTypesWithSizeLimitNotApplicable() = listOf(KlibMetaFileType) private const val VERSION = 4 /*todo: check version?!*/ private val INDEXER = indexer { fileContent -> val fragment = KlibLoadingMetadataCache .getInstance().getCachedPackageFragment(fileContent.file) if (fragment != null) FqName(fragment.getExtension(KlibMetadataProtoBuf.fqName)) else null } }
apache-2.0
488aedcafed806e097a6c2ea4d9d7f44
41.25
158
0.76832
4.807829
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/compiler-plugins/sam-with-receiver/common/src/org/jetbrains/kotlin/idea/compilerPlugin/samWithReceiver/IdeSamWithReceiverComponentContributor.kt
4
3019
// 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.compilerPlugin.samWithReceiver import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootModificationTracker import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.container.StorageComponentContainer import org.jetbrains.kotlin.container.useInstance import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptDependenciesInfo import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleProductionSourceInfo import org.jetbrains.kotlin.idea.compilerPlugin.getSpecialAnnotations import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverPluginNames.ANNOTATION_OPTION_NAME import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverPluginNames.PLUGIN_ID import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverResolverExtension class IdeSamWithReceiverComponentContributor(val project: Project) : StorageComponentContainerContributor { private companion object { val ANNOTATION_OPTION_PREFIX = "plugin:$PLUGIN_ID:${ANNOTATION_OPTION_NAME}=" } private val cache = CachedValuesManager.getManager(project).createCachedValue({ Result.create( ContainerUtil.createConcurrentWeakMap<Module, List<String>>(), ProjectRootModificationTracker.getInstance( project ) ) }, /* trackValue = */ false) private fun getAnnotationsForModule(module: Module): List<String> { return cache.value.getOrPut(module) { module.getSpecialAnnotations(ANNOTATION_OPTION_PREFIX) } } override fun registerModuleComponents( container: StorageComponentContainer, platform: TargetPlatform, moduleDescriptor: ModuleDescriptor ) { if (!platform.isJvm()) return val annotations = when (val moduleInfo = moduleDescriptor.getCapability(ModuleInfo.Capability)) { is ScriptModuleInfo -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers is ScriptDependenciesInfo.ForFile -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers is ModuleProductionSourceInfo -> getAnnotationsForModule(moduleInfo.module) else -> null } ?: return container.useInstance(SamWithReceiverResolverExtension(annotations)) } }
apache-2.0
a35307b7216dbdb5940be40b6b30a0f8
47.693548
158
0.783041
5.391071
false
false
false
false
DanielGrech/anko
dsl/src/org/jetbrains/android/anko/config/Props.kt
3
2378
/* * Copyright 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 org.jetbrains.android.anko.config import java.io.File import java.util.ArrayList import java.util.HashMap import kotlin.properties.Delegates class Variable(val name: String, val type: String) { override fun toString(): String { return "$name:$type" } } object Props { val imports: Map<String, String> by Delegates.lazy { val map = hashMapOf<String, String>() File("dsl/props") .listFiles { it.name.startsWith("imports_") && it.name.endsWith(".txt") } ?.forEach { val name = it.name.replace(".txt", "") map.put(name.substring(name.indexOf('_') + 1), it.readText()) } map } val helperConstructors: Map<String, List<List<Variable>>> by Delegates.lazy { val res = HashMap<String, ArrayList<List<Variable>>>() val lines = File("dsl/props/helper_constructors.txt").readLines() for (line in lines.filter { it.isNotEmpty() && !it.startsWith('#') }) { try { val separator = line.indexOf(' ') val className = line.substring(0, separator) val props = line.substring(separator + 1).split(',').map { val nameType = it.split(":".toRegex()).toTypedArray() Variable(nameType[0].trim(), nameType[1].trim()) }.toList() val constructors = res.getOrElse(className, { ArrayList<List<Variable>>() }) constructors.add(props) res.put(className, constructors) } catch (e: ArrayIndexOutOfBoundsException) { throw RuntimeException("Failed to tokenize string, malformed helper_constructors.txt") } } res } }
apache-2.0
cefdd12f8086d2da2a3b94075ba10371
36.171875
102
0.608495
4.428305
false
false
false
false
WeAreFrancis/auth-service
src/main/kotlin/com/wearefrancis/auth/dto/mapper/ReadUserByAdminDTOMapper.kt
1
569
package com.wearefrancis.auth.dto.mapper import com.wearefrancis.auth.domain.User import com.wearefrancis.auth.dto.ReadUserByAdminDTO import org.springframework.stereotype.Component @Component open class ReadUserByAdminDTOMapper : Mapper<User, ReadUserByAdminDTO> { override fun convert(model: User): ReadUserByAdminDTO = ReadUserByAdminDTO( email = model.email, enabled = model.enabled, id = model.id, locked = !model.isAccountNonLocked, role = model.role, username = model.username ) }
apache-2.0
08b3266076e105d1ff88fa672343b275
32.529412
79
0.699473
4.410853
false
false
false
false
icela/FriceEngine
src/org/frice/platform/adapter/JvmDrawer.kt
1
2741
package org.frice.platform.adapter import org.frice.obj.button.FText import org.frice.platform.FriceDrawer import org.frice.platform.FriceImage import org.frice.resource.graphics.ColorResource import org.frice.util.cast import org.frice.util.forceRun import java.awt.* /** * Created by ice1000 on 2016/10/31. * * @author ice1000 */ class JvmDrawer(private val frame: Frame) : FriceDrawer { override fun init() { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) } val friceImage = JvmImage(frame.width, frame.height) override var color: ColorResource get() = ColorResource(g.color) set(value) { g.color = value.`get reused color`() } var g: Graphics2D = cast(friceImage.image.graphics) override fun stringSize(size: Double) { g.font = g.font.deriveFont(size.toFloat()) } override fun useFont(text: FText) { if (text.`font tmp obj` == null) text.`font tmp obj` = Font(text.fontName, Font.PLAIN, text.textSize.toInt()) if (g.font != text.`font tmp obj`) g.font = cast(text.`font tmp obj`) } override fun drawOval(x: Double, y: Double, width: Double, height: Double) = g.fillOval(x.toInt(), y.toInt(), width.toInt(), height.toInt()) override fun strokeOval(x: Double, y: Double, width: Double, height: Double) = g.fillOval(x.toInt(), y.toInt(), width.toInt(), height.toInt()) override fun drawString(string: String, x: Double, y: Double) = g.drawString(string, x.toInt(), y.toInt()) override fun drawImage(image: FriceImage, x: Double, y: Double) { g.drawImage(cast<JvmImage>(image).image, x.toInt(), y.toInt(), frame) } override fun drawRect(x: Double, y: Double, width: Double, height: Double) = g.fillRect(x.toInt(), y.toInt(), width.toInt(), height.toInt()) override fun strokeRect(x: Double, y: Double, width: Double, height: Double) = g.drawRect(x.toInt(), y.toInt(), width.toInt(), height.toInt()) override fun drawLine(x: Double, y: Double, width: Double, height: Double) = g.drawLine(x.toInt(), y.toInt(), width.toInt(), height.toInt()) override fun rotate(theta: Double, x: Double, y: Double) = g.rotate(theta, x, y) override fun rotate(theta: Double) = g.rotate(theta) override fun drawRoundRect( x: Double, y: Double, width: Double, height: Double, arcWidth: Double, arcHeight: Double) = g.fillRoundRect(x.toInt(), y.toInt(), width.toInt(), height.toInt(), arcWidth.toInt(), arcHeight.toInt()) override fun strokeRoundRect( x: Double, y: Double, width: Double, height: Double, arcWidth: Double, arcHeight: Double) = g.drawRoundRect(x.toInt(), y.toInt(), width.toInt(), height.toInt(), arcWidth.toInt(), arcHeight.toInt()) override fun restore() { g = cast(friceImage.image.graphics) } }
agpl-3.0
f95a5638ef35b8cbcd626e1a21611aec
30.517241
111
0.699745
3.136156
false
false
false
false
davidcrotty/Hercules
app/src/main/java/net/davidcrotty/hercules/presenter/ExercisePresenter.kt
1
3858
package net.davidcrotty.hercules.presenter import android.content.res.Resources import net.davidcrotty.hercules.R import net.davidcrotty.hercules.model.Set import net.davidcrotty.hercules.view.ExerciseView import net.davidcrotty.hercules.view.Skippable import org.joda.time.Period import org.joda.time.format.PeriodFormatter import org.joda.time.format.PeriodFormatterBuilder /** * Created by David Crotty on 16/09/2017. * * Copyright © 2017 David Crotty - All Rights Reserved */ class ExercisePresenter(private val view: ExerciseView) { var currentTrackIndex: Int? = null set(value) { field = value } var currentSetList: ArrayList<Set>? = null private val MS_SCALAR = 1000L private val timeFormat: PeriodFormatter by lazy { PeriodFormatterBuilder() .printZeroAlways() .minimumPrintedDigits(2) .maximumParsedDigits(2) .appendMinutes() .appendSeparator(":") .printZeroAlways() .minimumPrintedDigits(2) .maximumParsedDigits(2) .appendSeconds() .toFormatter() } fun initializeSetsFrom(setList: ArrayList<Set>) { currentSetList = setList if(setList.isEmpty()) return for(i in 0 until setList.size) run { view.addSet(setList[i], i + 1) } currentTrackIndex = 0 val first = setList.first() resetUiUsing(first) } fun showTitlesFrom(resources: Resources, setList: ArrayList<Set>) { if(setList.isEmpty()) return val index = currentTrackIndex ?: return view.updateTitle(setList[index].title) view.updateSubtitle(resources.getString(R.string.plan_subtitle, setList.size, setList.first().repitions)) updateNextUp(resources, index) } fun nextSet(skippable: Skippable, resources: Resources) { var index = currentTrackIndex ?: return val setList = currentSetList ?: return skippable.next(index) index++ if(index >= setList.size) { index = setList.size } traverseSetUsing(index, resources) } fun previousSet(skippable: Skippable, resources: Resources) { var index = currentTrackIndex ?: return index-- if(index < 0) { index = 0 } skippable.previous(index) traverseSetUsing(index, resources) } private fun traverseSetUsing(index: Int, resources: Resources) { currentTrackIndex = index currentSetList?.let { if(index >= it.size || index < 0) return@let val set = it[index] resetUiUsing(set) view.updateTitle(it[index].title) updateNextUp(resources, index) view.updateReps(set.repitions) view.updateTimeRemaining(timeFrom(set.timeSeconds)) view.updateTimerComponents(set.timeSeconds, set.repitions, index) } } private fun updateNextUp(resources: Resources, index: Int) { val next = currentSetList?.peek(index + 1) if(next == null) { view.updateNextUp(resources.getString(R.string.plan_done)) } else { view.updateNextUp(resources.getString(R.string.plan_next, next.repitions, next.title)) } } fun timeFrom(seconds: Int) : String { val period = Period(seconds.toLong() * MS_SCALAR) return timeFormat.print(period) } private fun resetUiUsing(nextSet: Set) { val time = timeFrom(nextSet.timeSeconds) view.resetMainProgress(nextSet.repitions, time, nextSet.timeSeconds) } } private fun java.util.ArrayList<Set>.peek(index: Int) : Set? { if(index >= this.size) return null return this[index] }
mit
db1fca789308d7f3873a27eeada0c4f6
32.25
113
0.62069
4.387941
false
false
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/archive/Zip.kt
1
1407
package com.beust.kobalt.archive import com.beust.kobalt.Glob import com.beust.kobalt.IFileSpec import com.beust.kobalt.api.annotation.Directive import com.beust.kobalt.misc.From import com.beust.kobalt.misc.IncludedFile import com.beust.kobalt.misc.To open class Zip(open var name: String? = null) { val excludes = arrayListOf<Glob>() @Directive fun from(s: String) = From(s) @Directive fun to(s: String) = To(s) @Directive fun exclude(vararg files: String) { files.forEach { excludes.add(Glob(it)) } } @Directive fun exclude(vararg specs: Glob) { specs.forEach { excludes.add(it) } } @Directive fun include(vararg files: String) { includedFiles.add(IncludedFile(files.map { IFileSpec.FileSpec(it) })) } @Directive fun include(from: From, to: To, vararg specs: String) { includedFiles.add(IncludedFile(from, to, specs.map { IFileSpec.FileSpec(it) })) } @Directive fun include(from: From, to: To, vararg specs: IFileSpec.GlobSpec) { includedFiles.add(IncludedFile(from, to, listOf(*specs))) } /** * Prefix path to be removed from the zip file. For example, if you add "build/lib/a.jar" to the zip * file and the excludePrefix is "build/lib", then "a.jar" will be added at the root of the zip file. */ val includedFiles = arrayListOf<IncludedFile>() }
apache-2.0
756fd758a32d9b3336181ed4f41594cd
26.057692
105
0.665956
3.664063
false
false
false
false
ktorio/ktor
ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/Keys.kt
1
2291
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls import javax.crypto.* import javax.crypto.spec.* private val MASTER_SECRET_LABEL = "master secret".toByteArray() private val KEY_EXPANSION_LABEL = "key expansion".toByteArray() internal val CLIENT_FINISHED_LABEL = "client finished".toByteArray() internal val SERVER_FINISHED_LABEL = "server finished".toByteArray() internal fun ByteArray.clientMacKey(suite: CipherSuite): SecretKeySpec = SecretKeySpec( this, 0, suite.macStrengthInBytes, suite.hash.macName ) internal fun ByteArray.serverMacKey(suite: CipherSuite): SecretKeySpec = SecretKeySpec( this, suite.macStrengthInBytes, suite.macStrengthInBytes, suite.hash.macName ) internal fun ByteArray.serverKey(suite: CipherSuite): SecretKeySpec = SecretKeySpec( this, 2 * suite.macStrengthInBytes + suite.keyStrengthInBytes, suite.keyStrengthInBytes, suite.jdkCipherName.substringBefore("/") ) internal fun ByteArray.clientKey(suite: CipherSuite): SecretKeySpec = SecretKeySpec( this, 2 * suite.macStrengthInBytes, suite.keyStrengthInBytes, suite.jdkCipherName.substringBefore("/") ) internal fun ByteArray.clientIV(suite: CipherSuite): ByteArray = copyOfRange( 2 * suite.macStrengthInBytes + 2 * suite.keyStrengthInBytes, 2 * suite.macStrengthInBytes + 2 * suite.keyStrengthInBytes + suite.fixedIvLength ) internal fun ByteArray.serverIV(suite: CipherSuite): ByteArray = copyOfRange( 2 * suite.macStrengthInBytes + 2 * suite.keyStrengthInBytes + suite.fixedIvLength, 2 * suite.macStrengthInBytes + 2 * suite.keyStrengthInBytes + 2 * suite.fixedIvLength ) internal fun keyMaterial( masterSecret: SecretKey, seed: ByteArray, keySize: Int, macSize: Int, ivSize: Int ): ByteArray { val materialSize = 2 * macSize + 2 * keySize + 2 * ivSize return PRF(masterSecret, KEY_EXPANSION_LABEL, seed, materialSize) } internal fun masterSecret( preMasterSecret: SecretKey, clientRandom: ByteArray, serverRandom: ByteArray ): SecretKeySpec = SecretKeySpec( PRF(preMasterSecret, MASTER_SECRET_LABEL, clientRandom + serverRandom, 48), preMasterSecret.algorithm )
apache-2.0
17a0096e778d2379da55212f9fc18bdb
30.819444
119
0.749018
4.290262
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-core/common/src/io/ktor/client/statement/HttpStatement.kt
1
4587
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.statement import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.engine.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.client.utils.* import io.ktor.http.* import io.ktor.util.* import io.ktor.utils.io.* import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* import kotlinx.coroutines.* /** * Prepared statement for a HTTP client request. * This statement doesn't perform any network requests until [execute] method call. * [HttpStatement] is safe to execute multiple times. * * Example: [Streaming data](https://ktor.io/docs/response.html#streaming) */ public class HttpStatement( private val builder: HttpRequestBuilder, @PublishedApi internal val client: HttpClient ) { init { checkCapabilities() } /** * Executes this statement and calls the [block] with the streaming [response]. * * The [response] argument holds a network connection until the [block] isn't completed. You can read the body * on-demand or at once with [body<T>()] method. * * After [block] finishes, [response] will be completed body will be discarded or released depends on the engine configuration. * * Please note: the [response] instance will be canceled and shouldn't be passed outside of [block]. */ public suspend fun <T> execute(block: suspend (response: HttpResponse) -> T): T = unwrapRequestTimeoutException { val response = executeUnsafe() try { return block(response) } finally { response.cleanup() } } /** * Executes this statement and download the response. * After the method execution finishes, the client downloads the response body in memory and release the connection. * * To receive exact type, consider using [body<T>()] method. */ public suspend fun execute(): HttpResponse = execute { val savedCall = it.call.save() savedCall.response } /** * Executes this statement and runs [HttpClient.responsePipeline] with the response and expected type [T]. * * Note if T is a streaming type, you should manage how to close it manually. */ @OptIn(InternalAPI::class) public suspend inline fun <reified T> body(): T = unwrapRequestTimeoutException { val response = executeUnsafe() return try { response.body() } finally { response.complete() } } /** * Executes this statement and runs the [block] with a [HttpClient.responsePipeline] execution result. * * Note that T can be a streamed type such as [ByteReadChannel]. */ public suspend inline fun <reified T, R> body( crossinline block: suspend (response: T) -> R ): R = unwrapRequestTimeoutException { val response: HttpResponse = executeUnsafe() try { val result = response.body<T>() return block(result) } finally { response.cleanup() } } /** * Returns [HttpResponse] with open streaming body. */ @PublishedApi @OptIn(InternalAPI::class) internal suspend fun executeUnsafe(): HttpResponse = unwrapRequestTimeoutException { val builder = HttpRequestBuilder().takeFromWithExecutionContext(builder) val call = client.execute(builder) return call.response } /** * Completes [HttpResponse] and releases resources. */ @PublishedApi @OptIn(InternalAPI::class) internal suspend fun HttpResponse.cleanup() { val job = coroutineContext[Job]!! as CompletableJob job.apply { complete() try { content.cancel() } catch (_: Throwable) { } join() } } /** * Checks that all request configuration related to client capabilities have correspondent plugin installed. */ private fun checkCapabilities() { builder.attributes.getOrNull(ENGINE_CAPABILITIES_KEY)?.keys ?.filterIsInstance<HttpClientPlugin<*, *>>() ?.forEach { requireNotNull(client.pluginOrNull(it)) { "Consider installing $it plugin because the request requires it to be installed" } } } override fun toString(): String = "HttpStatement[${builder.url.buildString()}]" }
apache-2.0
8f2f45cc957015351fd808babc626cae
30.854167
131
0.636364
4.65213
false
false
false
false
adrianswiatek/price-comparator
PriceComparator/app/src/main/java/com/aswiatek/pricecomparator/activities/MainActivity.kt
1
4181
package com.aswiatek.pricecomparator.activities import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.view.View import android.widget.Button import android.widget.ImageButton import com.aswiatek.pricecomparator.R import com.aswiatek.pricecomparator.adapters.CardsAdapter import com.aswiatek.pricecomparator.buisinesslogic.ScreensConductor import com.aswiatek.pricecomparator.buisinesslogic.screenmodes.ModeGetter import com.aswiatek.pricecomparator.infrastructure.MyApplication import com.aswiatek.pricecomparator.model.Card import com.squareup.otto.Bus import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_main_displays.* class MainActivity : AppCompatActivity() { lateinit private var bus: Bus lateinit private var mScreensConductor: ScreensConductor lateinit private var mCardsAdapter: CardsAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bus = (application as MyApplication).bus bus.register(this) setContentView(R.layout.activity_main) mScreensConductor = ScreensConductor .create(digit_screen, description_screen, ModeGetter(), bus) initializeAddFloatingButton() initializeCards() } override fun onDestroy() { super.onDestroy() bus.unregister(this) } private fun initializeAddFloatingButton() { fab.setOnClickListener { val previousCard = mCardsAdapter.getActiveOrEmpty() val newCard = Card(targetQuantity = previousCard.targetQuantity) mCardsAdapter.add(newCard) cards.scrollToPosition(0) } } private fun initializeCards() { cards.setHasFixedSize(true) cards.layoutManager = LinearLayoutManager(this) cards.itemAnimator = DefaultItemAnimator() mCardsAdapter = CardsAdapter(this, mutableListOf(Card()), bus) cards.adapter = mCardsAdapter initializeCardsTouchEvents() } private fun initializeCardsTouchEvents() { val callback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) { override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) = false override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { if (direction != ItemTouchHelper.LEFT && direction != ItemTouchHelper.RIGHT) return val position = viewHolder.adapterPosition mCardsAdapter.removeAt(position) Snackbar .make(viewHolder.itemView, getString(R.string.the_card_has_been_removed), Snackbar.LENGTH_LONG) .setAction(resources.getText(R.string.undo_upper_case)) { mCardsAdapter.restore() } .show() } } ItemTouchHelper(callback).attachToRecyclerView(cards) } fun onKeyClicked(view: View) { when (view) { is Button -> handleButton(view) is ImageButton -> handleImageButton(view) } } fun handleButton(button: Button) { val buttonText = button.text.toString() if (mScreensConductor.canBeHandled(buttonText)) { mScreensConductor.handle(buttonText) } } fun handleImageButton(imageButton: ImageButton) { if (isForwardButton(imageButton)) { mScreensConductor.nextMode() } else if (isBackButton(imageButton)) { mScreensConductor.previousMode() } } private fun isForwardButton(imageButton: ImageButton) = imageButton.contentDescription == resources.getText(R.string.forward) private fun isBackButton(imageButton: ImageButton) = imageButton.contentDescription == resources.getText(R.string.back) }
mit
27b4b510aab913a1f24ae6a410358880
35.684211
137
0.706051
5.136364
false
false
false
false
MichaelRocks/grip
library/src/test/java/io/michaelrocks/mockito/MockitoExtension.kt
1
3905
/* * Copyright 2021 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.mockito import org.mockito.InOrder import org.mockito.MockSettings import org.mockito.MockingDetails import org.mockito.Mockito import org.mockito.stubbing.Answer import org.mockito.stubbing.OngoingStubbing import org.mockito.stubbing.Stubber import org.mockito.verification.VerificationAfterDelay import org.mockito.verification.VerificationMode import org.mockito.verification.VerificationWithTimeout val RETURNS_DEFAULTS: Answer<Any> get() = Mockito.RETURNS_DEFAULTS val RETURNS_SMART_NULLS: Answer<Any> get() = Mockito.RETURNS_SMART_NULLS val RETURNS_MOCKS: Answer<Any> get() = Mockito.RETURNS_MOCKS val RETURNS_DEEP_STUBS: Answer<Any> get() = Mockito.RETURNS_DEEP_STUBS val CALLS_REAL_METHODS: Answer<Any> get() = Mockito.CALLS_REAL_METHODS inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java) inline fun <reified T : Any> mock(name: String): T = Mockito.mock(T::class.java, name) inline fun <reified T : Any> mock(defaultAnswer: Answer<Any>): T = Mockito.mock(T::class.java, defaultAnswer) inline fun <reified T : Any> mock(mockSettings: MockSettings): T = Mockito.mock(T::class.java, mockSettings) fun mockingDetails(toInspect: Any): MockingDetails = Mockito.mockingDetails(toInspect) fun <T> spy(instance: T): T = Mockito.spy(instance) inline fun <reified T : Any> spy(): T = Mockito.spy(T::class.java) fun <T> given(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall) fun <T> verify(mock: T): T = Mockito.verify(mock) fun <T> verify(mock: T, mode: VerificationMode = times(1)): T = Mockito.verify(mock, mode) fun verifyNoMoreInteractions(vararg mocks: Any) = Mockito.verifyNoMoreInteractions(*mocks) fun verifyZeroInteractions(vararg mocks: Any) = Mockito.verifyNoInteractions(*mocks) fun <T> reset(vararg mocks: T) = Mockito.reset(*mocks) fun doThrow(toBeThrown: Throwable): Stubber = Mockito.doThrow(toBeThrown) inline fun <reified T : Throwable> doThrow(): Stubber = Mockito.doThrow(T::class.java) fun doCallRealMethod(): Stubber = Mockito.doCallRealMethod() fun doAnswer(answer: Answer<Any>): Stubber = Mockito.doAnswer(answer) fun doNothing(): Stubber = Mockito.doNothing() fun doReturn(toBeReturned: Any): Stubber = Mockito.doReturn(toBeReturned) fun inOrder(vararg mocks: Any): InOrder = Mockito.inOrder(*mocks) fun ignoreStubs(vararg mocks: Any): Array<Any> = Mockito.ignoreStubs(*mocks) fun times(wantedNumberOfInvocations: Int): VerificationMode = Mockito.times(wantedNumberOfInvocations) fun never(): VerificationMode = Mockito.never() fun atLeastOnce(): VerificationMode = Mockito.atLeastOnce() fun atLeast(minNumberOfInvocations: Int): VerificationMode = Mockito.atLeast(minNumberOfInvocations) fun atMost(maxNumberOfInvocations: Int): VerificationMode = Mockito.atMost(maxNumberOfInvocations) fun calls(wantedNumberOfInvocations: Int): VerificationMode = Mockito.calls(wantedNumberOfInvocations) fun only(): VerificationMode = Mockito.only() fun timeout(millis: Long): VerificationWithTimeout = Mockito.timeout(millis) fun after(millis: Long): VerificationAfterDelay = Mockito.after(millis) fun validateMockitoUsage() = Mockito.validateMockitoUsage() fun withSettings(): MockSettings = Mockito.withSettings() fun description(description: String): VerificationMode = Mockito.description(description)
apache-2.0
8fe37cbb18e1b2f0379af4936901c110
44.406977
109
0.778233
4.013361
false
false
false
false
fabianonline/telegram_backup
src/main/kotlin/de/fabianonline/telegram_backup/exporter/CSVExporter.kt
1
4078
/* Telegram_Backup * Copyright (C) 2016 Fabian Schlenz * * 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 de.fabianonline.telegram_backup.exporter import java.io.File import java.io.PrintWriter import java.io.OutputStreamWriter import java.io.FileOutputStream import java.nio.charset.Charset import java.io.FileWriter import java.io.IOException import java.io.FileNotFoundException import java.net.URL import org.apache.commons.io.FileUtils import java.util.LinkedList import java.util.HashMap import java.time.LocalDate import java.time.LocalTime import java.time.LocalDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.sql.Time import java.text.SimpleDateFormat import com.github.mustachejava.DefaultMustacheFactory import com.github.mustachejava.Mustache import com.github.mustachejava.MustacheFactory import de.fabianonline.telegram_backup.* import com.github.badoualy.telegram.tl.api.* import com.google.gson.* import com.github.salomonbrys.kotson.* import org.slf4j.Logger import org.slf4j.LoggerFactory class CSVExporter(val db: Database, val file_base: String, val settings: Settings) { val logger = LoggerFactory.getLogger(CSVExporter::class.java) val mustache = DefaultMustacheFactory().compile("templates/csv/messages.csv") val dialogs = db.getListOfDialogsForExport() val chats = db.getListOfChatsForExport() val datetime_format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val base = file_base + "files" + File.separatorChar fun export() { val today = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT) val timezone = ZoneOffset.systemDefault() val days = if (settings.max_file_age==-1) 7 else settings.max_file_age // Create base dir logger.debug("Creating base dir") File(base).mkdirs() if (days > 0) { for (dayOffset in days downTo 1) { val day = today.minusDays(dayOffset.toLong()) val start = day.toEpochSecond(timezone.rules.getOffset(day)) val end = start + 24 * 60 * 60 val filename = base + "messages.${day.format(DateTimeFormatter.ISO_LOCAL_DATE)}.csv" if (!File(file_base + filename).exists()) { logger.debug("Range: {} to {}", start, end) println("Processing messages for ${day}...") exportToFile(start, end, filename) } } } else { println("Processing all messages...") exportToFile(0, Long.MAX_VALUE, base + "messages.all.csv") } } fun exportToFile(start: Long, end: Long, filename: String) { val list = mutableListOf<Map<String, String?>>() db.getMessagesForCSVExport(start, end) {data: HashMap<String, Any> -> val scope = HashMap<String, String?>() val timestamp = data["time"] as Time scope.put("time", datetime_format.format(timestamp)) scope.put("username", if (data["user_username"]!=null) data["user_username"] as String else null) if (data["source_type"]=="dialog") { scope.put("chat_name", "@" + (dialogs.firstOrNull{it.id==data["source_id"]}?.username ?: "")) } else { scope.put("chat_name", chats.firstOrNull{it.id==data["source_id"]}?.name) } scope.put("message", data["message"] as String) list.add(scope) } val writer = getWriter(filename) mustache.execute(writer, mapOf("messages" to list)) writer.close() } private fun getWriter(filename: String): OutputStreamWriter { logger.trace("Creating writer for file {}", filename.anonymize()) return OutputStreamWriter(FileOutputStream(filename), Charset.forName("UTF-8").newEncoder()) } }
gpl-3.0
6d06f24643fda6c57f342722e76e617d
35.738739
100
0.733203
3.660682
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/imports/internal/conflicts/BaseConflictShould.kt
1
3211
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.imports.internal.conflicts import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.dataelement.DataElement import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute import org.junit.Before internal open class BaseConflictShould { protected val context: TrackerImportConflictItemContext = mock() protected val attributeStore: IdentifiableObjectStore<TrackedEntityAttribute> = mock() protected val dataElementStore: IdentifiableObjectStore<DataElement> = mock() protected val attribute: TrackedEntityAttribute = mock() protected val dataElement: DataElement = mock() protected val attributeUid = "DI85uC13Bzo" protected val value = "attribute value" protected val optionSetUid = "Q2nhc0pmcZ8" protected val dataElementUid = "NTlMmRqGWCM" protected val eventUid = "ohAH6BXIMad" protected val enrollmentUid = "tliijiEnCp5" protected val relatedTeiUid = "QGyxOe1zewj" protected val teiUid = "9iKols8763J" protected val fileResourceUid = "V8co7IqOJsS" protected val relationshipUid = "AJOytZW7OaI" @Before fun setUp() { whenever(context.attributeStore) doReturn attributeStore whenever(context.dataElementStore) doReturn dataElementStore whenever(attributeStore.selectByUid(attributeUid)) doReturn attribute whenever(dataElementStore.selectByUid(dataElementUid)) doReturn dataElement } }
bsd-3-clause
585a7687b87fd9fe8429a56d8b8d6456
45.536232
90
0.777017
4.478382
false
true
false
false
dahlstrom-g/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddSdkGroupPanel.kt
10
3598
/* * 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.sdk.add import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.components.JBRadioButton import com.intellij.util.ui.FormBuilder import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import java.awt.BorderLayout import javax.swing.ButtonGroup import javax.swing.Icon import javax.swing.JPanel /** * @author vlan */ class PyAddSdkGroupPanel(private val nameGetter: java.util.function.Supplier<@Nls String>, panelIcon: Icon, val panels: List<PyAddSdkPanel>, defaultPanel: PyAddSdkPanel) : PyAddSdkPanel() { override val panelName: String get() = nameGetter.get() // NON-NLS override val icon: Icon = panelIcon var selectedPanel: PyAddSdkPanel = defaultPanel private val changeListeners: MutableList<Runnable> = mutableListOf() override var newProjectPath: String? get() = selectedPanel.newProjectPath set(value) { for (panel in panels) { panel.newProjectPath = value } } init { layout = BorderLayout() val contentPanel = when (panels.size) { 1 -> panels[0] else -> createRadioButtonPanel(panels, defaultPanel) } add(contentPanel, BorderLayout.NORTH) } override fun validateAll(): List<ValidationInfo> = panels.filter { it.isEnabled }.flatMap { it.validateAll() } override val sdk: Sdk? get() = selectedPanel.sdk override fun getOrCreateSdk(): Sdk? = selectedPanel.getOrCreateSdk() override fun addChangeListener(listener: Runnable) { changeListeners += listener for (panel in panels) { panel.addChangeListener(listener) } } private fun createRadioButtonPanel(panels: List<PyAddSdkPanel>, defaultPanel: PyAddSdkPanel): JPanel { val buttonMap = panels.map { JBRadioButton(it.panelName) to it }.toMap(linkedMapOf()) ButtonGroup().apply { for (button in buttonMap.keys) { add(button) } } val formBuilder = FormBuilder.createFormBuilder() for ((button, panel) in buttonMap) { panel.border = JBUI.Borders.emptyLeft(30) val name = JPanel(BorderLayout()).apply { val inner = JPanel().apply { add(button) panel.nameExtensionComponent?.also { add(it) } } add(inner, BorderLayout.WEST) } formBuilder.addComponent(name) formBuilder.addComponent(panel) button.addItemListener { for (c in panels) { UIUtil.setEnabled(c, c == panel, true) c.nameExtensionComponent?.let { UIUtil.setEnabled(it, c == panel, true) } } if (button.isSelected) { selectedPanel = panel for (listener in changeListeners) { listener.run() } } } } buttonMap.filterValues { it == defaultPanel }.keys.first().isSelected = true return formBuilder.panel } }
apache-2.0
87c468d0f1861d9e75aa653d7c6490a6
31.718182
112
0.67343
4.447466
false
false
false
false
dahlstrom-g/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRListSearchValue.kt
1
3310
// 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.plugins.github.pullrequest.ui.toolwindow import com.intellij.collaboration.ui.codereview.list.search.ReviewListSearchValue import kotlinx.serialization.Serializable import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.pullrequest.data.GHPRSearchQuery import org.jetbrains.plugins.github.pullrequest.data.GHPRSearchQuery.QualifierName import org.jetbrains.plugins.github.pullrequest.data.GHPRSearchQuery.Term import org.jetbrains.plugins.github.pullrequest.data.GHPRSearchQuery.Term.Qualifier import org.jetbrains.plugins.github.pullrequest.data.GHPRSearchQuery.Term.QueryPart @Serializable internal data class GHPRListSearchValue(override val searchQuery: String? = null, val state: State? = null, val assignee: String? = null, val reviewState: ReviewState? = null, val author: String? = null, val label: String? = null) : ReviewListSearchValue { override val isEmpty = searchQuery == null && state == null && assignee == null && reviewState == null && author == null && label == null fun toQuery(): GHPRSearchQuery? { val terms = mutableListOf<Term<*>>() if (searchQuery != null) { terms.add(QueryPart(searchQuery)) } if (state != null) { val term = when (state) { State.OPEN -> Qualifier.Enum(QualifierName.`is`, GithubIssueState.open) State.CLOSED -> Qualifier.Enum(QualifierName.`is`, GithubIssueState.closed) State.MERGED -> Qualifier.Simple(QualifierName.`is`, "merged") } terms.add(term) } if (assignee != null) { terms.add(Qualifier.Simple(QualifierName.assignee, assignee)) } if (reviewState != null) { val term = when (reviewState) { ReviewState.NO_REVIEW -> Qualifier.Simple(QualifierName.review, "none") ReviewState.REQUIRED -> Qualifier.Simple(QualifierName.review, "required") ReviewState.APPROVED -> Qualifier.Simple(QualifierName.review, "approved") ReviewState.CHANGES_REQUESTED -> Qualifier.Simple(QualifierName.review, "changes-requested") ReviewState.REVIEWED_BY_ME -> Qualifier.Simple(QualifierName.reviewedBy, "@me") ReviewState.NOT_REVIEWED_BY_ME -> Qualifier.Simple(QualifierName.reviewedBy, "@me").not() ReviewState.AWAITING_REVIEW -> Qualifier.Simple(QualifierName.reviewRequested, "@me") } terms.add(term) } if (author != null) { terms.add(Qualifier.Simple(QualifierName.author, author)) } if (label != null) { terms.add(Qualifier.Simple(QualifierName.label, label)) } if (terms.isEmpty()) return null return GHPRSearchQuery(terms) } companion object { val DEFAULT = GHPRListSearchValue(state = State.OPEN) val EMPTY = GHPRListSearchValue() } enum class State { OPEN, CLOSED, MERGED } enum class ReviewState { NO_REVIEW, REQUIRED, APPROVED, CHANGES_REQUESTED, REVIEWED_BY_ME, NOT_REVIEWED_BY_ME, AWAITING_REVIEW } }
apache-2.0
72e966595b28ba13381fbc09cb851fc8
37.045977
139
0.667976
4.485095
false
false
false
false
Thelonedevil/TLDMaths
TLDMaths/src/main/kotlin/uk/tldcode/math/tldmaths/biginteger/Ranges.kt
1
4420
package uk.tldcode.math.tldmaths.biginteger import java.math.BigInteger class BigIntegerRange(start: BigInteger, endInclusive: BigInteger) : BigIntegerProgression(start, endInclusive, BigInteger.ONE), ClosedRange<BigInteger> { override val start: BigInteger get() = first override val endInclusive: BigInteger get() = last @Suppress("ConvertTwoComparisonsToRangeCheck") override fun contains(value: BigInteger): Boolean = first <= value && value <= last override fun isEmpty(): Boolean = first > last override fun equals(other: Any?): Boolean = other is BigIntegerRange && (isEmpty() && other.isEmpty() || first == other.first && last == other.last) override fun hashCode(): Int { val prime = BigInteger.valueOf(31) return if (isEmpty()) -1 else (prime * first + last).toInt() } override fun toString(): String = "$first..$last" companion object { /** An empty range of values of type BigInteger. */ val EMPTY: BigIntegerRange = BigIntegerRange(BigInteger.ONE, BigInteger.ZERO) } } infix fun BigIntegerProgression.step(step: BigInteger): BigIntegerProgression { if (step <= BigInteger.ZERO) throw IllegalArgumentException("Step must be positive, was: $step") return BigIntegerProgression.fromClosedRange(first, last, if (this.step > BigInteger.ZERO) step else -step) } open class BigIntegerProgression internal constructor ( start: BigInteger, endInclusive: BigInteger, step: BigInteger ) : Iterable<BigInteger> { init { if (step == BigInteger.ZERO) throw kotlin.IllegalArgumentException("Step must be non-zero") } /** * The first element in the progression. */ val first: BigInteger = start /** * The last element in the progression. */ val last: BigInteger = getProgressionLastElement(start, endInclusive, step) /** * The step of the progression. */ val step: BigInteger = step override fun iterator(): BigIntegerIterator = BigIntegerProgressionIterator(first, last, step) /** Checks if the progression is empty. */ open fun isEmpty(): Boolean = if (step > BigInteger.ZERO) first > last else first < last override fun equals(other: Any?): Boolean = other is BigIntegerProgression && (isEmpty() && other.isEmpty() || first == other.first && last == other.last && step == other.step) override fun hashCode(): Int { val prime = BigInteger.valueOf(31) return if (isEmpty()) -1 else (prime * (prime * first + last) + step).toInt() } override fun toString(): String = if (step > BigInteger.ZERO) "$first..$last step $step" else "$first downTo $last step ${-step}" companion object { fun fromClosedRange(rangeStart: BigInteger, rangeEnd: BigInteger, step: BigInteger): BigIntegerProgression = BigIntegerProgression(rangeStart, rangeEnd, step) } } abstract class BigIntegerIterator : Iterator<BigInteger> { override final fun next() = nextBigInteger() /** Returns the next value in the sequence without boxing. */ public abstract fun nextBigInteger(): BigInteger } internal class BigIntegerProgressionIterator(first: BigInteger, last: BigInteger, val step: BigInteger) : BigIntegerIterator() { private var next = first private val finalElement = last private var hasNext: Boolean = if (step > BigInteger.ZERO) first <= last else first >= last override fun hasNext(): Boolean = hasNext override fun nextBigInteger(): BigInteger { val value = next if (value == finalElement) { hasNext = false } else { next += step } return value } } internal fun getProgressionLastElement(start: BigInteger, end: BigInteger, step: BigInteger): BigInteger { if (step > BigInteger.ZERO) { return end - differenceModulo(end, start, step) } else if (step < BigInteger.ZERO) { return end + differenceModulo(start, end, -step) } else { throw kotlin.IllegalArgumentException("Step is zero.") } } private fun mod(a: BigInteger, b: BigInteger): BigInteger { val mod = a % b return if (mod >= BigInteger.ZERO) mod else mod + b } // (a - b) mod c private fun differenceModulo(a: BigInteger, b: BigInteger, c: BigInteger): BigInteger { return mod(mod(a, c) - mod(b, c), c) }
apache-2.0
c1ae88ef54b98b083f73b60010a859b6
33.811024
166
0.66448
4.566116
false
false
false
false
cdietze/klay
tripleklay/tripleklay-demo/src/main/kotlin/tripleklay/demo/core/util/InterpDemo.kt
1
2424
package tripleklay.demo.core.util import klay.core.Clock import klay.scene.ImageLayer import klay.scene.Layer import tripleklay.demo.core.DemoScreen import tripleklay.ui.* import tripleklay.ui.layout.TableLayout import tripleklay.util.Interpolator class InterpDemo : DemoScreen() { init { paint.connect({ clock: Clock -> for (driver in _drivers) if (driver!!.elapsed >= 0) driver.paint(clock) }) } override fun name(): String { return "Interps" } override fun title(): String { return "Util: Interpolators" } override fun createIface(root: Root): Group { val grid = Group(TableLayout(TableLayout.COL.stretch().fixed(), TableLayout.COL).gaps(10, 10)) val square = graphics().createCanvas(20f, 20f) square.setFillColor(0xFFFF0000.toInt()).fillRect(0f, 0f, 20f, 20f) val sqtex = square.toTexture() for (ii in INTERPS.indices) { val knob = ImageLayer(sqtex) val tray = Shim(300f, 20f) tray.addStyles(Style.BACKGROUND.`is`(Background.solid(0xFF666666.toInt()))) tray.layer.add(knob) val driver = Driver(INTERPS[ii], knob) _drivers[ii] = driver grid.add(Button(INTERPS[ii].toString()).onClick({ driver.elapsed = 0f })) grid.add(tray) } grid.add(Button("ALL").onClick({ for (driver in _drivers) driver!!.elapsed = 0f })) return grid.addStyles(Style.BACKGROUND.`is`(Background.blank().inset(15f))) } protected fun demoInterp(interp: Interpolator, knob: Layer) { // TODO } protected inner class Driver(val interp: Interpolator, val knob: Layer) { var elapsed = -1f fun paint(clock: Clock) { if (elapsed > 2500) { // spend 500ms at max value knob.setTx(0f) elapsed = -1f } else { elapsed += clock.dt.toFloat() knob.setTx(interp.applyClamp(0f, 300f, elapsed, 2000f)) } } } protected val INTERPS = arrayOf(Interpolator.LINEAR, Interpolator.EASE_IN, Interpolator.EASE_OUT, Interpolator.EASE_INOUT, Interpolator.EASE_IN_BACK, Interpolator.EASE_OUT_BACK, Interpolator.BOUNCE_OUT, Interpolator.EASE_OUT_ELASTIC) protected val _drivers = arrayOfNulls<Driver>(INTERPS.size) }
apache-2.0
685baa3f50c93fdcf3e29eeaf458a8dd
33.140845
237
0.606023
3.960784
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/InlineClassDeprecatedFix.kt
2
2280
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.has import org.jetbrains.kotlin.platform.jvm.JvmPlatform import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.JVM_INLINE_ANNOTATION_FQ_NAME class InlineClassDeprecatedFix( element: KtModifierListOwner ) : KotlinQuickFixAction<KtModifierListOwner>(element), CleanupFix { private val text = KotlinBundle.message( "replace.with.0", (if (element.containingKtFile.hasJvmTarget()) "@JvmInline " else "") + "value" ) override fun getText() = text override fun getFamilyName() = KotlinBundle.message("replace.modifier") override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.removeModifier(KtTokens.INLINE_KEYWORD) element?.addModifier(KtTokens.VALUE_KEYWORD) if (file.hasJvmTarget()) { element?.addAnnotation(JVM_INLINE_ANNOTATION_FQ_NAME) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val deprecatedModifier = Errors.INLINE_CLASS_DEPRECATED.cast(diagnostic) val modifierListOwner = deprecatedModifier.psiElement.getParentOfType<KtModifierListOwner>(strict = true) ?: return null return if (deprecatedModifier != null) InlineClassDeprecatedFix(modifierListOwner) else null } } private fun KtFile.hasJvmTarget(): Boolean = platform.has<JvmPlatform>() }
apache-2.0
d406fec788e23a5316dbac5b7a221fd0
41.240741
132
0.763596
4.615385
false
false
false
false
ngs-doo/dsl-json
examples/AndroidKotlin/app/src/main/java/com/dslplatform/androidkotlin/MainActivity.kt
1
9117
package com.dslplatform.androidkotlin import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import com.dslplatform.json.* import com.dslplatform.json.runtime.MapAnalyzer import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.IOException import java.time.LocalTime import java.math.BigDecimal import java.util.* class MainActivity : AppCompatActivity() { @CompiledJson(onUnknown = CompiledJson.Behavior.IGNORE) //ignore unknown properties (default for objects). to disallow unknown properties in JSON set it to FAIL which will result in exception instead data class Model ( //data classes are supported the same way as immutable objects in Java val string: String,//not null annotations indicate that field can't be null val integers: List<Int>?, @JsonAttribute(name = "guids") //use alternative name in JSON val uuids: Array<UUID>?, val decimals: Set<BigDecimal>?, val longs: Vector<Long>, @JsonAttribute(hashMatch = false) // exact name match can be forced, otherwise hash value will be used for matching val number: Int, @JsonAttribute(alternativeNames = arrayOf("old_nested", "old_nested2")) //several JSON attribute names can be deserialized into this field val nested: List<Nested?>, @JsonAttribute(typeSignature = CompiledJson.TypeSignature.EXCLUDE) //$type attribute can be excluded from resulting JSON val abs: Abstract?,//abstract classes or interfaces can be used which will also include $type attribute in JSON by default val absList: List<Abstract?>, val iface: Interface?,//interfaces without deserializedAs will also include $type attribute in JSON by default val inheritance: ParentClass?, @JsonAttribute(mandatory = true)// mandatory adds check if property exist in JSON and will serialize it even in omit-defaults mode val states: List<State>?, val jsonObject: JsonObjectReference?, //object implementing JsonObject manage their own conversion. They must start with '{' val jsonObjects: List<JsonObjectReference>?, val time: LocalTime?, //LocalTime is not supported, but with the use of converter it will work val times: List<LocalTime?>?, //even containers with unsupported type will be resolved @JsonAttribute(converter = FormatDecimal2::class) val decimal2: BigDecimal, //custom formatting can be implemented with per property converters val intList: ArrayList<Int>, //most collections are supported through runtime converters //since this signature has an unknown part (Object), it must be whitelisted //This can be done via appropriate converter, by registering @JsonConverter for the specified type //or by enabling support for unknown types in the annotation processor @JsonAttribute(converter = MapAnalyzer.Runtime::class) val map: Map<String, Any>, val person: Person? //immutable objects are supported via builder pattern ) //explicitly referenced classes don't require @CompiledJson annotation class Nested { var x: Long = 0 var y: Double = 0.toDouble() var z: Float = 0.toFloat() } @CompiledJson(deserializeAs = Concrete::class)//without deserializeAs deserializing Abstract would fails since it doesn't contain a $type due to it's exclusion in the above configuration abstract class Abstract { var x: Int = 0 } //since this class is not explicitly referenced, but it's an extension of the abstract class used as a property //it needs to be decorated with annotation @CompiledJson class Concrete : Abstract() { var y: Long = 0 } interface Interface { fun x(v: Int) fun x(): Int } @CompiledJson(name = "custom-name")//by default class name will be used for $type attribute class WithCustomCtor : Interface { private var x: Int = 0 var y: Int = 0 constructor(x: Int) { this.x = x this.y = x } @CompiledJson constructor(x: Int, y: Int) { this.x = x this.y = y } override fun x(v: Int) { x = v } override fun x(): Int { return x } } open class BaseClass { var a: Int = 0 } class ParentClass : BaseClass() { var b: Long = 0 } enum class State private constructor(private val value: Int) { LOW(0), MID(1), HI(2) } data class JsonObjectReference(val x: Int, val s: String) : JsonObject { override fun serialize(writer: JsonWriter, minimal: Boolean) { writer.writeAscii("{\"x\":") NumberConverter.serialize(x, writer) writer.writeAscii(",\"s\":") StringConverter.serialize(s, writer) writer.writeAscii("}") } companion object { val JSON_READER = object:JsonReader.ReadJsonObject<JsonObjectReference> { override fun deserialize(reader: JsonReader<*>): JsonObjectReference { reader.fillName()//"x" reader.getNextToken()//start number val x = NumberConverter.deserializeInt(reader) reader.getNextToken()//, reader.getNextToken()//start name reader.fillName()//"s" reader.getNextToken()//start string val s = StringConverter.deserialize(reader) reader.getNextToken()//} return JsonObjectReference(x, s) } } } } @JsonConverter(target = LocalTime::class) object LocalTimeConverter { val JSON_READER = object:JsonReader.ReadObject<LocalTime?> { override fun read(reader: JsonReader<*>): LocalTime? { if (reader.wasNull()) return null return LocalTime.parse(reader.readSimpleString()) } } val JSON_WRITER = object:JsonWriter.WriteObject<LocalTime?> { override fun write(writer: JsonWriter, value: LocalTime?) { if (value == null) { writer.writeNull() } else { writer.writeString(value.toString()) } } } } object FormatDecimal2 { val JSON_READER = object:JsonReader.ReadObject<BigDecimal> { override fun read(reader: JsonReader<*>): BigDecimal { return NumberConverter.deserializeDecimal(reader).setScale(2) } } val JSON_WRITER = object:JsonWriter.WriteObject<BigDecimal> { override fun write(writer: JsonWriter, value: BigDecimal) { NumberConverter.serializeNullable(value.setScale(2), writer) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val dslJson = DSL.JSON() val concrete = Concrete() concrete.x = 11 concrete.y = 23 val parent = ParentClass() parent.a = 5 parent.b = 6 val instance = Model( string = "Hello World!", number = 42, integers = listOf(1, 2, 3), decimals = HashSet(listOf(BigDecimal.ONE, BigDecimal.ZERO)), uuids = arrayOf(UUID(1L, 2L), UUID(3L, 4L)), longs = Vector(listOf(1L, 2L)), nested = listOf(Nested(), null), inheritance = parent, iface = WithCustomCtor(5, 6), person = Person("first name", "last name", 35), states = Arrays.asList(State.HI, State.LOW), jsonObject = JsonObjectReference(43, "abcd"), jsonObjects = Collections.singletonList(JsonObjectReference(34, "dcba")), time = LocalTime.of(12, 15), times = listOf(null, LocalTime.of(8, 16)), abs = concrete, absList = listOf<Abstract?>(concrete, null, concrete), decimal2 = BigDecimal.TEN, intList = ArrayList(listOf(123, 456)), map = mapOf("abc" to 678, "array" to arrayOf(2, 4, 8)) ) val tv = findViewById<TextView>(R.id.tvHello) try { val os = ByteArrayOutputStream() //serialize into stream dslJson.serialize(instance, os) val stream = ByteArrayInputStream(os.toByteArray()) //deserialized using stream API val result = dslJson.deserialize(Model::class.java, stream) tv.setText(result.string) } catch (ex: IOException) { tv.setText(ex.message) } } }
bsd-3-clause
96b3507a0a5f4a41cbf0e04780cd8d8d
38.52
203
0.597236
4.965686
false
false
false
false
elpassion/el-space-android
el-space-app/src/main/java/pl/elpassion/elspace/common/extensions/ToolbarExtensions.kt
1
631
package pl.elpassion.elspace.common.extensions import android.support.v7.widget.Toolbar import android.view.MenuItem import com.jakewharton.rxbinding2.support.v7.widget.itemClicks import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers fun Observable<MenuItem>.onMenuItemClicks(menuId: Int): Observable<Unit> = onMenuItemAction(menuId).map { Unit } fun Observable<MenuItem>.onMenuItemAction(menuId: Int): Observable<MenuItem> = this.filter { it.itemId == menuId } fun Toolbar.menuClicks(): Observable<MenuItem> = itemClicks() .subscribeOn(AndroidSchedulers.mainThread()) .share()
gpl-3.0
043f5bd88c63bd217ea91257f27005fc
41.133333
114
0.795563
4.206667
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/firehose/src/main/kotlin/com/kotlin/firehose/PutRecord.kt
1
1999
// snippet-sourcedescription:[PutRecord.kt demonstrates how to write a data record into a delivery stream.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Kinesis Data Firehose] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.firehose // snippet-start:[firehose.kotlin.put_record.import] import aws.sdk.kotlin.services.firehose.FirehoseClient import aws.sdk.kotlin.services.firehose.model.PutRecordRequest import aws.sdk.kotlin.services.firehose.model.Record import kotlin.system.exitProcess // snippet-end:[firehose.kotlin.put_record.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <textValue> <streamName> Where: textValue - The text used as the data to write to the data stream. streamName - The data stream name. """ if (args.size != 2) { println(usage) exitProcess(0) } val textValue = args[0] val streamName = args[1] putSingleRecord(textValue, streamName) } // snippet-start:[firehose.kotlin.put_record.main] suspend fun putSingleRecord(textValue: String, streamName: String?) { val bytes = textValue.toByteArray() val recordOb = Record { data = bytes } val request = PutRecordRequest { deliveryStreamName = streamName record = recordOb } FirehoseClient { region = "us-west-2" }.use { firehoseClient -> val recordResponse = firehoseClient.putRecord(request) println("The record ID is ${recordResponse.recordId}") } } // snippet-end:[firehose.kotlin.put_record.main]
apache-2.0
8bd914a9956f1df6636aad2a219924a5
28.753846
107
0.677839
3.998
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/bukkit/inspection/BukkitListenerImplementedInspection.kt
1
2215
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bukkit.inspection import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants import com.demonwav.mcdev.util.addImplements import com.demonwav.mcdev.util.extendsOrImplements import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class BukkitListenerImplementedInspection : BaseInspection() { @Nls override fun getDisplayName() = "Bukkit @EventHandler in class not implementing Listener" override fun buildErrorString(vararg infos: Any) = "This class contains @EventHandler methods but does not implement Listener." override fun getStaticDescription() = "All Bukkit @EventHandler methods must reside in a class that implements Listener." override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { return object : InspectionGadgetsFix() { override fun doFix(project: Project, descriptor: ProblemDescriptor) { val psiClass = infos[0] as PsiClass psiClass.addImplements(BukkitConstants.LISTENER_CLASS) } @Nls override fun getName() = "Implement Listener" @Nls override fun getFamilyName() = name } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitClass(aClass: PsiClass) { if ( aClass.methods.none { it.modifierList.findAnnotation(BukkitConstants.HANDLER_ANNOTATION) != null } ) { return } val inError = !aClass.extendsOrImplements(BukkitConstants.LISTENER_CLASS) if (inError) { registerClassError(aClass, aClass) } } } } }
mit
2e2ee0b76a01ed6c3edbba707f325d07
30.642857
98
0.648758
5.224057
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ConventionUtils.kt
1
1384
// 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.intentions.conventionNameCalls import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors fun KtExpression.isAnyEquals(): Boolean { val resolvedCall = resolveToCall() ?: return false return (resolvedCall.resultingDescriptor as? FunctionDescriptor)?.isAnyEquals() == true } fun FunctionDescriptor.isAnyEquals(): Boolean { val overriddenDescriptors = findOriginalTopMostOverriddenDescriptors() return overriddenDescriptors.any { it.fqNameUnsafe.asString() == "kotlin.Any.equals" } } fun FunctionDescriptor.isAnyHashCode(): Boolean { val overriddenDescriptors = findOriginalTopMostOverriddenDescriptors() return overriddenDescriptors.any { it.fqNameUnsafe.asString() == "kotlin.Any.hashCode" } } fun FunctionDescriptor.isAnyToString(): Boolean { val overriddenDescriptors = findOriginalTopMostOverriddenDescriptors() return overriddenDescriptors.any { it.fqNameUnsafe.asString() == "kotlin.Any.toString" } }
apache-2.0
90a6e89ae19abcf50ccdc98038cc58f8
46.724138
158
0.807081
4.907801
false
false
false
false
JetBrains/intellij-community
platform/lang-api/src/com/intellij/codeInsight/hints/declarative/DeclarativeHintsSettings.kt
1
1927
// 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.codeInsight.hints.declarative import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.util.concurrency.annotations.RequiresReadLock import com.intellij.util.concurrency.annotations.RequiresWriteLock @State(name = "DeclarativeInlayHintsSettings", storages = [Storage("editor.xml")], category = SettingsCategory.CODE) class DeclarativeInlayHintsSettings(private val project: Project) : SimplePersistentStateComponent<DeclarativeInlayHintsSettings.HintsState>( HintsState()) { class HintsState : BaseState() { // Format: providerId + # + optionId var disabledOptions by stringSet() var providerIdToEnabled by map<String, Boolean>() } companion object { fun getInstance(project: Project): DeclarativeInlayHintsSettings { return project.service() } } /** * Note that it may return true even if the provider is enabled! */ @RequiresReadLock fun isOptionEnabled(optionId: String, providerId: String): Boolean? { if (getSerializedId(providerId, optionId) in state.disabledOptions) return false return null } private fun getSerializedId(providerId: String, optionId: String) = "$providerId#$optionId" @RequiresWriteLock fun setOptionEnabled(optionId: String, providerId: String, value: Boolean) { if (!value) { state.disabledOptions.add(getSerializedId(providerId, optionId)) } } @RequiresReadLock fun isProviderEnabled(providerId: String): Boolean? { return state.providerIdToEnabled[providerId] } @RequiresWriteLock fun setProviderEnabled(providerId: String, value: Boolean) { val previousState = state.providerIdToEnabled.put(providerId, value) if (previousState != value) { state.intIncrementModificationCount() } } }
apache-2.0
1d07e3885454cd054ee3642cdd64f6e6
33.428571
141
0.754541
4.621103
false
false
false
false
spacecowboy/Feeder
app/src/main/java/org/kodein/di/compose/Retreiving.kt
1
4196
package org.kodein.di.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import org.kodein.di.* /** * Gets an instance of `T` for the given type and tag. * * T generics will be preserved! * * @param T The type of object to retrieve. * @param tag The bound tag, if any. * @return An instance. * @throws DI.NotFoundException if no provider was found. * @throws DI.DependencyLoopException If the instance construction triggered a dependency loop. */ @Composable inline fun <reified T : Any> instance(tag: Any? = null): DIProperty<T> = with(LocalDI.current) { remember { instance(tag) } } /** * Gets an instance of [T] for the given type and tag, curried from a factory that takes an argument [A]. * * A & T generics will be preserved! * * @param A The type of argument the curried factory takes. * @param T The type of object to retrieve. * @param tag The bound tag, if any. * @param arg The argument that will be given to the factory when curried. * @return An instance of [T]. * @throws DI.NotFoundException If no provider was found. * @throws DI.DependencyLoopException If the value construction triggered a dependency loop. */ @Composable inline fun <reified A : Any, reified T : Any> instance(tag: Any? = null, arg: A): DIProperty<T> = with(LocalDI.current) { remember { instance(tag, arg) } } /** * Gets a factory of `T` for the given argument type, return type and tag. * * A & T generics will be preserved! * * @param A The type of argument the factory takes. * @param T The type of object the factory returns. * @param tag The bound tag, if any. * @return A factory. * @throws DI.NotFoundException if no factory was found. * @throws DI.DependencyLoopException When calling the factory function, if the instance construction triggered a dependency loop. */ @Composable inline fun <reified A : Any, reified T : Any> factory(tag: Any? = null): DIProperty<(A) -> T> = with(LocalDI.current) { remember { factory(tag) } } /** * Gets a provider of `T` for the given type and tag. * * T generics will be preserved! * * @param T The type of object the provider returns. * @param tag The bound tag, if any. * @return A provider. * @throws DI.NotFoundException if no provider was found. * @throws DI.DependencyLoopException When calling the provider function, if the instance construction triggered a dependency loop. */ @Composable inline fun <reified A : Any, reified T : Any> provider(tag: Any? = null): DIProperty<() -> T> = with(LocalDI.current) { remember { provider(tag) } } /** * Gets a provider of [T] for the given type and tag, curried from a factory that takes an argument [A]. * * A & T generics will be preserved! * * @param A The type of argument the curried factory takes. * @param T The type of object to retrieve with the returned provider. * @param tag The bound tag, if any. * @param arg The argument that will be given to the factory when curried. * @return A provider of [T]. * @throws DI.NotFoundException If no provider was found. * @throws DI.DependencyLoopException When calling the provider, if the value construction triggered a dependency loop. */ @Composable inline fun <reified A : Any, reified T : Any> provider(tag: Any? = null, arg: A): DIProperty<() -> T> = with(LocalDI.current) { remember { provider(tag, arg) } } /** * Gets a provider of [T] for the given type and tag, curried from a factory that takes an argument [A]. * * A & T generics will be preserved! * * @param A The type of argument the curried factory takes. * @param T The type of object to retrieve with the returned provider. * @param tag The bound tag, if any. * @param fArg A function that returns the argument that will be given to the factory when curried. * @return A provider of [T]. * @throws DI.NotFoundException If no provider was found. * @throws DI.DependencyLoopException When calling the provider, if the value construction triggered a dependency loop. */ @Composable inline fun <reified A : Any, reified T : Any> provider(tag: Any? = null, noinline fArg: () -> A): DIProperty<() -> T> = with(LocalDI.current) { remember { provider(tag, fArg) } }
gpl-3.0
9de3005bbf91be63f59b8fd15302979e
37.851852
143
0.710677
3.80417
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/ClassLoaderTreeChecker.kt
2
2304
// 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.ide.plugins import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.openapi.diagnostic.logger import com.intellij.util.containers.WeakList private val LOG = logger<ClassLoaderTreeChecker>() internal class ClassLoaderTreeChecker(private val unloadedMainDescriptor: IdeaPluginDescriptorImpl, private val classLoaders: WeakList<PluginClassLoader>) { fun checkThatClassLoaderNotReferencedByPluginClassLoader() { if (!ClassLoaderConfigurationData.SEPARATE_CLASSLOADER_FOR_SUB || unloadedMainDescriptor.classLoader !is PluginClassLoader) { return } PluginManagerCore.getLoadedPlugins(null).forEach(this::checkThatClassLoaderNotReferencedByPluginClassLoader) } private fun checkThatClassLoaderNotReferencedByPluginClassLoader(descriptor: IdeaPluginDescriptorImpl) { checkThatClassloaderNotReferenced(descriptor) for (dependency in (descriptor.pluginDependencies ?: return)) { checkThatClassLoaderNotReferencedByPluginClassLoader(dependency.subDescriptor ?: continue) } } private fun checkThatClassloaderNotReferenced(descriptor: IdeaPluginDescriptorImpl) { val classLoader = descriptor.classLoader as? PluginClassLoader ?: return if (descriptor !== unloadedMainDescriptor) { // unrealistic case, but who knows if (classLoaders.contains(classLoader)) { LOG.error("$classLoader must be unloaded but still referenced") } if (classLoader.pluginId === unloadedMainDescriptor.pluginId && classLoader.pluginDescriptor === descriptor) { LOG.error("Classloader of $descriptor must be nullified") } } val parents = classLoader._getParents() for (unloadedClassLoader in classLoaders) { if (parents.contains(unloadedClassLoader)) { LOG.error("$classLoader references via parents $unloadedClassLoader that must be unloaded") } } for (parent in parents) { if (parent is PluginClassLoader && parent.pluginId === unloadedMainDescriptor.pluginId) { LOG.error("$classLoader references via parents $parent that must be unloaded") } } } }
apache-2.0
c24b30091639f8f8f321db10f5e74baf
41.685185
140
0.748698
5.592233
false
false
false
false
allotria/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/dsl/MavenDependencyModificator.kt
1
13746
// 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.dsl import com.intellij.buildsystem.model.DeclaredDependency import com.intellij.buildsystem.model.unified.UnifiedCoordinates import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.externalSystem.ExternalDependencyModificator import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ReadAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.xml.XmlFile import com.intellij.psi.xml.XmlTag import com.intellij.util.xml.DomUtil import com.intellij.util.xml.GenericDomValue import org.jetbrains.annotations.NotNull import org.jetbrains.idea.maven.dom.MavenDomElement import org.jetbrains.idea.maven.dom.MavenDomUtil import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil import org.jetbrains.idea.maven.dom.model.MavenDomDependency import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel import org.jetbrains.idea.maven.dom.model.MavenDomRepository import org.jetbrains.idea.maven.model.MavenConstants.SCOPE_COMPILE import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.project.MavenProjectsManager val mavenTopLevelElementsOrder = listOf( "modelVersion", "parent", "groupId", "artifactId", "version", "packaging", "properties", "name", "description", "url", "inceptionYear", "licenses", "organization", "developers", "contributors", "modules", "dependencyManagement", "dependencies", "build", "reporting", "issueManagement", "ciManagement", "mailingLists", "scm", "prerequisites", "repositories", "pluginRepositories", "distributionManagement", "profiles" ) val elementsBeforeDependencies = elementsBefore("dependencies") val elementsBeforeRepositories = elementsBefore("repositories") fun elementsBefore(s: String): Set<String> { return mavenTopLevelElementsOrder.takeWhile { it != s } .toSet() } class MavenDependencyModificator(private val myProject: Project) : ExternalDependencyModificator { private val myProjectsManager: MavenProjectsManager = MavenProjectsManager.getInstance(myProject) private val myDocumentManager: PsiDocumentManager = PsiDocumentManager.getInstance(myProject) private fun addDependenciesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) { addTagIfNotExists(psiFile, model.dependencies, elementsBeforeDependencies) } private fun addRepositoriesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) { addTagIfNotExists(psiFile, model.repositories, elementsBeforeRepositories) } private fun addTagIfNotExists(psiFile: XmlFile, element: MavenDomElement, elementsBefore: Set<String>) { if (element.exists()) { return } val rootTag = psiFile.rootTag; if (rootTag == null) { element.ensureTagExists(); return } val children = rootTag.children if (children == null || children.isEmpty()) { element.ensureTagExists() return } val lastOrNull = children .mapNotNull { it as? XmlTag } .lastOrNull { elementsBefore.contains(it.name) } val child = rootTag.createChildTag(element.xmlElementName, rootTag.namespace, null, false) rootTag.addAfter(child, lastOrNull) } private fun getDependenciesModel(module: Module, groupId: String, artifactId: String): Pair<MavenDomProjectModel, MavenDomDependency?> { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) return ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) val managedDependency = MavenDependencyCompletionUtil.findManagedDependency(model, myProject, groupId, artifactId) return@compute Pair(model, managedDependency) } } override fun supports(module: Module): Boolean { return myProjectsManager.isMavenizedModule(module) } override fun addDependency(module: Module, descriptor: UnifiedDependency) { requireNotNull(descriptor.coordinates.groupId) requireNotNull(descriptor.coordinates.version) requireNotNull(descriptor.coordinates.artifactId) val mavenId = descriptor.coordinates.toMavenId() val (model, managedDependency) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!) val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { addDependenciesTagIfNotExists(psiFile, model); val dependency = MavenDomUtil.createDomDependency(model, null) dependency.groupId.stringValue = mavenId.groupId dependency.artifactId.stringValue = mavenId.artifactId val scope = toMavenScope(descriptor.scope, managedDependency?.scope?.stringValue); scope?.let { dependency.scope.stringValue = it } if (managedDependency == null || managedDependency.version.stringValue != mavenId.version) { dependency.version.stringValue = mavenId.version } saveFile(psiFile) } } override fun updateDependency(module: Module, oldDescriptor: UnifiedDependency, newDescriptor: UnifiedDependency) { requireNotNull(newDescriptor.coordinates.groupId) requireNotNull(newDescriptor.coordinates.version) requireNotNull(newDescriptor.coordinates.artifactId) val oldMavenId = oldDescriptor.coordinates.toMavenId() val newMavenId = newDescriptor.coordinates.toMavenId() val (model, managedDependency) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> { getDependenciesModel(module, oldMavenId.groupId!!, oldMavenId.artifactId!!) } val psiFile = managedDependency?.let(DomUtil::getFile) ?: DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { if (managedDependency != null) { val parentModel = managedDependency.getParentOfType(MavenDomProjectModel::class.java, true) if (parentModel != null) { updateVariableOrValue(parentModel, managedDependency.version, newMavenId.version!!) } else { managedDependency.version.stringValue = newDescriptor.coordinates.version } } else { for (dep in model.dependencies.dependencies) { if (dep.artifactId.stringValue == oldMavenId.artifactId && dep.groupId.stringValue == oldMavenId.groupId) { updateVariableOrValue(model, dep.artifactId, newMavenId.artifactId!!) updateVariableOrValue(model, dep.groupId, newMavenId.groupId!!) updateVariableOrValue(model, dep.version, newMavenId.version!!) } } } saveFile(psiFile) } } override fun removeDependency(module: Module, descriptor: UnifiedDependency) { requireNotNull(descriptor.coordinates.groupId) requireNotNull(descriptor.coordinates.version) val mavenId = descriptor.coordinates.toMavenId() val (model, _) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!) val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { for (dep in model.dependencies.dependencies) { if (dep.artifactId.stringValue == mavenId.artifactId && dep.groupId.stringValue == mavenId.groupId) { dep.xmlTag?.delete() } } if (model.dependencies.dependencies.isEmpty()) { model.dependencies.xmlTag?.delete(); } saveFile(psiFile) } } override fun addRepository(module: Module, repository: UnifiedDependencyRepository) { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) val model = ReadAction.compute<MavenDomProjectModel, Throwable> { MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) } for (repo in model.repositories.repositories) { if (repo.url.stringValue?.trimLastSlash() == repository.url.trimLastSlash()) { return; } } val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { addRepositoriesTagIfNotExists(psiFile, model) val repoTag = model.repositories.addRepository() repository.id?.let { repoTag.id.stringValue = it } repository.name?.let { repoTag.name.stringValue = it } repository.url.let { repoTag.url.stringValue = it } saveFile(psiFile) } } override fun deleteRepository(module: Module, repository: UnifiedDependencyRepository) { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) val (model, repo) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomRepository?>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) for (repo in model.repositories.repositories) { if (repo.url.stringValue?.trimLastSlash() == repository.url.trimLastSlash()) { return@compute Pair(model, repo) } } return@compute null; } if (repo == null) return; val psiFile = DomUtil.getFile(repo) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { repo.xmlTag?.delete() if(model.repositories.repositories.isEmpty()) { model.repositories.xmlTag?.delete() } saveFile(psiFile) } } private fun saveFile(psiFile: @NotNull XmlFile) { val document = myDocumentManager.getDocument(psiFile) ?: throw IllegalStateException(MavenProjectBundle.message( "maven.model.error", psiFile)); myDocumentManager.doPostponedOperationsAndUnblockDocument(document) FileDocumentManager.getInstance().saveDocument(document) } private fun updateVariableOrValue(model: MavenDomProjectModel, domValue: GenericDomValue<String>, newValue: String) { val rawText = domValue.rawText?.trim() if (rawText != null && rawText.startsWith("${'$'}{") && rawText.endsWith("}")) { val propertyName = rawText.substring(2, rawText.length - 1); val subTags = model.properties.xmlTag?.subTags ?: emptyArray() for (subTag in subTags) { if (subTag.name == propertyName) { //TODO: recursive property declaration subTag.value.text = newValue return } } } else { domValue.stringValue = newValue } } private fun toMavenScope(scope: String?, managedScope: String?): String? { if (managedScope == null) { if (scope == null || scope == SCOPE_COMPILE) return null return scope; } if (scope == managedScope) return null return scope } override fun declaredDependencies(module: @NotNull Module): List<DeclaredDependency>? { val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList() return ReadAction.compute<List<DeclaredDependency>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) model.dependencies.dependencies.map { var scope = it.scope.stringValue; if (scope == SCOPE_COMPILE) scope = null val dataContext = object: DataContext { override fun getData(dataId: String): Any? { if(CommonDataKeys.PSI_ELEMENT.`is`(dataId)){ return it.xmlElement } return null } } DeclaredDependency(it.groupId.stringValue, it.artifactId.stringValue, it.version.stringValue, scope, dataContext) } } } override fun declaredRepositories(module: Module): List<UnifiedDependencyRepository> { val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList() return ReadAction.compute<List<UnifiedDependencyRepository>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) model.repositories.repositories.map { UnifiedDependencyRepository(it.id.stringValue, it.name.stringValue, it.url.stringValue ?: "") } } } } private fun String.trimLastSlash(): String { return trimEnd('/'); } private fun UnifiedCoordinates.toMavenId(): MavenId { return MavenId(groupId, artifactId, version) }
apache-2.0
9ddaa8d448409b77ff835589bb5de205
39.789318
140
0.729885
4.932185
false
false
false
false
allotria/intellij-community
platform/util-ex/src/com/intellij/util/containers/util.kt
1
9498
// 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.util.containers import com.intellij.openapi.diagnostic.Logger import com.intellij.util.SmartList import com.intellij.util.lang.CompoundRuntimeException import java.util.* import java.util.stream.Stream import kotlin.collections.ArrayDeque fun <K, V> MutableMap<K, MutableList<V>>.remove(key: K, value: V) { val list = get(key) if (list != null && list.remove(value) && list.isEmpty()) { remove(key) } } fun <K, V> MutableMap<K, MutableList<V>>.putValue(key: K, value: V) { val list = get(key) if (list == null) { put(key, SmartList<V>(value)) } else { list.add(value) } } fun Collection<*>?.isNullOrEmpty(): Boolean = this == null || isEmpty() /** * @return all the elements of a non-empty list except the first one */ fun <T> List<T>.tail(): List<T> { require(isNotEmpty()) return subList(1, size) } /** * @return all the elements of a non-empty list except the first one or empty list */ fun <T> List<T>.tailOrEmpty(): List<T> { if (isEmpty()) return emptyList() return subList(1, size) } /** * @return pair of the first element and the rest of a non-empty list */ fun <T> List<T>.headTail(): Pair<T, List<T>> = Pair(first(), tail()) /** * @return pair of the first element and the rest of a non-empty list, or `null` if a list is empty */ fun <T> List<T>.headTailOrNull(): Pair<T, List<T>>? = if (isEmpty()) null else headTail() /** * @return all the elements of a non-empty list except the last one */ fun <T> List<T>.init(): List<T> { require(isNotEmpty()) return subList(0, size - 1) } fun <T> List<T>?.nullize(): List<T>? = if (isNullOrEmpty()) null else this inline fun <T> Array<out T>.forEachGuaranteed(operation: (T) -> Unit) { return iterator().forEachGuaranteed(operation) } inline fun <T> Collection<T>.forEachGuaranteed(operation: (T) -> Unit) { return iterator().forEachGuaranteed(operation) } inline fun <T> Iterator<T>.forEachGuaranteed(operation: (T) -> Unit) { var errors: MutableList<Throwable>? = null for (element in this) { try { operation(element) } catch (e: Throwable) { if (errors == null) { errors = SmartList() } errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) } inline fun <T> Collection<T>.forEachLoggingErrors(logger: Logger, operation: (T) -> Unit) { return asSequence().forEachLoggingErrors(logger, operation) } inline fun <T> Sequence<T>.forEachLoggingErrors(logger: Logger, operation: (T) -> Unit) { forEach { try { operation(it) } catch (e: Throwable) { logger.error(e) } } } inline fun <T, R : Any> Collection<T>.mapNotNullLoggingErrors(logger: Logger, operation: (T) -> R?): List<R> { return mapNotNull { try { operation(it) } catch (e: Throwable) { logger.error(e) null } } } fun <T> Array<T>?.stream(): Stream<T> = if (this != null) Stream.of(*this) else Stream.empty() fun <T> Stream<T>?.isEmpty(): Boolean = this == null || !this.findAny().isPresent fun <T> Stream<T>?.notNullize(): Stream<T> = this ?: Stream.empty() fun <T> Stream<T>?.getIfSingle(): T? = this?.limit(2) ?.map { Optional.ofNullable(it) } ?.reduce(Optional.empty()) { a, b -> if (a.isPresent xor b.isPresent) b else Optional.empty() } ?.orNull() /** * There probably could be some performance issues if there is lots of streams to concat. See * http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010659.html for some details. * * See also [Stream.concat] documentation for other possible issues of concatenating large number of streams. */ fun <T> concat(vararg streams: Stream<T>): Stream<T> = Stream.of(*streams).reduce(Stream.empty()) { a, b -> Stream.concat(a, b) } inline fun MutableList<Throwable>.catch(runnable: () -> Unit) { try { runnable() } catch (e: Throwable) { add(e) } } fun <T> MutableList<T>.addIfNotNull(e: T?) { e?.let { add(it) } } fun <T> MutableList<T>.addAllIfNotNull(vararg elements: T?) { elements.forEach { e -> e?.let { add(it) } } } inline fun <T, R> Array<out T>.mapSmart(transform: (T) -> R): List<R> { return when (val size = size) { 1 -> SmartList(transform(this[0])) 0 -> SmartList() else -> mapTo(ArrayList(size), transform) } } inline fun <T, reified R> Array<out T>.map2Array(transform: (T) -> R): Array<R> = Array(this.size) { i -> transform(this[i]) } @Suppress("UNCHECKED_CAST") inline fun <T, reified R> Collection<T>.map2Array(transform: (T) -> R): Array<R> = arrayOfNulls<R>(this.size).also { array -> this.forEachIndexed { index, t -> array[index] = transform(t) } } as Array<R> inline fun <T, R> Collection<T>.mapSmart(transform: (T) -> R): List<R> { return when (val size = size) { 1 -> SmartList(transform(first())) 0 -> emptyList() else -> mapTo(ArrayList(size), transform) } } /** * Not mutable set will be returned. */ inline fun <T, R> Collection<T>.mapSmartSet(transform: (T) -> R): Set<R> { return when (val size = size) { 1 -> { Collections.singleton(transform(first())) } 0 -> emptySet() else -> mapTo(HashSet(size), transform) } } inline fun <T, R : Any> Collection<T>.mapSmartNotNull(transform: (T) -> R?): List<R> { val size = size return if (size == 1) { transform(first())?.let { SmartList<R>(it) } ?: SmartList<R>() } else { mapNotNullTo(ArrayList(size), transform) } } fun <T> List<T>.toMutableSmartList(): MutableList<T> { return when (size) { 1 -> SmartList(first()) 0 -> SmartList() else -> ArrayList(this) } } inline fun <T> Collection<T>.filterSmart(predicate: (T) -> Boolean): List<T> { val result: MutableList<T> = when (size) { 1 -> SmartList() 0 -> return emptyList() else -> ArrayList() } filterTo(result, predicate) return result } inline fun <T> Collection<T>.filterSmartMutable(predicate: (T) -> Boolean): MutableList<T> { return filterTo(if (size <= 1) SmartList() else ArrayList(), predicate) } inline fun <reified E : Enum<E>, V> enumMapOf(): MutableMap<E, V> = EnumMap<E, V>(E::class.java) fun <E> Collection<E>.toArray(empty: Array<E>): Array<E> { @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") return (this as java.util.Collection<E>).toArray(empty) } /** * Given a collection of elements S returns collection of minimal elements M as ordered by [comparator]. * * Let S = M ∪ R; M ∩ R = ∅. Then: * - ∀ m1 ∈ M, ∀ m2 ∈ M : m1 = m2; * - ∀ m ∈ M, ∀ r ∈ R : m < r. */ fun <T> Collection<T>.minimalElements(comparator: Comparator<in T>): Collection<T> { if (isEmpty() || size == 1) return this val result = SmartList<T>() for (item in this) { if (result.isEmpty()) { result.add(item) } else { val comparison = comparator.compare(result[0], item) if (comparison > 0) { result.clear() result.add(item) } else if (comparison == 0) { result.add(item) } } } return result } /** * _Example_ * The following will print `1`, `2` and `3` when executed: * ``` * arrayOf(1, 2, 3, 4, 5) * .iterator() * .stopAfter { it == 3 } * .forEach(::println) * ``` * @return an iterator, which stops [this] Iterator after first element for which [predicate] returns `true` */ inline fun <T> Iterator<T>.stopAfter(crossinline predicate: (T) -> Boolean): Iterator<T> = iterator { for (element in this@stopAfter) { yield(element) if (predicate(element)) { break } } } fun <T> Optional<T>.orNull(): T? = orElse(null) fun <T> Iterable<T>?.asJBIterable(): JBIterable<T> = JBIterable.from(this) fun <T> Array<T>?.asJBIterable(): JBIterable<T> = if (this == null) JBIterable.empty() else JBIterable.of(*this) /** * returns sequence of distinct nodes in breadth-first order. */ fun <Node> generateRecursiveSequence(initialSequence: Sequence<Node>, children: (Node) -> Sequence<Node>): Sequence<Node> { return Sequence { val initialIterator = initialSequence.iterator() if (!initialIterator.hasNext()) emptySequence<Node>().iterator() else object : Iterator<Node> { private var currentNode: Node? = null private var currentSequenceIterator: Iterator<Node>? = initialIterator private val nextSequences = ArrayDeque<Sequence<Node>>() private val visited = mutableSetOf<Node>() private fun getNext(): Node? { currentNode?.let { return it } while (true) { val iterator = getCurrentSequenceIterator() ?: return null while (iterator.hasNext()) { val next = iterator.next() if (visited.add(next)) { currentNode = next return next } } currentSequenceIterator = null } } private fun getCurrentSequenceIterator(): Iterator<Node>? { currentSequenceIterator?.let { return it } val nextIterator = nextSequences.removeFirstOrNull()?.iterator() ?: return null currentSequenceIterator = nextIterator return nextIterator } override fun hasNext(): Boolean = getNext() != null override fun next(): Node { val node = getNext() ?: throw NoSuchElementException() nextSequences += children(node) currentNode = null return node } } } }
apache-2.0
330ab3c18b3be56c62980a36bfee33e6
27.205357
140
0.631385
3.472334
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/expenseedit/ExpenseEditViewModel.kt
1
4454
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.view.expenseedit import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.benoitletondor.easybudgetapp.model.Expense import com.benoitletondor.easybudgetapp.db.DB import com.benoitletondor.easybudgetapp.helper.MutableLiveFlow import com.benoitletondor.easybudgetapp.parameters.Parameters import com.benoitletondor.easybudgetapp.parameters.getInitDate import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.time.LocalDate import javax.inject.Inject @HiltViewModel class ExpenseEditViewModel @Inject constructor( private val db: DB, private val parameters: Parameters, savedStateHandle: SavedStateHandle, ) : ViewModel() { /** * Expense that is being edited (will be null if it's a new one) */ private val editedExpense: Expense? = savedStateHandle.get<Expense>("expense") private val expenseDateMutableStateFlow = MutableStateFlow(LocalDate.ofEpochDay(savedStateHandle.get<Long>("date") ?: 0)) val expenseDateFlow: Flow<LocalDate> = expenseDateMutableStateFlow private val editTypeMutableStateFlow = MutableStateFlow(ExpenseEditType( editedExpense?.isRevenue() ?: false, editedExpense != null )) val editTypeFlow: Flow<ExpenseEditType> = editTypeMutableStateFlow val existingExpenseData = editedExpense?.let { expense -> ExistingExpenseData( expense.title, expense.amount, ) } private val expenseAddBeforeInitDateErrorMutableFlow = MutableLiveFlow<Unit>() val expenseAddBeforeInitDateEventFlow: Flow<Unit> = expenseAddBeforeInitDateErrorMutableFlow private val finishMutableFlow = MutableLiveFlow<Unit>() val finishFlow: Flow<Unit> = finishMutableFlow fun onExpenseRevenueValueChanged(isRevenue: Boolean) { editTypeMutableStateFlow.value = ExpenseEditType(isRevenue, editedExpense != null) } fun onSave(value: Double, description: String) { val isRevenue = editTypeMutableStateFlow.value.isRevenue val date = expenseDateMutableStateFlow.value val dateOfInstallation = parameters.getInitDate() ?: LocalDate.now() if( date.isBefore(dateOfInstallation) ) { viewModelScope.launch { expenseAddBeforeInitDateErrorMutableFlow.emit(Unit) } return } doSaveExpense(value, description, isRevenue, date) } fun onAddExpenseBeforeInitDateConfirmed(value: Double, description: String) { val isRevenue = editTypeMutableStateFlow.value.isRevenue val date = expenseDateMutableStateFlow.value doSaveExpense(value, description, isRevenue, date) } fun onAddExpenseBeforeInitDateCancelled() { // No-op } private fun doSaveExpense(value: Double, description: String, isRevenue: Boolean, date: LocalDate) { viewModelScope.launch { withContext(Dispatchers.Default) { val expense = editedExpense?.copy( title = description, amount = if (isRevenue) -value else value, date = date ) ?: Expense(description, if (isRevenue) -value else value, date, false) db.persistExpense(expense) } finishMutableFlow.emit(Unit) } } fun onDateChanged(date: LocalDate) { expenseDateMutableStateFlow.value = date } } data class ExpenseEditType(val isRevenue: Boolean, val editing: Boolean) data class ExistingExpenseData(val title: String, val amount: Double)
apache-2.0
74bbc0908097560b238345e1370cc4a7
34.927419
125
0.718455
5.038462
false
false
false
false
room-15/ChatSE
app/src/main/java/com/tristanwiley/chatse/event/presenter/message/MessageEventPresenter.kt
1
6380
package com.tristanwiley.chatse.event.presenter.message import android.content.Context import com.squareup.okhttp.Request import com.tristanwiley.chatse.chat.ChatRoom import com.tristanwiley.chatse.event.ChatEvent import com.tristanwiley.chatse.event.presenter.EventPresenter import com.tristanwiley.chatse.network.Client import com.tristanwiley.chatse.network.ClientManager import org.jetbrains.anko.doAsync import org.json.JSONObject import timber.log.Timber import java.util.* import kotlin.collections.ArrayList /** * One of the most important files * Where messages are added to an ArrayList of MessageEvents. This implements EventPresentor which overrides getEventsList and getUsersList which get the list of messages and users respectively. * Inside this class, events are handled based on the eventType that StackExchange assigns it. * List of event types can be found in the ChatEvent file. * * @property messages: A TreeSet containing all the messages for a Room * @property users; A hashmap of all the users in a Room * * Get these by calling .getEventsList() and .getUsersList() */ class MessageEventPresenter : EventPresenter<MessageEvent> { private var messages = TreeSet<MessageEvent>() private var users = hashMapOf<Long, MessageEvent>() override fun addEvent(event: ChatEvent, roomNum: Int, context: Context, room: ChatRoom?) { //If the event type is not for leaving but definitely exists then continue so we can add the user to the UsersList if (event.eventType != ChatEvent.EVENT_TYPE_LEAVE && event.userId != 0) { //If the user is already in the room, move them to the top if (users.containsKey(event.userId.toLong())) { //Create a new MessageEvent and say it's for the users list val newEvent = MessageEvent(event) newEvent.isForUsersList = true //Put in the users list users.put(event.userId.toLong(), newEvent) } else { //If the user is not in the users list get their profile picture //Determine what URL to use (StackOverflow or StackExchange) val url: String = if (room?.site == Client.SITE_STACK_OVERFLOW) { "https://chat.stackoverflow.com/users/thumbs/${event.userId}" } else { "https://chat.stackexchange.com/users/thumbs/${event.userId}" } //Make a call with Ion (for parsing simplicity) and parse the result doAsync { val client = ClientManager.client val soChatPageRequest = Request.Builder() .url(url) .build() val response = client.newCall(soChatPageRequest).execute() val jsonData = response.body().string() val result = JSONObject(jsonData) //Get the rooms array val rooms = result.getJSONArray("rooms") //Find the current room from it val r: JSONObject? = (0..(rooms.length() - 1)) .map { rooms.getJSONObject(it) } .lastOrNull { it.getInt("id") == roomNum } //Ensure the user is in the room if (r != null) { //Get the profile picture for the user and add it to the user in the users list val newEvent = MessageEvent(event) newEvent.isForUsersList = true val imageUrl = result.getString("email_hash").replace("!", "") if (imageUrl.contains(".")) { newEvent.emailHash = imageUrl } else { newEvent.emailHash = "https://www.gravatar.com/avatar/$imageUrl" } users.put(newEvent.userId, newEvent) } } } } //Make sure the room is the correct room if (room?.num == event.roomId) { //Kotlin version of the switch statement, determine what to do with the event when (event.eventType) { //If the event is a message, add it to the messages ChatEvent.EVENT_TYPE_MESSAGE -> messages.add(MessageEvent(event)) //If the event is an edit, or a delete, then add that new event in place of the old. ChatEvent.EVENT_TYPE_EDIT, ChatEvent.EVENT_TYPE_DELETE -> { val newMessage = MessageEvent(event) val originalMessage = messages.floor(newMessage) if (originalMessage != newMessage) { Timber.w("MessageEventPresenter Attempting to edit nonexistent message") return } newMessage.previous = originalMessage messages.remove(originalMessage) messages.add(newMessage) } //If the event is a starred message, modify the original message with the stars to add it to the event ChatEvent.EVENT_TYPE_STAR -> { val newMessage = MessageEvent(event) val originalMessage = messages.floor(newMessage) if (originalMessage != null) { newMessage.userId = originalMessage.userId newMessage.userName = originalMessage.userName newMessage.messageStars = event.messageStars newMessage.messageStarred = event.messageStarred messages.remove(originalMessage) messages.add(newMessage) } } } } } //Used from adapter to get all the messages override fun getEventsList(): List<MessageEvent> { return Collections.unmodifiableList(ArrayList(messages)) } //Used from adapter to get all the users in a room override fun getUsersList(): List<MessageEvent> { return Collections.unmodifiableList(ArrayList(users.values).sortedByDescending { it.timestamp }) } }
apache-2.0
73ca40d5d69e47f4576f3a9c15f1912e
47.709924
194
0.576489
5.352349
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/increment/postfixIncrementOnSmartCast.kt
3
263
public fun box() : String { var i : Int? i = 10 // Postfix increment on a smart cast should work // Specific: i.inc() type is Int but i and j types are both Int? val j = i++ return if (j == 10 && 11 == i) "OK" else "fail j = $j i = $i" }
apache-2.0
4770cafdbd0939de126e7cb0e38315b7
28.222222
68
0.543726
3.168675
false
false
false
false
google/intellij-community
plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/InvalidEnvironmentImportingTest.kt
3
4648
// 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.idea.maven.importing import com.intellij.build.SyncViewManager import com.intellij.build.events.BuildEvent import com.intellij.maven.testFramework.MavenMultiVersionImportingTestCase import com.intellij.openapi.application.WriteAction import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl import com.intellij.openapi.roots.ProjectRootManager import com.intellij.testFramework.LoggedErrorProcessor import junit.framework.TestCase import org.jetbrains.idea.maven.execution.MavenRunnerSettings import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent import org.jetbrains.idea.maven.server.MavenServerCMDState import org.jetbrains.idea.maven.server.MavenServerManager import org.junit.Test import java.util.* class InvalidEnvironmentImportingTest : MavenMultiVersionImportingTestCase() { private lateinit var myTestSyncViewManager: SyncViewManager private val myEvents: MutableList<BuildEvent> = ArrayList() public override fun setUp() { super.setUp() myTestSyncViewManager = object : SyncViewManager(myProject) { override fun onEvent(buildId: Any, event: BuildEvent) { myEvents.add(event) } } myProjectsManager.setProgressListener(myTestSyncViewManager) } @Test fun testShouldShowWarningIfProjectJDKIsNullAndRollbackToInternal() { val projectSdk = ProjectRootManager.getInstance(myProject).projectSdk val jdkForImporter = MavenWorkspaceSettingsComponent.getInstance(myProject).settings.importingSettings.jdkForImporter try { LoggedErrorProcessor.executeWith<RuntimeException>(loggedErrorProcessor("Project JDK is not specifie")) { MavenWorkspaceSettingsComponent.getInstance(myProject) .settings.getImportingSettings().jdkForImporter = MavenRunnerSettings.USE_PROJECT_JDK WriteAction.runAndWait<Throwable> { ProjectRootManager.getInstance(myProject).projectSdk = null } createAndImportProject() val connectors = MavenServerManager.getInstance().allConnectors.filter { it.project == myProject } assertNotEmpty(connectors) TestCase.assertEquals(JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(), connectors[0].jdk) } } finally { WriteAction.runAndWait<Throwable> { ProjectRootManager.getInstance(myProject).projectSdk = projectSdk } MavenWorkspaceSettingsComponent.getInstance(myProject).settings.importingSettings.jdkForImporter = jdkForImporter } } @Test fun testShouldShowLogsOfMavenServerIfNotStarted() { try { LoggedErrorProcessor.executeWith<RuntimeException>(loggedErrorProcessor("Maven server exception for tests")) { MavenServerCMDState.setThrowExceptionOnNextServerStart() createAndImportProject() assertEvent { it.message.contains("Maven server exception for tests") } } } finally { MavenServerCMDState.resetThrowExceptionOnNextServerStart() } } @Test fun `test maven server not started - bad vm config`() { LoggedErrorProcessor.executeWith<RuntimeException>(loggedErrorProcessor("java.util.concurrent.ExecutionException:")) { createProjectSubFile(".mvn/jvm.config", "-Xms100m -Xmx10m") createAndImportProject() assertEvent { it.message.contains("Error occurred during initialization of VM") } } } @Test fun `test maven import - bad maven config`() { assumeVersionMoreThan("3.3.1") createProjectSubFile(".mvn/maven.config", "-aaaaT1") createAndImportProject() assertModules("test") assertEvent { it.message.contains("Unable to parse maven.config:") } } private fun loggedErrorProcessor(search: String) = object : LoggedErrorProcessor() { override fun processError(category: String, message: String, details: Array<out String>, t: Throwable?): Set<Action> = if (message.contains(search)) Action.NONE else Action.ALL } private fun assertEvent(description: String = "Asserted", predicate: (BuildEvent) -> Boolean) { if (myEvents.isEmpty()) { fail("Message \"${description}\" was not found. No messages was recorded at all") } if (myEvents.any(predicate)) { return } fail("Message \"${description}\" was not found. Known messages:\n" + myEvents.joinToString("\n") { "${it}" }) } private fun createAndImportProject() { createProjectPom("<groupId>test</groupId>" + "<artifactId>test</artifactId>" + "<version>1.0</version>") importProjectWithErrors() } }
apache-2.0
8f29654c404d02e6f8b64a50d4134e31
41.642202
122
0.747849
4.965812
false
true
false
false
jotomo/AndroidAPS
app/src/test/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorageTest.kt
1
3234
package info.nightscout.androidaps.plugins.pump.common.bolusInfo import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.data.DetailedBolusInfo import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class DetailedBolusInfoStorageTest : TestBase() { private val info1 = DetailedBolusInfo() private val info2 = DetailedBolusInfo() private val info3 = DetailedBolusInfo() lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage init { info1.date = 1000000 info1.insulin = 3.0 info2.date = 1000001 info2.insulin = 4.0 info3.date = 2000000 info3.insulin = 5.0 } @Before fun prepare() { detailedBolusInfoStorage = DetailedBolusInfoStorage(aapsLogger) } private fun setUp() { detailedBolusInfoStorage.store.clear() detailedBolusInfoStorage.add(info1) detailedBolusInfoStorage.add(info2) detailedBolusInfoStorage.add(info3) } @Test fun add() { detailedBolusInfoStorage.store.clear() assertEquals(0, detailedBolusInfoStorage.store.size) detailedBolusInfoStorage.add(info1) assertEquals(1, detailedBolusInfoStorage.store.size) } @Test fun findDetailedBolusInfo() { // Look for exact bolus setUp() var d: DetailedBolusInfo? = detailedBolusInfoStorage.findDetailedBolusInfo(1000000, 4.0) assertEquals(4.0, d!!.insulin, 0.01) assertEquals(2, detailedBolusInfoStorage.store.size) // Look for exact bolus setUp() d = detailedBolusInfoStorage.findDetailedBolusInfo(1000000, 3.0) assertEquals(3.0, d!!.insulin, 0.01) assertEquals(2, detailedBolusInfoStorage.store.size) // With less insulin (bolus not delivered completely). Should return first one matching date setUp() d = detailedBolusInfoStorage.findDetailedBolusInfo(1000500, 2.0) assertEquals(3.0, d!!.insulin, 0.01) assertEquals(2, detailedBolusInfoStorage.store.size) // With less insulin (bolus not delivered completely). Should return first one matching date setUp() d = detailedBolusInfoStorage.findDetailedBolusInfo(1000500, 3.5) assertEquals(4.0, d!!.insulin, 0.01) assertEquals(2, detailedBolusInfoStorage.store.size) // With more insulin should return null setUp() d = detailedBolusInfoStorage.findDetailedBolusInfo(1000500, 4.5) assertNull(d) assertEquals(3, detailedBolusInfoStorage.store.size) // With more than one minute off should return null setUp() d = detailedBolusInfoStorage.findDetailedBolusInfo(1070000, 4.0) assertNull(d) assertEquals(3, detailedBolusInfoStorage.store.size) // Use last, if bolus size is the same setUp() d = detailedBolusInfoStorage.findDetailedBolusInfo(1070000, 5.0) assertEquals(5.0, d!!.insulin, 0.01) assertEquals(2, detailedBolusInfoStorage.store.size) } }
agpl-3.0
a2873abc719ffea17fa273e05aa3cae7
34.944444
100
0.692641
4.9
false
true
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertRangeCheckToTwoComparisonsIntention.kt
1
2569
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.hints.RangeKtExpressionType.* import org.jetbrains.kotlin.idea.codeInsight.hints.getRangeBinaryExpressionType import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConvertRangeCheckToTwoComparisonsIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("convert.to.comparisons") ) { private fun KtExpression?.isSimple() = this is KtConstantExpression || this is KtNameReferenceExpression override fun applyTo(element: KtBinaryExpression, editor: Editor?) { element.replace(convertToComparison(element)?.value ?: return) } override fun isApplicableTo(element: KtBinaryExpression) = convertToComparison(element) != null private fun convertToComparison(element: KtBinaryExpression): Lazy<KtExpression>? { if (element.operationToken != KtTokens.IN_KEYWORD) return null // ignore for-loop. for(x in 1..2) should not be convert to for(1<=x && x<=2) if (element.parent is KtForExpression) return null val rangeExpression = element.right ?: return null val arg = element.left ?: return null val (left, right) = rangeExpression.getArguments() ?: return null val context = lazy { rangeExpression.analyze(BodyResolveMode.PARTIAL) } if (!arg.isSimple() || left?.isSimple() != true || right?.isSimple() != true || setOf(arg.getType(context.value), left.getType(context.value), right.getType(context.value)).size != 1) return null val pattern = when (rangeExpression.getRangeBinaryExpressionType(context)) { RANGE_TO -> "$0 <= $1 && $1 <= $2" UNTIL, RANGE_UNTIL -> "$0 <= $1 && $1 < $2" DOWN_TO -> "$0 >= $1 && $1 >= $2" null -> return null } return lazy { KtPsiFactory(element).createExpressionByPattern(pattern, left, arg, right, reformat = false) } } }
apache-2.0
ca3b75d014cf55736ef5e3143fa381ca
51.44898
158
0.725963
4.491259
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/project/ProbablyNothingCallableNamesImpl.kt
4
1512
// 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.project import com.intellij.openapi.project.Project import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener import org.jetbrains.kotlin.idea.stubindex.KotlinProbablyNothingFunctionShortNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinProbablyNothingPropertyShortNameIndex import org.jetbrains.kotlin.resolve.lazy.ProbablyNothingCallableNames class ProbablyNothingCallableNamesImpl(project: Project) : ProbablyNothingCallableNames { private val functionNames = createCachedValue(project) { KotlinProbablyNothingFunctionShortNameIndex.getAllKeys(project) } private val propertyNames = createCachedValue(project) { KotlinProbablyNothingPropertyShortNameIndex.getAllKeys(project) } override fun functionNames(): Collection<String> = functionNames.value override fun propertyNames(): Collection<String> = propertyNames.value } private inline fun createCachedValue(project: Project, crossinline names: () -> Collection<String>) = CachedValuesManager.getManager(project).createCachedValue( { CachedValueProvider.Result.create(names(), KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker) }, false )
apache-2.0
08c1912c0c99243263cab5b3f51e6d1d
57.153846
158
0.823413
5.231834
false
false
false
false
jwren/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/IterableTypesDetection.kt
3
4559
// 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 import com.intellij.openapi.project.Project import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.idea.util.FuzzyType import org.jetbrains.kotlin.idea.util.toFuzzyType import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.resolve.BindingTraceContext import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory import org.jetbrains.kotlin.resolve.constants.IntegerLiteralTypeConstructor import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.utils.collectFunctions import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext import org.jetbrains.kotlin.types.expressions.ForLoopConventionsChecker import org.jetbrains.kotlin.util.isValidOperator import org.jetbrains.kotlin.utils.getOrPutNullable import java.util.* class IterableTypesDetection( private val project: Project, private val forLoopConventionsChecker: ForLoopConventionsChecker, private val languageVersionSettings: LanguageVersionSettings, private val dataFlowValueFactory: DataFlowValueFactory ) { companion object { private val iteratorName = Name.identifier("iterator") } fun createDetector(scope: LexicalScope): IterableTypesDetector { return Detector(scope) } private inner class Detector(private val scope: LexicalScope) : IterableTypesDetector { private val cache = HashMap<FuzzyType, FuzzyType?>() private val typesWithExtensionIterator: Collection<KotlinType> = scope .collectFunctions(iteratorName, NoLookupLocation.FROM_IDE) .filter { it.isValidOperator() } .mapNotNull { it.extensionReceiverParameter?.type } override fun isIterable(type: FuzzyType, loopVarType: KotlinType?): Boolean { val elementType = elementType(type) ?: return false return loopVarType == null || elementType.checkIsSubtypeOf(loopVarType) != null } override fun isIterable(type: KotlinType, loopVarType: KotlinType?): Boolean = isIterable(type.toFuzzyType(emptyList()), loopVarType) private fun elementType(type: FuzzyType): FuzzyType? { return cache.getOrPutNullable(type) { elementTypeNoCache(type) } } override fun elementType(type: KotlinType): FuzzyType? = elementType(type.toFuzzyType(emptyList())) private fun elementTypeNoCache(type: FuzzyType): FuzzyType? { // optimization if (!canBeIterable(type)) return null val expression = KtPsiFactory(project).createExpression("fake") val context = ExpressionTypingContext.newContext( BindingTraceContext(), scope, DataFlowInfo.EMPTY, TypeUtils.NO_EXPECTED_TYPE, languageVersionSettings, dataFlowValueFactory ) val expressionReceiver = ExpressionReceiver.create(expression, type.type, context.trace.bindingContext) val elementType = forLoopConventionsChecker.checkIterableConvention(expressionReceiver, context) return elementType?.let { it.toFuzzyType(type.freeParameters) } } private fun canBeIterable(type: FuzzyType): Boolean { if (type.type.constructor is IntegerLiteralTypeConstructor) return false return type.type.memberScope.getContributedFunctions(iteratorName, NoLookupLocation.FROM_IDE).isNotEmpty() || typesWithExtensionIterator.any { val freeParams = it.arguments.mapNotNull { it.type.constructor.declarationDescriptor as? TypeParameterDescriptor } type.checkIsSubtypeOf(it.toFuzzyType(freeParams)) != null } } } } interface IterableTypesDetector { fun isIterable(type: KotlinType, loopVarType: KotlinType? = null): Boolean fun isIterable(type: FuzzyType, loopVarType: KotlinType? = null): Boolean fun elementType(type: KotlinType): FuzzyType? }
apache-2.0
67fe3ac26c25664dfc8418735a5ddd7b
47.510638
158
0.747313
5.210286
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/ConvertCallChainIntoSequenceInspection.kt
1
11015
// 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.collections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent import com.intellij.psi.PsiWhiteSpace import com.intellij.ui.EditorTextField import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import java.awt.BorderLayout import javax.swing.JPanel class ConvertCallChainIntoSequenceInspection : AbstractKotlinInspection() { private val defaultCallChainLength = 5 private var callChainLength = defaultCallChainLength var callChainLengthText = defaultCallChainLength.toString() set(value) { field = value callChainLength = value.toIntOrNull() ?: defaultCallChainLength } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(expression) { val (qualified, firstCall, callChainLength) = expression.findCallChain() ?: return val rangeInElement = firstCall.calleeExpression?.textRange?.shiftRight(-qualified.startOffset) ?: return val highlightType = if (callChainLength >= this.callChainLength) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION holder.registerProblemWithoutOfflineInformation( qualified, KotlinBundle.message("call.chain.on.collection.could.be.converted.into.sequence.to.improve.performance"), isOnTheFly, highlightType, rangeInElement, ConvertCallChainIntoSequenceFix() ) }) override fun createOptionsPanel(): JPanel = OptionsPanel(this) private class OptionsPanel(owner: ConvertCallChainIntoSequenceInspection) : JPanel() { init { layout = BorderLayout() val regexField = EditorTextField(owner.callChainLengthText).apply { setOneLineMode(true) } regexField.document.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { owner.callChainLengthText = regexField.text } }) val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("call.chain.length.to.transform"), BorderLayout.WEST) add(labeledComponent, BorderLayout.NORTH) } } } private class ConvertCallChainIntoSequenceFix : LocalQuickFix { override fun getName() = KotlinBundle.message("convert.call.chain.into.sequence.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtQualifiedExpression ?: return val context = expression.analyze(BodyResolveMode.PARTIAL) val calls = expression.collectCallExpression(context).reversed() val firstCall = calls.firstOrNull() ?: return val lastCall = calls.lastOrNull() ?: return val first = firstCall.getQualifiedExpressionForSelector() ?: firstCall val last = lastCall.getQualifiedExpressionForSelector() ?: return val endWithTermination = lastCall.isTermination(context) val psiFactory = KtPsiFactory(expression) val dot = buildString { if (first is KtQualifiedExpression && first.receiverExpression.siblings().filterIsInstance<PsiWhiteSpace>().any { it.textContains('\n') } ) append("\n") if (first is KtSafeQualifiedExpression) append("?") append(".") } val firstCommentSaver = CommentSaver(first) val firstReplaced = first.replaced( psiFactory.buildExpression { if (first is KtQualifiedExpression) { appendExpression(first.receiverExpression) appendFixedText(dot) } appendExpression(psiFactory.createExpression("asSequence()")) appendFixedText(dot) appendExpression(firstCall) } ) firstCommentSaver.restore(firstReplaced) if (!endWithTermination) { val lastCommentSaver = CommentSaver(last) val lastReplaced = last.replace( psiFactory.buildExpression { appendExpression(last) appendFixedText(dot) appendExpression(psiFactory.createExpression("toList()")) } ) lastCommentSaver.restore(lastReplaced) } } } private data class CallChain( val qualified: KtQualifiedExpression, val firstCall: KtCallExpression, val callChainLength: Int ) private fun KtQualifiedExpression.findCallChain(): CallChain? { if (parent is KtQualifiedExpression) return null val context = safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val calls = collectCallExpression(context) if (calls.isEmpty()) return null val lastCall = calls.last() val receiverType = lastCall.receiverType(context) if (receiverType?.isIterable(DefaultBuiltIns.Instance) != true) return null val firstCall = calls.first() val qualified = firstCall.getQualifiedExpressionForSelector() ?: firstCall.getQualifiedExpressionForReceiver() ?: return null return CallChain(qualified, lastCall, calls.size) } private fun KtQualifiedExpression.collectCallExpression(context: BindingContext): List<KtCallExpression> { val calls = mutableListOf<KtCallExpression>() fun collect(qualified: KtQualifiedExpression) { val call = qualified.callExpression ?: return calls.add(call) val receiver = qualified.receiverExpression if (receiver is KtCallExpression && receiver.implicitReceiver(context) != null) { calls.add(receiver) return } if (receiver is KtQualifiedExpression) collect(receiver) } collect(this) if (calls.size < 2) return emptyList() val transformationCalls = calls .asSequence() .dropWhile { !it.isTransformationOrTermination(context) } .takeWhile { it.isTransformationOrTermination(context) && !it.hasReturn() } .toList() .dropLastWhile { it.isLazyTermination(context) } if (transformationCalls.size < 2) return emptyList() return transformationCalls } private fun KtCallExpression.hasReturn(): Boolean = valueArguments.any { arg -> arg.anyDescendantOfType<KtReturnExpression> { it.labelQualifier == null } } private fun KtCallExpression.isTransformationOrTermination(context: BindingContext): Boolean { val fqName = transformationAndTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isTermination(context: BindingContext): Boolean { val fqName = terminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isLazyTermination(context: BindingContext): Boolean { val fqName = lazyTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } internal val collectionTransformationFunctionNames = listOf( "chunked", "distinct", "distinctBy", "drop", "dropWhile", "filter", "filterIndexed", "filterIsInstance", "filterNot", "filterNotNull", "flatten", "map", "mapIndexed", "mapIndexedNotNull", "mapNotNull", "minus", "minusElement", "onEach", "onEachIndexed", "plus", "plusElement", "requireNoNulls", "sorted", "sortedBy", "sortedByDescending", "sortedDescending", "sortedWith", "take", "takeWhile", "windowed", "withIndex", "zipWithNext" ) @NonNls private val transformations = collectionTransformationFunctionNames.associateWith { FqName("kotlin.collections.$it") } internal val collectionTerminationFunctionNames = listOf( "all", "any", "asIterable", "asSequence", "associate", "associateBy", "associateByTo", "associateTo", "average", "contains", "count", "elementAt", "elementAtOrElse", "elementAtOrNull", "filterIndexedTo", "filterIsInstanceTo", "filterNotNullTo", "filterNotTo", "filterTo", "find", "findLast", "first", "firstNotNullOf", "firstNotNullOfOrNull", "firstOrNull", "fold", "foldIndexed", "groupBy", "groupByTo", "groupingBy", "indexOf", "indexOfFirst", "indexOfLast", "joinTo", "joinToString", "last", "lastIndexOf", "lastOrNull", "mapIndexedNotNullTo", "mapIndexedTo", "mapNotNullTo", "mapTo", "maxOrNull", "maxByOrNull", "maxWithOrNull", "maxOf", "maxOfOrNull", "maxOfWith", "maxOfWithOrNull", "minOrNull", "minByOrNull", "minWithOrNull", "minOf", "minOfOrNull", "minOfWith", "minOfWithOrNull", "none", "partition", "reduce", "reduceIndexed", "reduceIndexedOrNull", "reduceOrNull", "runningFold", "runningFoldIndexed", "runningReduce", "runningReduceIndexed", "scan", "scanIndexed", "single", "singleOrNull", "sum", "sumBy", "sumByDouble", "sumOf", "toCollection", "toHashSet", "toList", "toMutableList", "toMutableSet", "toSet", "toSortedSet", "unzip" ) @NonNls private val terminations = collectionTerminationFunctionNames.associateWith { val pkg = if (it in listOf("contains", "indexOf", "lastIndexOf")) "kotlin.collections.List" else "kotlin.collections" FqName("$pkg.$it") } private val lazyTerminations = terminations.filter { (key, _) -> key == "groupingBy" } private val transformationAndTerminations = transformations + terminations
apache-2.0
8659d1d31891eb8e401fb763f6744954
32.177711
158
0.684612
5.101899
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/RowImpl.kt
1
16022
// 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.ui.dsl.builder.impl import com.intellij.BundleBase import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.util.PopupUtil import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ContextHelpLabel import com.intellij.ui.JBIntSpinner import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.UIBundle import com.intellij.ui.components.* import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.components.* import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.VerticalGaps import com.intellij.ui.layout.* import com.intellij.ui.popup.PopupState import com.intellij.util.Function import com.intellij.util.MathUtil import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBFont import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import java.awt.event.ActionEvent import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.util.* import javax.swing.* @Suppress("OVERRIDE_DEPRECATION") @ApiStatus.Internal internal open class RowImpl(private val dialogPanelConfig: DialogPanelConfig, private val panelContext: PanelContext, private val parent: PanelImpl, rowLayout: RowLayout) : Row { var rowLayout = rowLayout private set var resizableRow = false private set var rowComment: DslLabel? = null private set var topGap: TopGap? = null private set /** * Used if topGap is not set, skipped for first row */ var internalTopGap = 0 var bottomGap: BottomGap? = null private set /** * Used if bottomGap is not set, skipped for last row */ var internalBottomGap = 0 val cells = mutableListOf<CellBaseImpl<*>?>() private var visible = true private var enabled = true override fun layout(rowLayout: RowLayout): RowImpl { this.rowLayout = rowLayout return this } override fun resizableRow(): RowImpl { resizableRow = true return this } override fun rowComment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int, action: HyperlinkEventAction): RowImpl { this.rowComment = createComment(comment, maxLineLength, action) return this } @Suppress("OVERRIDE_DEPRECATION") override fun <T : JComponent> cell(component: T, viewComponent: JComponent): CellImpl<T> { val result = CellImpl(dialogPanelConfig, component, this, viewComponent) cells.add(result) if (component is JRadioButton) { @Suppress("UNCHECKED_CAST") registerRadioButton(result as CellImpl<JRadioButton>, null) } return result } override fun <T : JComponent> cell(component: T): CellImpl<T> { return cell(component, component) } override fun cell() { cells.add(null) } override fun <T : JComponent> scrollCell(component: T): CellImpl<T> { return cell(component, JBScrollPane(component)) } override fun placeholder(): PlaceholderImpl { val result = PlaceholderImpl(this) cells.add(result) return result } override fun enabled(isEnabled: Boolean): RowImpl { enabled = isEnabled if (parent.isEnabled()) { doEnabled(enabled) } return this } fun enabledFromParent(parentEnabled: Boolean): RowImpl { doEnabled(parentEnabled && enabled) return this } fun isEnabled(): Boolean { return enabled && parent.isEnabled() } override fun enabledIf(predicate: ComponentPredicate): RowImpl { enabled(predicate()) predicate.addListener { enabled(it) } return this } override fun visible(isVisible: Boolean): RowImpl { visible = isVisible if (parent.isVisible()) { doVisible(visible) } return this } override fun visibleIf(predicate: ComponentPredicate): Row { visible(predicate()) predicate.addListener { visible(it) } return this } fun visibleFromParent(parentVisible: Boolean): RowImpl { doVisible(parentVisible && visible) return this } fun isVisible(): Boolean { return visible && parent.isVisible() } override fun topGap(topGap: TopGap): RowImpl { this.topGap = topGap return this } override fun bottomGap(bottomGap: BottomGap): RowImpl { this.bottomGap = bottomGap return this } override fun panel(init: Panel.() -> Unit): PanelImpl { val result = PanelImpl(dialogPanelConfig, parent.spacingConfiguration, this) result.init() cells.add(result) return result } override fun checkBox(@NlsContexts.Checkbox text: String): CellImpl<JBCheckBox> { return cell(JBCheckBox(text)).applyToComponent { isOpaque = false } } override fun radioButton(text: String, value: Any?): Cell<JBRadioButton> { val result = cell(JBRadioButton(text)).applyToComponent { isOpaque = false } registerRadioButton(result, value) return result } override fun button(@NlsContexts.Button text: String, actionListener: (event: ActionEvent) -> Unit): CellImpl<JButton> { val button = JButton(BundleBase.replaceMnemonicAmpersand(text)) button.addActionListener(actionListener) button.isOpaque = false return cell(button) } override fun button(text: String, action: AnAction, actionPlace: String): Cell<JButton> { lateinit var result: CellImpl<JButton> result = button(text) { ActionUtil.invokeAction(action, result.component, actionPlace, null, null) } return result } override fun actionButton(action: AnAction, actionPlace: String): Cell<ActionButton> { val component = ActionButton(action, action.templatePresentation.clone(), actionPlace, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) return cell(component) } override fun actionsButton(vararg actions: AnAction, actionPlace: String, icon: Icon): Cell<ActionButton> { val actionGroup = PopupActionGroup(arrayOf(*actions)) actionGroup.templatePresentation.icon = icon return cell(ActionButton(actionGroup, actionGroup.templatePresentation.clone(), actionPlace, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE)) } @Suppress("OVERRIDE_DEPRECATION") override fun <T> segmentedButton(options: Collection<T>, property: GraphProperty<T>, renderer: (T) -> String): Cell<SegmentedButtonToolbar> { val actionGroup = DefaultActionGroup(options.map { DeprecatedSegmentedButtonAction(it, property, renderer(it)) }) val toolbar = SegmentedButtonToolbar(actionGroup, parent.spacingConfiguration) toolbar.targetComponent = null // any data context is supported, suppress warning return cell(toolbar) } override fun <T> segmentedButton(items: Collection<T>, renderer: (T) -> String): SegmentedButton<T> { val result = SegmentedButtonImpl(this, renderer) result.items(items) cells.add(result) return result } override fun tabbedPaneHeader(items: Collection<String>): Cell<JBTabbedPane> { val tabbedPaneHeader = TabbedPaneHeader() for (item in items) { tabbedPaneHeader.add(item, JPanel()) } return cell(tabbedPaneHeader) } override fun slider(min: Int, max: Int, minorTickSpacing: Int, majorTickSpacing: Int): Cell<JSlider> { val slider = JSlider() UIUtil.setSliderIsFilled(slider, true) slider.paintLabels = true slider.paintTicks = true slider.paintTrack = true slider.minimum = min slider.maximum = max slider.minorTickSpacing = minorTickSpacing slider.majorTickSpacing = majorTickSpacing return cell(slider) } override fun label(text: String): CellImpl<JLabel> { return cell(JLabel(text)) } override fun text(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): Cell<JEditorPane> { val dslLabel = DslLabel(DslLabelType.LABEL) dslLabel.action = action dslLabel.maxLineLength = maxLineLength dslLabel.text = text val result = cell(dslLabel) if (maxLineLength == MAX_LINE_LENGTH_WORD_WRAP) { result.align(AlignX.FILL) } return result } override fun comment(comment: String, maxLineLength: Int, action: HyperlinkEventAction): CellImpl<JEditorPane> { val result: CellImpl<JEditorPane> = cell(createComment(comment, maxLineLength, action)) if (maxLineLength == MAX_LINE_LENGTH_WORD_WRAP) { result.align(AlignX.FILL) } return result } override fun link(text: String, action: (ActionEvent) -> Unit): CellImpl<ActionLink> { return cell(ActionLink(text, action)) } override fun browserLink(text: String, url: String): CellImpl<BrowserLink> { return cell(BrowserLink(text, url)) } override fun <T> dropDownLink(item: T, items: List<T>, onSelected: ((T) -> Unit)?, updateText: Boolean): Cell<DropDownLink<T>> { return cell(DropDownLink(item, items, onSelect = { t -> onSelected?.let { it(t) } }, updateText = updateText)) } override fun icon(icon: Icon): CellImpl<JLabel> { return cell(JBLabel(icon)) } override fun contextHelp(description: String, title: String?): CellImpl<JLabel> { val result = if (title == null) ContextHelpLabel.create(description) else ContextHelpLabel.create(title, description) return cell(result) } override fun textField(): CellImpl<JBTextField> { val result = cell(JBTextField()) result.columns(COLUMNS_SHORT) return result } override fun textFieldWithBrowseButton(browseDialogTitle: String?, project: Project?, fileChooserDescriptor: FileChooserDescriptor, fileChosen: ((chosenFile: VirtualFile) -> String)?): Cell<TextFieldWithBrowseButton> { val result = cell(textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen)).applyToComponent { isOpaque = false textField.isOpaque = false } result.columns(COLUMNS_SHORT) return result } override fun passwordField(): CellImpl<JBPasswordField> { val result = cell(JBPasswordField()) result.columns(COLUMNS_SHORT) return result } override fun expandableTextField(parser: Function<in String, out MutableList<String>>, joiner: Function<in MutableList<String>, String>): Cell<ExpandableTextField> { val result = cell(ExpandableTextField(parser, joiner)) result.columns(COLUMNS_SHORT) return result } override fun intTextField(range: IntRange?, keyboardStep: Int?): CellImpl<JBTextField> { val result = cell(JBTextField()) .validationOnInput { val value = it.text.toIntOrNull() when { value == null -> error(UIBundle.message("please.enter.a.number")) range != null && value !in range -> error(UIBundle.message("please.enter.a.number.from.0.to.1", range.first, range.last)) else -> null } } result.columns(COLUMNS_TINY) result.component.putClientProperty(DSL_INT_TEXT_RANGE_PROPERTY, range) keyboardStep?.let { result.component.addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent?) { val increment: Int = when (e?.keyCode) { KeyEvent.VK_UP -> keyboardStep KeyEvent.VK_DOWN -> -keyboardStep else -> return } var value = result.component.text.toIntOrNull() if (value != null) { value += increment if (range != null) { value = MathUtil.clamp(value, range.first, range.last) } result.component.text = value.toString() e.consume() } } }) } return result } override fun spinner(range: IntRange, step: Int): CellImpl<JBIntSpinner> { return cell(JBIntSpinner(range.first, range.first, range.last, step)).applyToComponent { isOpaque = false } } override fun spinner(range: ClosedRange<Double>, step: Double): Cell<JSpinner> { return cell(JSpinner(SpinnerNumberModel(range.start, range.start, range.endInclusive, step))).applyToComponent { isOpaque = false } } override fun textArea(): Cell<JBTextArea> { val textArea = JBTextArea() // Text area should have same margins as TextField. When margin is TestArea used then border is MarginBorder and margins are taken // into account twice, which is hard to workaround in current API. So use border instead textArea.border = JBEmptyBorder(3, 5, 3, 5) textArea.columns = COLUMNS_SHORT textArea.font = JBFont.regular() textArea.emptyText.setFont(JBFont.regular()) textArea.putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps.EMPTY) return scrollCell(textArea) } override fun <T> comboBox(model: ComboBoxModel<T>, renderer: ListCellRenderer<in T?>?): Cell<ComboBox<T>> { val component = ComboBox(model) component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() } return cell(component) } override fun <T> comboBox(items: Collection<T>, renderer: ListCellRenderer<in T?>?): Cell<ComboBox<T>> { val component = ComboBox(DefaultComboBoxModel(Vector(items))) component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() } return cell(component) } @Suppress("OVERRIDE_DEPRECATION") override fun <T> comboBox(items: Array<T>, renderer: ListCellRenderer<T?>?): Cell<ComboBox<T>> { val component = ComboBox(items) component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() } return cell(component) } override fun customize(customRowGaps: VerticalGaps): Row { internalTopGap = customRowGaps.top internalBottomGap = customRowGaps.bottom topGap = null bottomGap = null return this } fun getIndent(): Int { return panelContext.indentCount * parent.spacingConfiguration.horizontalIndent } private fun doVisible(isVisible: Boolean) { for (cell in cells) { cell?.visibleFromParent(isVisible) } rowComment?.let { it.isVisible = isVisible } } private fun doEnabled(isEnabled: Boolean) { for (cell in cells) { cell?.enabledFromParent(isEnabled) } rowComment?.let { it.isEnabled = isEnabled } } private fun registerRadioButton(cell: CellImpl<out JRadioButton>, value: Any?) { val buttonsGroup = dialogPanelConfig.context.getButtonsGroup() ?: throw UiDslException( "Button group must be defined before using radio button") buttonsGroup.add(cell, value) } } private class PopupActionGroup(private val actions: Array<AnAction>): ActionGroup(), DumbAware { private val popupState = PopupState.forPopup() init { isPopup = true templatePresentation.isPerformGroup = actions.isNotEmpty() } override fun getChildren(e: AnActionEvent?): Array<AnAction> = actions override fun actionPerformed(e: AnActionEvent) { if (popupState.isRecentlyHidden) { return } val popup = JBPopupFactory.getInstance().createActionGroupPopup(null, this, e.dataContext, JBPopupFactory.ActionSelectionAid.MNEMONICS, true) popupState.prepareToShow(popup) PopupUtil.showForActionButtonEvent(popup, e) } }
apache-2.0
d2cc963a6a8a248aa5e92de5f41c48bd
32.448852
158
0.706591
4.495511
false
false
false
false
androidx/androidx
tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/grid/LazySemanticsTest.kt
3
5813
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy.grid import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.requiredWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.SemanticsActions.ScrollToIndex import androidx.compose.ui.semantics.SemanticsProperties.IndexForKey import androidx.compose.ui.semantics.getOrNull import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.assert import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Tests the semantics properties defined on a LazyGrid: * - GetIndexForKey * - ScrollToIndex * * GetIndexForKey: * Create a lazy grid, iterate over all indices, verify key of each of them * * ScrollToIndex: * Create a lazy grid, scroll to a line off screen, verify shown items * * All tests performed in [runTest], scenarios set up in the test methods. */ @MediumTest @RunWith(AndroidJUnit4::class) class LazySemanticsTest { private val N = 20 private val LazyGridTag = "lazy_grid" private val LazyGridModifier = Modifier.testTag(LazyGridTag).requiredSize(100.dp) private fun tag(index: Int): String = "tag_$index" private fun key(index: Int): String = "key_$index" @get:Rule val rule = createComposeRule() @Test fun itemSemantics_verticalGrid() { rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(1), LazyGridModifier) { repeat(N) { item(key = key(it)) { SpacerInColumn(it) } } } } runTest() } @Test fun itemsSemantics_verticalGrid() { rule.setContent { val state = rememberTvLazyGridState() TvLazyVerticalGrid(TvGridCells.Fixed(1), LazyGridModifier, state) { items(items = List(N) { it }, key = { key(it) }) { SpacerInColumn(it) } } } runTest() } // @Test // fun itemSemantics_row() { // rule.setContent { // LazyRow(LazyGridModifier) { // repeat(N) { // item(key = key(it)) { // SpacerInRow(it) // } // } // } // } // runTest() // } // @Test // fun itemsSemantics_row() { // rule.setContent { // LazyRow(LazyGridModifier) { // items(items = List(N) { it }, key = { key(it) }) { // SpacerInRow(it) // } // } // } // runTest() // } private fun runTest() { checkViewport(firstExpectedItem = 0, lastExpectedItem = 3) // Verify IndexForKey rule.onNodeWithTag(LazyGridTag).assert( SemanticsMatcher.keyIsDefined(IndexForKey).and( SemanticsMatcher("keys match") { node -> val actualIndex = node.config.getOrNull(IndexForKey)!! (0 until N).all { expectedIndex -> expectedIndex == actualIndex.invoke(key(expectedIndex)) } } ) ) // Verify ScrollToIndex rule.onNodeWithTag(LazyGridTag).assert(SemanticsMatcher.keyIsDefined(ScrollToIndex)) invokeScrollToIndex(targetIndex = 10) checkViewport(firstExpectedItem = 10, lastExpectedItem = 13) invokeScrollToIndex(targetIndex = N - 1) checkViewport(firstExpectedItem = N - 4, lastExpectedItem = N - 1) } private fun invokeScrollToIndex(targetIndex: Int) { val node = rule.onNodeWithTag(LazyGridTag) .fetchSemanticsNode("Failed: invoke ScrollToIndex") rule.runOnUiThread { node.config[ScrollToIndex].action!!.invoke(targetIndex) } } private fun checkViewport(firstExpectedItem: Int, lastExpectedItem: Int) { if (firstExpectedItem > 0) { rule.onNodeWithTag(tag(firstExpectedItem - 1)).assertDoesNotExist() } (firstExpectedItem..lastExpectedItem).forEach { rule.onNodeWithTag(tag(it)).assertExists() } if (firstExpectedItem < N - 1) { rule.onNodeWithTag(tag(lastExpectedItem + 1)).assertDoesNotExist() } } @Composable private fun SpacerInColumn(index: Int) { Spacer(Modifier.testTag(tag(index)).requiredHeight(30.dp).fillMaxWidth()) } @Composable private fun SpacerInRow(index: Int) { Spacer(Modifier.testTag(tag(index)).requiredWidth(30.dp).fillMaxHeight()) } }
apache-2.0
5f8566dcfc3d5902adc2123c8e6e0e17
32.217143
92
0.633408
4.562794
false
true
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/AbstractKotlinUVariable.kt
4
6358
// 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.uast.kotlin import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.elements.KtLightAbstractAnnotation import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable @ApiStatus.Internal abstract class AbstractKotlinUVariable( givenParent: UElement? ) : KotlinAbstractUElement(givenParent), PsiVariable, UVariableEx, UAnchorOwner { override val uastInitializer: UExpression? get() { val initializerExpression = when (val psi = psi) { is UastKotlinPsiVariable -> psi.ktInitializer is UastKotlinPsiParameter -> psi.ktDefaultValue is KtLightElement<*, *> -> { when (val origin = psi.kotlinOrigin?.takeIf { it.canAnalyze() }) { // EA-137191 is KtVariableDeclaration -> origin.initializer is KtParameter -> origin.defaultValue else -> null } } else -> null } ?: return null return languagePlugin?.convertElement(initializerExpression, this) as? UExpression ?: UastEmptyExpression(null) } protected val delegateExpression: UExpression? by lz { val expression = when (val psi = psi) { is KtLightElement<*, *> -> (psi.kotlinOrigin as? KtProperty)?.delegateExpression is UastKotlinPsiVariable -> (psi.ktElement as? KtProperty)?.delegateExpression else -> null } expression?.let { languagePlugin?.convertElement(it, this) as? UExpression } } override fun getNameIdentifier(): PsiIdentifier { val kotlinOrigin = (psi as? KtLightElement<*, *>)?.kotlinOrigin return UastLightIdentifier(psi, kotlinOrigin as? KtDeclaration) } override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile) override val uAnnotations by lz { val sourcePsi = sourcePsi ?: return@lz psi.annotations.map { WrappedUAnnotation(it, this) } val annotations = SmartList<UAnnotation>(KotlinNullabilityUAnnotation(baseResolveProviderService, sourcePsi, this)) if (sourcePsi is KtModifierListOwner) { sourcePsi.annotationEntries .filter { acceptsAnnotationTarget(it.useSiteTarget?.getAnnotationUseSiteTarget()) } .mapTo(annotations) { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) } } annotations } protected abstract fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean override val typeReference: UTypeReferenceExpression? by lz { KotlinUTypeReferenceExpression((sourcePsi as? KtCallableDeclaration)?.typeReference, this) { type } } override val uastAnchor: UIdentifier? get() { val identifierSourcePsi = when (val sourcePsi = sourcePsi) { is KtNamedDeclaration -> sourcePsi.nameIdentifier is KtTypeReference -> sourcePsi.typeElement?.let { // receiver param in extension function (it as? KtUserType)?.referenceExpression?.getIdentifier() ?: it } ?: sourcePsi is KtNameReferenceExpression -> sourcePsi.getReferencedNameElement() is KtBinaryExpression, is KtCallExpression -> null // e.g. `foo("Lorem ipsum") ?: foo("dolor sit amet")` is KtDestructuringDeclaration -> sourcePsi.valOrVarKeyword is KtLambdaExpression -> sourcePsi.functionLiteral.lBrace else -> sourcePsi } ?: return null return KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this) } override fun equals(other: Any?) = other is AbstractKotlinUVariable && psi == other.psi class WrappedUAnnotation( psiAnnotation: PsiAnnotation, override val uastParent: UElement ) : UAnnotation, UAnchorOwner, DelegatedMultiResolve { override val javaPsi: PsiAnnotation = psiAnnotation override val psi: PsiAnnotation = javaPsi override val sourcePsi: PsiElement? = psiAnnotation.safeAs<KtLightAbstractAnnotation>()?.kotlinOrigin override val attributeValues: List<UNamedExpression> by lz { psi.parameterList.attributes.map { WrappedUNamedExpression(it, this) } } override val uastAnchor: UIdentifier by lz { KotlinUIdentifier( { javaPsi.nameReferenceElement?.referenceNameElement }, sourcePsi.safeAs<KtAnnotationEntry>()?.typeReference?.nameElement, this ) } class WrappedUNamedExpression( pair: PsiNameValuePair, override val uastParent: UElement? ) : UNamedExpression { override val name: String? = pair.name override val psi = pair override val javaPsi: PsiElement = psi override val sourcePsi: PsiElement? = null override val uAnnotations: List<UAnnotation> = emptyList() override val expression: UExpression by lz { toUExpression(psi.value) } } override val qualifiedName: String? = psi.qualifiedName override fun findAttributeValue(name: String?): UExpression? = psi.findAttributeValue(name)?.let { toUExpression(it) } override fun findDeclaredAttributeValue(name: String?): UExpression? = psi.findDeclaredAttributeValue(name)?.let { toUExpression(it) } override fun resolve(): PsiClass? = psi.nameReferenceElement?.resolve() as? PsiClass } } private fun toUExpression(psi: PsiElement?): UExpression = psi.toUElementOfType() ?: UastEmptyExpression(null)
apache-2.0
c385531a56c0d9cea4e70806aa714bfe
45.072464
158
0.671752
5.8117
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/imports/ImportMapper.kt
4
4220
// 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.imports import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.name.FqName class ImportMapper { companion object { private val UTIL_TO_COLLECTIONS get() = createPackageMapping( javaPackage = "java.util", kotlinPackage = "kotlin.collections", names = listOf( "RandomAccess", "ArrayList", "LinkedHashMap", "HashMap", "LinkedHashSet", "HashSet", ), ) private val CONCURRENT_TO_CANCELLATION get() = createPackageMapping( javaPackage = "java.util.concurrent", kotlinPackage = "kotlin.coroutines.cancellation", version = ApiVersion.KOTLIN_1_4, names = listOf("CancellationException"), ) private val LANG_TO_TEXT get() = createPackageMapping( javaPackage = "java.lang", kotlinPackage = "kotlin.text", names = listOf("Appendable", "StringBuilder"), ) private val CHARSET_TO_TEXT get() = createPackageMapping( javaPackage = "java.nio.charset", kotlinPackage = "kotlin.text", version = ApiVersion.KOTLIN_1_4, names = listOf("CharacterCodingException"), ) private val KOTLIN_JVM_TO_KOTLIN get() = createPackageMapping( javaPackage = "kotlin.jvm", kotlinPackage = "kotlin", version = ApiVersion.KOTLIN_1_4, names = listOf("Throws"), ) private val LANG_TO_KOTLIN get() = createPackageMapping( javaPackage = "java.lang", kotlinPackage = "kotlin", names = listOf( "Error", "Exception", "RuntimeException", "IllegalArgumentException", "IllegalStateException", "IndexOutOfBoundsException", "UnsupportedOperationException", "ArithmeticException", "NumberFormatException", "NullPointerException", "ClassCastException", "AssertionError", ), ) private val UTIL_TO_KOTLIN get() = createPackageMapping( javaPackage = "java.util", kotlinPackage = "kotlin", names = listOf( "NoSuchElementException", "ConcurrentModificationException", "Comparator", ), ) private fun createPackageMapping( javaPackage: String, kotlinPackage: String, version: ApiVersion = ApiVersion.KOTLIN_1_3, names: List<String>, ): Map<FqName, FqNameWithVersion> = names.associate { FqName("$javaPackage.$it") to FqNameWithVersion(FqName("$kotlinPackage.$it"), version) } private val javaToKotlinMap: Map<FqName, FqNameWithVersion> = UTIL_TO_COLLECTIONS + //CONCURRENT_TO_CANCELLATION + // experimental LANG_TO_TEXT + CHARSET_TO_TEXT + KOTLIN_JVM_TO_KOTLIN + LANG_TO_KOTLIN + UTIL_TO_KOTLIN @TestOnly fun getImport2AliasMap(): Map<FqName, FqName> = javaToKotlinMap.mapValues { it.value.fqName } fun findCorrespondingKotlinFqName(fqName: FqName, availableVersion: ApiVersion): FqName? { return javaToKotlinMap[fqName]?.takeIf { it.version <= availableVersion }?.fqName } } } private data class FqNameWithVersion(val fqName: FqName, val version: ApiVersion)
apache-2.0
670a348e585b2b565f91dafca4bfdf35
36.017544
158
0.524171
5.844875
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHEditableHtmlPaneHandle.kt
2
1890
// 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 org.jetbrains.plugins.github.pullrequest.ui import com.intellij.CommonBundle import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt import com.intellij.collaboration.ui.CollaborationToolsUIUtil import com.intellij.openapi.project.Project import com.intellij.ui.components.panels.VerticalLayout import org.jetbrains.plugins.github.pullrequest.comment.ui.GHCommentTextFieldFactory import org.jetbrains.plugins.github.pullrequest.comment.ui.GHCommentTextFieldModel import java.util.concurrent.CompletableFuture import javax.swing.JComponent import javax.swing.JPanel internal class GHEditableHtmlPaneHandle(private val project: Project, private val paneComponent: JComponent, private val getSourceText: () -> String, private val updateText: (String) -> CompletableFuture<out Any?>) { val panel = JPanel(VerticalLayout(8, VerticalLayout.FILL)).apply { isOpaque = false add(paneComponent) } private var editor: JComponent? = null fun showAndFocusEditor() { if (editor == null) { val model = GHCommentTextFieldModel(project, getSourceText()) { newText -> updateText(newText).successOnEdt { hideEditor() } } editor = GHCommentTextFieldFactory(model).create(CommonBundle.message("button.submit"), onCancel = { hideEditor() }) panel.add(editor!!) panel.validate() panel.repaint() } editor?.let { CollaborationToolsUIUtil.focusPanel(it) } } private fun hideEditor() { editor?.let { panel.remove(it) panel.revalidate() panel.repaint() } editor = null } }
apache-2.0
4be36397708ee11359ca3134ec4020f0
32.767857
140
0.687302
4.713217
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GHRepositoryCoordinates.kt
2
1081
// 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.plugins.github.api import git4idea.remote.hosting.HostedRepositoryCoordinates import com.intellij.openapi.util.NlsSafe data class GHRepositoryCoordinates(override val serverPath: GithubServerPath, val repositoryPath: GHRepositoryPath) : HostedRepositoryCoordinates { fun toUrl(): String { return serverPath.toUrl() + "/" + repositoryPath } @NlsSafe override fun toString(): String { return "$serverPath/$repositoryPath" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is GHRepositoryCoordinates) return false if (!serverPath.equals(other.serverPath, true)) return false if (repositoryPath != other.repositoryPath) return false return true } override fun hashCode(): Int { var result = serverPath.hashCode() result = 31 * result + repositoryPath.hashCode() return result } }
apache-2.0
d3350a1f40bdf4cd4f2bbef4960e892c
29.885714
140
0.711378
4.804444
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/kotlin/TextFragment.kt
1
1288
package com.zhou.android.kotlin import android.graphics.Color import android.os.Bundle import android.support.annotation.ColorInt import android.support.annotation.ColorRes import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.zhou.android.R /** * Created by mxz on 2019/7/25. */ class TextFragment : Fragment() { private var text: TextView? = null private var str = "" private var color = Color.WHITE var mark = 0 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { text = inflater.inflate(R.layout.fragment_text, container, false) as TextView return text } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) text?.text = str text?.setBackgroundColor(color) } fun setText(_str: String) { if (text == null) { str = _str } else { text?.text = _str } } fun bg(@ColorInt c: Int) { if (text == null) { color = c } else { text?.setBackgroundColor(c) } } }
mit
c166661d2f2df70b67c6b8c2aa6c034d
23.788462
116
0.647516
4.264901
false
false
false
false
jwren/intellij-community
plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/NativeDefinitions.kt
3
9417
// 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.ide.konan import com.intellij.extapi.psi.PsiFileBase import com.intellij.lang.* import com.intellij.lexer.FlexAdapter import com.intellij.lexer.Lexer import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.fileTypes.* import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.tree.* import javax.swing.Icon import java.io.Reader import org.jetbrains.kotlin.ide.konan.psi.* import org.jetbrains.kotlin.idea.KotlinIcons const val KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION = "def" const val KOTLIN_NATIVE_DEFINITIONS_ID = "KND" val KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION get() = KotlinNativeBundle.message("kotlin.native.definitions.description") object NativeDefinitionsFileType : LanguageFileType(NativeDefinitionsLanguage.INSTANCE) { override fun getName(): String = "Kotlin/Native Def" override fun getDescription(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION override fun getDefaultExtension(): String = KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION override fun getIcon(): Icon = KotlinIcons.NATIVE } class NativeDefinitionsLanguage private constructor() : Language(KOTLIN_NATIVE_DEFINITIONS_ID) { companion object { val INSTANCE = NativeDefinitionsLanguage() } override fun getDisplayName(): String = KotlinNativeBundle.message("kotlin.native.definitions.short") } class NativeDefinitionsFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, NativeDefinitionsLanguage.INSTANCE) { override fun getFileType(): FileType = NativeDefinitionsFileType override fun toString(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION override fun getIcon(flags: Int): Icon? = super.getIcon(flags) } class NativeDefinitionsLexerAdapter : FlexAdapter(NativeDefinitionsLexer(null as Reader?)) class NativeDefinitionsParserDefinition : ParserDefinition { private val COMMENTS = TokenSet.create(NativeDefinitionsTypes.COMMENT) private val FILE = IFileElementType(NativeDefinitionsLanguage.INSTANCE) override fun getWhitespaceTokens(): TokenSet = TokenSet.WHITE_SPACE override fun getCommentTokens(): TokenSet = COMMENTS override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY override fun getFileNodeType(): IFileElementType = FILE override fun createLexer(project: Project): Lexer = NativeDefinitionsLexerAdapter() override fun createParser(project: Project): PsiParser = NativeDefinitionsParser() override fun createFile(viewProvider: FileViewProvider): PsiFile = NativeDefinitionsFile(viewProvider) override fun createElement(node: ASTNode): PsiElement = NativeDefinitionsTypes.Factory.createElement(node) override fun spaceExistenceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements = ParserDefinition.SpaceRequirements.MAY } class CLanguageInjector : LanguageInjector { val cLanguage = Language.findLanguageByID("ObjectiveC") override fun getLanguagesToInject(host: PsiLanguageInjectionHost, registrar: InjectedLanguagePlaces) { if (!host.isValid) return if (host is NativeDefinitionsCodeImpl && cLanguage != null) { val range = host.getTextRange().shiftLeft(host.startOffsetInParent) registrar.addPlace(cLanguage, range, null, null) } } } object NativeDefinitionsSyntaxHighlighter : SyntaxHighlighterBase() { override fun getTokenHighlights(tokenType: IElementType?): Array<TextAttributesKey> = when (tokenType) { TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS NativeDefinitionsTypes.COMMENT -> COMMENT_KEYS NativeDefinitionsTypes.DELIM -> COMMENT_KEYS NativeDefinitionsTypes.SEPARATOR -> OPERATOR_KEYS NativeDefinitionsTypes.UNKNOWN_KEY -> BAD_CHAR_KEYS NativeDefinitionsTypes.UNKNOWN_PLATFORM -> BAD_CHAR_KEYS NativeDefinitionsTypes.VALUE -> VALUE_KEYS // known properties NativeDefinitionsTypes.COMPILER_OPTS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.DEPENDS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.DISABLE_DESIGNATED_INITIALIZER_CHECKS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.ENTRY_POINT -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDE_DEPENDENT_MODULES -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDE_SYSTEM_LIBS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDED_FUNCTIONS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDED_MACROS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXPORT_FORWARD_DECLARATIONS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.HEADERS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.HEADER_FILTER -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LANGUAGE -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LIBRARY_PATHS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LINKER -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LINKER_OPTS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.MODULES -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.NON_STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.NO_STRING_CONVERSION -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.PACKAGE -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.STATIC_LIBRARIES -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS // known extensions NativeDefinitionsTypes.ANDROID -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_X86 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS_ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_ARM32_HFP -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_MIPS32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_MIPSEL32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MACOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MINGW -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MINGW_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MIPS32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MIPSEL32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.OSX -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.TVOS -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.TVOS_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.TVOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WASM -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WASM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_X86 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.X64 -> KNOWN_EXTENSIONS_KEYS else -> EMPTY_KEYS } override fun getHighlightingLexer(): Lexer = NativeDefinitionsLexerAdapter() private fun createKeys(externalName: String, key: TextAttributesKey): Array<TextAttributesKey> { return arrayOf(TextAttributesKey.createTextAttributesKey(externalName, key)) } private val BAD_CHAR_KEYS = createKeys("Unknown key", HighlighterColors.BAD_CHARACTER) private val COMMENT_KEYS = createKeys("Comment", DefaultLanguageHighlighterColors.LINE_COMMENT) private val EMPTY_KEYS = emptyArray<TextAttributesKey>() private val KNOWN_EXTENSIONS_KEYS = createKeys("Known extension", DefaultLanguageHighlighterColors.LABEL) private val KNOWN_PROPERTIES_KEYS = createKeys("Known property", DefaultLanguageHighlighterColors.KEYWORD) private val OPERATOR_KEYS = createKeys("Operator", DefaultLanguageHighlighterColors.OPERATION_SIGN) private val VALUE_KEYS = createKeys("Value", DefaultLanguageHighlighterColors.STRING) } class NativeDefinitionsSyntaxHighlighterFactory : SyntaxHighlighterFactory() { override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter = NativeDefinitionsSyntaxHighlighter }
apache-2.0
b7de4f1b391837c6414ac48ba1ec295e
51.910112
125
0.747903
5.612038
false
false
false
false
hotchemi/PermissionsDispatcher
sample/src/main/kotlin/permissions/dispatcher/sample/contacts/ContactsFragment.kt
2
6027
package permissions.dispatcher.sample.contacts import android.content.ContentProviderOperation import android.content.OperationApplicationException import android.database.Cursor import android.os.Bundle import android.os.RemoteException import android.provider.ContactsContract import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.fragment.app.Fragment import androidx.loader.app.LoaderManager import androidx.loader.content.CursorLoader import androidx.loader.content.Loader import permissions.dispatcher.sample.R import kotlin.properties.Delegates /** * Displays the first contact stored on the device and contains an option to add a dummy contact. * * * This Fragment is only used to illustrate that access to the Contacts ContentProvider API has * been granted (or denied) as part of the runtime permissions model. It is not relevant for the * use * of the permissions API. * * * This fragments demonstrates a basic use case for accessing the Contacts Provider. The * implementation is based on the training guide available here: * https://developer.android.com/training/contacts-provider/retrieve-names.html */ class ContactsFragment : Fragment(), LoaderManager.LoaderCallbacks<Cursor> { private var messageText: TextView by Delegates.notNull() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.fragment_contacts, container, false)!! override fun onViewCreated(view: View, savedInstanceState: Bundle?) { messageText = view.findViewById(R.id.contact_message) val button: Button? = view.findViewById(R.id.back) button?.setOnClickListener { fragmentManager?.popBackStack() } val addButton: Button = view.findViewById(R.id.contact_add) addButton.setOnClickListener { insertDummyContact() } val loadButton: Button = view.findViewById(R.id.contact_load) loadButton.setOnClickListener { loadContact() } } /** * Restart the Loader to query the Contacts content provider to display the first contact. */ private fun loadContact() = loaderManager.restartLoader(0, null, this) /** * Initialises a new [CursorLoader] that queries the [ContactsContract]. */ override fun onCreateLoader(i: Int, bundle: Bundle?): Loader<Cursor> = CursorLoader(activity!!.applicationContext, ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null, ORDER) /** * Dislays either the name of the first contact or a message. */ override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor?) { cursor?.let { val totalCount: Int = it.count if (totalCount > 0) { it.moveToFirst() val name = it.getString(it.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) messageText.text = resources.getString(R.string.contacts_string, totalCount, name) Log.d(TAG, "First contact loaded: $name") Log.d(TAG, "Total number of contacts: $totalCount") Log.d(TAG, "Total number of contacts: $totalCount") } else { Log.d(TAG, "List of contacts is empty.") messageText.setText(R.string.contacts_empty) } } } override fun onLoaderReset(loader: Loader<Cursor>) = messageText.setText(R.string.contacts_empty) /** * Accesses the Contacts content provider directly to insert a new contact. * * * The contact is called "__DUMMY ENTRY" and only contains a name. */ private fun insertDummyContact() { // Two operations are needed to insert a new contact. val operations = arrayListOf<ContentProviderOperation>() // First, set up a new raw contact. ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) .build().let { operations.add(it) } // Next, set the name for the contact. ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DUMMY_CONTACT_NAME) .build().let { operations.add(it) } // Apply the operations. try { activity?.contentResolver?.applyBatch(ContactsContract.AUTHORITY, operations) } catch (e: RemoteException) { Log.d(TAG, "Could not add a new contact: " + e.message) } catch (e: OperationApplicationException) { Log.d(TAG, "Could not add a new contact: " + e.message) } } companion object { private const val TAG = "Contacts" private const val DUMMY_CONTACT_NAME = "__DUMMY CONTACT from runtime permissions sample" /** * Projection for the content provider query includes the id and primary name of a contact. */ private val PROJECTION = arrayOf(ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY) /** * Sort order for the query. Sorted by primary name in ascending order. */ private const val ORDER = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC" /** * Creates a new instance of a ContactsFragment. */ fun newInstance(): ContactsFragment = ContactsFragment() } }
apache-2.0
597270f6e7da69ec730fa73991a890e2
38.913907
188
0.670981
4.91198
false
false
false
false
LouisCAD/Splitties
modules/views-dsl/src/androidMain/kotlin/splitties/views/dsl/core/Views.kt
1
12128
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.views.dsl.core import android.content.Context import android.view.View import android.widget.* import androidx.annotation.IdRes import androidx.annotation.StyleRes import kotlin.contracts.InvocationKind import kotlin.contracts.contract // TextView inline fun Context.textView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: TextView.() -> Unit = {} ): TextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.textView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: TextView.() -> Unit = {} ): TextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.textView(id, theme, initView) } inline fun Ui.textView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: TextView.() -> Unit = {} ): TextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.textView(id, theme, initView) } // Button inline fun Context.button( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Button.() -> Unit = {} ): Button { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.button( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Button.() -> Unit = {} ): Button { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.button(id, theme, initView) } inline fun Ui.button( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Button.() -> Unit = {} ): Button { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.button(id, theme, initView) } // ImageView inline fun Context.imageView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: ImageView.() -> Unit = {} ): ImageView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.imageView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: ImageView.() -> Unit = {} ): ImageView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.imageView(id, theme, initView) } inline fun Ui.imageView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: ImageView.() -> Unit = {} ): ImageView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.imageView(id, theme, initView) } // EditText inline fun Context.editText( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: EditText.() -> Unit = {} ): EditText { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.editText( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: EditText.() -> Unit = {} ): EditText { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.editText(id, theme, initView) } inline fun Ui.editText( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: EditText.() -> Unit = {} ): EditText { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.editText(id, theme, initView) } // Spinner inline fun Context.spinner( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Spinner.() -> Unit = {} ): Spinner { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.spinner( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Spinner.() -> Unit = {} ): Spinner { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.spinner(id, theme, initView) } inline fun Ui.spinner( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Spinner.() -> Unit = {} ): Spinner { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.spinner(id, theme, initView) } // ImageButton inline fun Context.imageButton( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: ImageButton.() -> Unit = {} ): ImageButton { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.imageButton( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: ImageButton.() -> Unit = {} ): ImageButton { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.imageButton(id, theme, initView) } inline fun Ui.imageButton( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: ImageButton.() -> Unit = {} ): ImageButton { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.imageButton(id, theme, initView) } // CheckBox inline fun Context.checkBox( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: CheckBox.() -> Unit = {} ): CheckBox { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.checkBox( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: CheckBox.() -> Unit = {} ): CheckBox { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.checkBox(id, theme, initView) } inline fun Ui.checkBox( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: CheckBox.() -> Unit = {} ): CheckBox { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.checkBox(id, theme, initView) } // RadioButton inline fun Context.radioButton( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: RadioButton.() -> Unit = {} ): RadioButton { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.radioButton( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: RadioButton.() -> Unit = {} ): RadioButton { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.radioButton(id, theme, initView) } inline fun Ui.radioButton( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: RadioButton.() -> Unit = {} ): RadioButton { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.radioButton(id, theme, initView) } // CheckedTextView inline fun Context.checkedTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: CheckedTextView.() -> Unit = {} ): CheckedTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.checkedTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: CheckedTextView.() -> Unit = {} ): CheckedTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.checkedTextView(id, theme, initView) } inline fun Ui.checkedTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: CheckedTextView.() -> Unit = {} ): CheckedTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.checkedTextView(id, theme, initView) } // AutoCompleteTextView inline fun Context.autoCompleteTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: AutoCompleteTextView.() -> Unit = {} ): AutoCompleteTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.autoCompleteTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: AutoCompleteTextView.() -> Unit = {} ): AutoCompleteTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.autoCompleteTextView(id, theme, initView) } inline fun Ui.autoCompleteTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: AutoCompleteTextView.() -> Unit = {} ): AutoCompleteTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.autoCompleteTextView(id, theme, initView) } // MultiAutoCompleteTextView inline fun Context.multiAutoCompleteTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: MultiAutoCompleteTextView.() -> Unit = {} ): MultiAutoCompleteTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.multiAutoCompleteTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: MultiAutoCompleteTextView.() -> Unit = {} ): MultiAutoCompleteTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.multiAutoCompleteTextView(id, theme, initView) } inline fun Ui.multiAutoCompleteTextView( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: MultiAutoCompleteTextView.() -> Unit = {} ): MultiAutoCompleteTextView { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.multiAutoCompleteTextView(id, theme, initView) } // RatingBar inline fun Context.ratingBar( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: RatingBar.() -> Unit = {} ): RatingBar { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.ratingBar( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: RatingBar.() -> Unit = {} ): RatingBar { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.ratingBar(id, theme, initView) } inline fun Ui.ratingBar( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: RatingBar.() -> Unit = {} ): RatingBar { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.ratingBar(id, theme, initView) } // SeekBar inline fun Context.seekBar( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: SeekBar.() -> Unit = {} ): SeekBar { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.seekBar( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: SeekBar.() -> Unit = {} ): SeekBar { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.seekBar(id, theme, initView) } inline fun Ui.seekBar( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: SeekBar.() -> Unit = {} ): SeekBar { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.seekBar(id, theme, initView) } // Space inline fun Context.space( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Space.() -> Unit = {} ): Space { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return view(id, theme, initView) } inline fun View.space( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Space.() -> Unit = {} ): Space { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return context.space(id, theme, initView) } inline fun Ui.space( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: Space.() -> Unit = {} ): Space { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.space(id, theme, initView) }
apache-2.0
a54473170b95b732e3488967c11d401e
28.014354
109
0.674802
3.813836
false
false
false
false
smmribeiro/intellij-community
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/model/SearchEverywhereMLRankingModelProvider.kt
1
3369
// 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.ide.actions.searcheverywhere.ml.model import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereMlSessionService import com.intellij.internal.ml.DecisionFunction import com.intellij.internal.ml.FeaturesInfo import com.intellij.internal.ml.catboost.CatBoostResourcesModelMetadataReader import com.intellij.openapi.extensions.ExtensionPointName /** * Provides model to predict relevance of each element in Search Everywhere tab */ internal abstract class SearchEverywhereMLRankingModelProvider { companion object { private val EP_NAME: ExtensionPointName<SearchEverywhereMLRankingModelProvider> = ExtensionPointName.create("com.intellij.searcheverywhere.ml.rankingModelProvider") fun getForTab(contributorId: String): SearchEverywhereMLRankingModelProvider { return EP_NAME.findFirstSafe { it.supportedContributor.simpleName == contributorId } ?: throw IllegalArgumentException("Unsupported contributor $contributorId") } } /** * Returns a model used for ranking. * If a path to a local model is specified, a local model will be returned, provided that the user is in an experimental group. * This is so that, a new model can be easily compared to an existing one. * * If no path is specified, then a bundled model will be provided which can either be experimental or standard, * depending on the return value of [shouldProvideExperimentalModel]. */ val model: DecisionFunction get() { return if (shouldProvideLocalModel() && shouldProvideExperimentalModel()) { getLocalModel() } else { getBundledModel() } } /** * Returns a model bundled with the IDE. * This function, if implemented in a ranking provider where sorting by ML is enabled by default, * should use [shouldProvideExperimentalModel] function to return an appropriate model. * * For providers that only have one experimental model, just returning that model will suffice. */ protected abstract fun getBundledModel(): DecisionFunction protected abstract val supportedContributor: Class<out SearchEverywhereContributor<*>> protected fun shouldProvideExperimentalModel(): Boolean { return SearchEverywhereMlSessionService.getService().shouldUseExperimentalModel(supportedContributor.simpleName) } private fun shouldProvideLocalModel(): Boolean { return LocalRankingModelProviderUtil.isPathToLocalModelSpecified(supportedContributor.simpleName) } private fun getLocalModel(): DecisionFunction { return LocalRankingModelProviderUtil.getLocalModel(supportedContributor.simpleName)!! } protected fun getCatBoostModel(resourceDirectory: String, modelDirectory: String): DecisionFunction { val metadataReader = CatBoostResourcesModelMetadataReader(this::class.java, resourceDirectory, modelDirectory) val metadata = FeaturesInfo.buildInfo(metadataReader) val model = metadataReader.loadModel() return object : SearchEverywhereMLRankingDecisionFunction(metadata) { override fun predict(features: DoubleArray): Double = model.makePredict(features) } } }
apache-2.0
0137b9a75f0a33783760a5977c7a9dbe
43.933333
158
0.781241
5.135671
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeIntention.kt
1
5468
// 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.intentions import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.util.elementType import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.refactoring.addTypeArgumentsIfNeeded import org.jetbrains.kotlin.idea.refactoring.getQualifiedTypeArgumentList import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.checkers.ExplicitApiDeclarationChecker import org.jetbrains.kotlin.types.typeUtil.isUnit class RemoveExplicitTypeIntention : SelfTargetingRangeIntention<KtCallableDeclaration>( KtCallableDeclaration::class.java, KotlinBundle.lazyMessage("remove.explicit.type.specification") ), HighPriorityAction { override fun applicabilityRange(element: KtCallableDeclaration): TextRange? = getRange(element) override fun applyTo(element: KtCallableDeclaration, editor: Editor?) = removeExplicitType(element) companion object { fun removeExplicitType(element: KtCallableDeclaration) { val initializer = (element as? KtProperty)?.initializer val typeArgumentList = initializer?.let { getQualifiedTypeArgumentList(it) } element.typeReference = null if (typeArgumentList != null) addTypeArgumentsIfNeeded(initializer, typeArgumentList) } fun isApplicableTo(element: KtCallableDeclaration): Boolean { return getRange(element) != null } fun getRange(element: KtCallableDeclaration): TextRange? { if (element.containingFile is KtCodeFragment) return null val typeReference = element.typeReference ?: return null if (typeReference.annotationEntries.isNotEmpty()) return null if (element is KtParameter) { if (element.isLoopParameter) return element.textRange if (element.isSetterParameter) return typeReference.textRange } if (element !is KtProperty && element !is KtNamedFunction) return null if (element is KtNamedFunction && element.hasBlockBody() && (element.descriptor as? FunctionDescriptor)?.returnType?.isUnit()?.not() != false ) return null val initializer = (element as? KtDeclarationWithInitializer)?.initializer if (element is KtProperty && element.isVar && initializer?.node?.elementType == KtNodeTypes.NULL) return null if (ExplicitApiDeclarationChecker.publicReturnTypeShouldBePresentInApiMode( element, element.languageVersionSettings, element.resolveToDescriptorIfAny() ) ) return null if (!redundantTypeSpecification(element.typeReference, initializer)) return null return when { initializer != null -> TextRange(element.startOffset, initializer.startOffset - 1) element is KtProperty && element.getter != null -> TextRange(element.startOffset, typeReference.endOffset) element is KtNamedFunction -> TextRange(element.startOffset, typeReference.endOffset) else -> null } } tailrec fun redundantTypeSpecification(typeReference: KtTypeReference?, initializer: KtExpression?): Boolean { if (initializer == null || typeReference == null) return true if (initializer !is KtLambdaExpression && initializer !is KtNamedFunction) return true val typeElement = typeReference.typeElement ?: return true if (typeReference.hasModifier(KtTokens.SUSPEND_KEYWORD)) return false return when (typeElement) { is KtFunctionType -> { if (typeElement.receiver != null) return false if (typeElement.parameters.isEmpty()) return true val valueParameters = when (initializer) { is KtLambdaExpression -> initializer.valueParameters is KtNamedFunction -> initializer.valueParameters else -> emptyList() } valueParameters.isNotEmpty() && valueParameters.none { it.typeReference == null } } is KtUserType -> { val typeAlias = typeElement.referenceExpression?.mainReference?.resolve() as? KtTypeAlias ?: return true return redundantTypeSpecification(typeAlias.getTypeReference(), initializer) } else -> true } } } } internal val KtParameter.isSetterParameter: Boolean get() = (parent.parent as? KtPropertyAccessor)?.isSetter ?: false
apache-2.0
ead3b10efa914ab777afcbd969ddc8e6
49.62963
158
0.68654
5.860665
false
false
false
false