Q: Charm Down PicturesService not working I'm still having problems getting the Charm Down PicturesService to work.
(I already posted a question regarding the issue).
Now I created a very simple test application and updated the build.gradle file with the latest library versions.
However, the PicturesService is still working very unreliable.  Selecting a picture sometimes works, sometimes it doesn't. Taking a picture seems to be working even more unreliable.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {   classpath 'org.javafxports:jfxmobile-plugin:1.3.5'}
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'com.gluonapplication.GluonApplication'

dependencies {
    compile 'com.gluonhq:charm:4.3.4'
    compile 'org.javafxports:jfxdvk:8.60.9'
    compileNoRetrolambda 'com.airhacks:afterburner.mfx:1.6.2'
}

jfxmobile {
    downConfig {
        version = '3.3.0'
        plugins 'display', 'lifecycle', 'statusbar', 'storage', 'pictures'
    }
    android {
        manifest = 'src/android/AndroidManifest.xml'
        compileSdkVersion = '23'

        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE.txt'
            exclude 'license/LICENSE.txt'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/NOTICE.txt'
        }
    }
}

The necessary permissions are added to the AndroidManifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

MobileApplication:
public class GluonApplication extends MobileApplication {

    @Override
    public void init() {

        addViewFactory(HOME_VIEW, () ->
            {

                PicturesService pictureService = Services.get(PicturesService.class)
                                                         .orElseThrow(() -> new IllegalStateException("Failed to get PictureService"));

                Button btnLoadImage = new Button("load image");
                btnLoadImage.setOnAction(e -> pictureService.loadImageFromGallery().ifPresent(i -> imv.setImage(i)));

                CheckBox chkSavePicture = new CheckBox("save picture");

                Button btnTakePhoto = new Button("take photo");
                btnTakePhoto.setOnAction(e -> pictureService.takePhoto(chkSavePicture.isSelected()).ifPresent(i -> imv.setImage(i)));

                ImageView imv= new ImageView();
                imv.setFitHeight(300);
                imv.setFitWidth(300);

                VBox content = new VBox(16, btnLoadImage, btnTakePhoto, chkSavePicture, imv);
                content.setAlignment(Pos.CENTER);

                return new View(content);
            });
    }
}

Tested on a Huawei P9 lite, Android 6.0
Logcat take photo succeeded:
05-13 16:08:49.200: V/FXActivity(18796): onActivityResult with requestCode 2 and resultCode = -1 and intent = null
05-13 16:08:50.180: V/FXActivity(18796): onRestart
05-13 16:08:50.187: V/FXActivity(18796): onStart
05-13 16:08:50.187: V/FXActivity(18796): onResume
05-13 16:08:50.196: V/FXEntity(18796): Surface created.
05-13 16:08:50.198: V/FXActivity native(18796): [JVDBG] SURFACE created native android window at 0xe7c9b208, surface = 0xffac4e60
05-13 16:08:50.202: D/mali_winsys(18796): new_window_surface returns 0x3000
05-13 16:08:50.202: I/GLASS(18796): Native code is notified that surface has changed (repaintall)!
05-13 16:08:50.203: V/FXEntity(18796): Called Surface changed [1080, 1740], format 4
05-13 16:08:50.203: V/FXActivity native(18796): [JVDBG] SURFACE created native android window at 0xe7c9b208, surface = 0xffac4e40
05-13 16:08:50.204: I/GLASS(18796): Native code is notified that surface has changed with size provided (repaintall)!
05-13 16:08:50.204: V/FXEntity(18796): Called Surface redraw needed
05-13 16:08:50.205: V/FXEntity(18796): Redraw...
05-13 16:08:50.205: I/GLASS(18796): Call surfaceRedrawNeeded
05-13 16:08:50.205: I/GLASS(18796): Native code is notified that surface needs to be redrawn (repaintall)!
05-13 16:08:50.205: V/FXEntity(18796): Wait a while before doing this again...
05-13 16:08:50.230: I/System.out(18796): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_20
05-13 16:08:50.310: I/System.out(18796): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_28
05-13 16:08:50.408: V/FXEntity(18796): Redraw again...
05-13 16:08:50.408: I/GLASS(18796): Call surfaceRedrawNeeded
05-13 16:08:50.408: I/GLASS(18796): Native code is notified that surface needs to be redrawn (repaintall)!
05-13 16:08:50.416: I/OpenGLRenderer(18796): Initialized EGL, version 1.4
05-13 16:08:50.419: D/mali_winsys(18796): new_window_surface returns 0x3000

Logcat take photo failed:
    05-13 22:18:38.264: I/art(9381): Late-enabling -Xcheck:jni
    05-13 22:18:38.299: D/ActivityThread(9381): ActivityThread,attachApplication
    05-13 16:07:13.229: D/HwCust(18033): Create obj success use class android.content.res.HwCustHwResourcesImpl
    05-13 16:07:13.393: I/MultiDex(18033): VM with version 2.1.0 has multidex support
    05-13 16:07:13.393: I/MultiDex(18033): install
    05-13 16:07:13.393: I/MultiDex(18033): VM has multidex support, MultiDex support library is disabled.
    05-13 16:07:13.429: V/FXActivity(18033): Initializing JavaFX Platform, using 8.60.9-SNAPSHOT
    05-13 16:07:13.438: V/FXActivity native(18033): Loading JavaFXDalvik library
    05-13 16:07:13.452: V/HwPolicyFactory(18033): : success to get AllImpl object and return....
    05-13 16:07:13.474: I/HwCust(18033): Constructor found for class android.app.HwCustHwWallpaperManagerImpl
    05-13 16:07:13.474: D/HwCust(18033): Create obj success use class android.app.HwCustHwWallpaperManagerImpl
    05-13 16:07:13.475: V/ActivityThread(18033): ActivityThread,callActivityOnCreate
    05-13 16:07:13.482: I/System.out(18033): usetextureview = false, useswipekeyboard = false
    05-13 16:07:13.484: I/HwSecImmHelper(18033): mSecurityInputMethodService is null
    05-13 16:07:13.485: V/FXActivity(18033): onCreate called, using 8.60.9-SNAPSHOT
    05-13 16:07:13.486: V/FXActivity native(18033): Notification queue instance created.
    05-13 16:07:13.486: V/FXActivity native(18033): Notification queue started
    05-13 16:07:13.498: V/HwWidgetFactory(18033): : successes to get AllImpl object and return....
    05-13 16:07:13.542: V/FXActivity native(18033): appDataDir: /data/user/0/com.gluonapplication
    05-13 16:07:13.543: V/FXActivity(18033): onStart
    05-13 16:07:13.544: D/ActivityThread(18033): add activity client record, r= ActivityRecord{a0b6377 token=android.os.BinderProxy@a432176 {com.gluonapplication/javafxports.android.FXActivity}} token= android.os.BinderProxy@a432176
    05-13 16:07:13.544: V/FXActivity(18033): onActivityResult with requestCode 2 and resultCode = -1 and intent = null
    05-13 16:07:13.544: V/FXActivity(18033): onResume
    05-13 16:07:13.566: D/OpenGLRenderer(18033): Use EGL_SWAP_BEHAVIOR_PRESERVED: false
    05-13 16:07:13.638: I/OpenGLRenderer(18033): Initialized EGL, version 1.4
    05-13 16:07:13.655: D/mali_winsys(18033): new_window_surface returns 0x3000
    05-13 16:07:13.665: V/FXEntity(18033): Surface created.
    05-13 16:07:13.666: V/FXActivity native(18033): [JVDBG] SURFACE created native android window at 0xe7c99d08, surface = 0xffac4f30
    05-13 16:07:13.816: I/System.out(18033): user.locale=de-DE
    05-13 16:07:13.816: I/System.out(18033): javax.xml.stream.XMLEventFactory=com.sun.xml.stream.events.ZephyrEvent...
    05-13 16:07:13.816: I/System.out(18033): prism.text=native
    05-13 16:07:13.816: I/System.out(18033): java.vendor.url=http://www.android.com/
    05-13 16:07:13.816: I/System.out(18033): java.ext.dirs=
    05-13 16:07:13.816: I/System.out(18033): line.separator=
    05-13 16:07:13.816: I/System.out(18033): file.encoding=UTF-8
    05-13 16:07:13.816: I/System.out(18033): java.runtime.version=0.9
    05-13 16:07:13.816: I/System.out(18033): prism.dirtyopts=true
    05-13 16:07:13.816: I/System.out(18033): user.name=root
    05-13 16:07:13.816: I/System.out(18033): java.compiler=
    05-13 16:07:13.816: I/System.out(18033): android.icu.unicode.version=7.0
    05-13 16:07:13.816: I/System.out(18033): javax.xml.stream.XMLOutputFactory=com.sun.xml.stream.ZephyrWriterFactory
    05-13 16:07:13.816: I/System.out(18033): prism.debugfonts=true
    05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.gestures.rotate=true
    05-13 16:07:13.816: I/System.out(18033): java.version=0
    05-13 16:07:13.816: I/System.out(18033): android.icu.library.version=55.1
    05-13 16:07:13.816: I/System.out(18033): use.egl=true
    05-13 16:07:13.816: I/System.out(18033): embedded=monocle
    05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.gestures.scroll=true
    05-13 16:07:13.816: I/System.out(18033): prism.lcdtext=false
    05-13 16:07:13.816: I/System.out(18033): os.arch=armv7l
    05-13 16:07:13.816: I/System.out(18033): java.io.tmpdir=/data/user/0/com.gluonapplication/cache
    05-13 16:07:13.816: I/System.out(18033): glass.platform=Monocle
    05-13 16:07:13.816: I/System.out(18033): android.zlib.version=1.2.8
    05-13 16:07:13.816: I/System.out(18033): user.language=de
    05-13 16:07:13.816: I/System.out(18033): java.vm.version=2.1.0
    05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.isEmbedded=true
    05-13 16:07:13.816: I/System.out(18033): javax.xml.stream.XMLInputFactory=com.sun.xml.stream.ZephyrParserFactory
    05-13 16:07:13.816: I/System.out(18033): prism.glDepthSize=16
    05-13 16:07:13.816: I/System.out(18033): path.separator=:
    05-13 16:07:13.816: I/System.out(18033): java.runtime.name=Android Runtime
    05-13 16:07:13.816: I/System.out(18033): java.specification.version=0.9
    05-13 16:07:13.816: I/System.out(18033): user.dir=/
    05-13 16:07:13.816: I/System.out(18033): prism.maxTextureSize=2048
    05-13 16:07:13.816: I/System.out(18033): java.vm.specification.vendor=The Android Project
    05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.gestures.zoom=true
    05-13 16:07:13.816: I/System.out(18033): java.vm.name=Dalvik
    05-13 16:07:13.816: I/System.out(18033): monocle.platform=Android
    05-13 16:07:13.816: I/System.out(18033): log.lens=FINEST
    05-13 16:07:13.816: I/System.out(18033): java.vm.specification.version=0.9
    05-13 16:07:13.816: I/System.out(18033): user.home=
    05-13 16:07:13.816: I/System.out(18033): java.specification.name=Dalvik Core Library
    05-13 16:07:13.816: I/System.out(18033): file.separator=/
    05-13 16:07:13.816: I/System.out(18033): java.library.path=/vendor/lib:/system/lib
    05-13 16:07:13.816: I/System.out(18033): user.variant=
    05-13 16:07:13.816: I/System.out(18033): os.version=3.10.90-g033208c
    05-13 16:07:13.816: I/System.out(18033): java.boot.class.path=/system/framework/core-libart.jar:/sy...
    05-13 16:07:13.816: I/System.out(18033): DALVIK.prism.verbose=true
    05-13 16:07:13.816: I/System.out(18033): java.vm.specification.name=Dalvik Virtual Machine Specification
    05-13 16:07:13.816: I/System.out(18033): javafx.platform=android
    05-13 16:07:13.816: I/System.out(18033): glass.lens=eglfb
    05-13 16:07:13.816: I/System.out(18033): os.name=Linux
    05-13 16:07:13.816: I/System.out(18033): user.region=DE
    05-13 16:07:13.816: I/System.out(18033): java.class.path=.
    05-13 16:07:13.816: I/System.out(18033): android.icu.impl.ICUBinary.dataPath=/data/misc/zoneinfo/current/icu:/syst...
    05-13 16:07:13.816: I/System.out(18033): prism.verbose=true
    05-13 16:07:13.816: I/System.out(18033): prism.vsync=false
    05-13 16:07:13.816: I/System.out(18033): java.specification.vendor=The Android Project
    05-13 16:07:13.816: I/System.out(18033): java.vm.vendor=The Android Project
    05-13 16:07:13.816: I/System.out(18033): prism.allowhidpi=true
    05-13 16:07:13.816: I/System.out(18033): java.vendor=The Android Project
    05-13 16:07:13.816: I/System.out(18033): http.agent=Dalvik/2.1.0 (Linux; U; Android 6.0; ...
    05-13 16:07:13.816: I/System.out(18033): android.icu.cldr.version=27.0.1
    05-13 16:07:13.816: I/System.out(18033): android.openssl.version=BoringSSL
    05-13 16:07:13.817: I/System.out(18033): java.home=/system
    05-13 16:07:13.817: I/System.out(18033): java.vm.vendor.url=http://www.android.com/
    05-13 16:07:13.817: I/System.out(18033): java.class.version=50.0
    05-13 16:07:13.817: V/DalvikLauncher(18033): Launch JavaFX application on DALVIK vm.
    05-13 16:07:13.848: V/DalvikLauncher(18033): We have JavaFX on our current (base) classpath, registered exit listener
    05-13 16:07:13.854: V/DalvikLauncher(18033): application class: [class com.gluonapplication.GluonApplication]
    05-13 16:07:13.854: V/DalvikLauncher(18033): preloader class: [null]
    05-13 16:07:13.854: V/DalvikLauncher(18033): javafx application class: [class javafx.application.Application]
    05-13 16:07:13.854: V/DalvikLauncher(18033): javafx launcher class: [class com.sun.javafx.application.LauncherImpl]
    05-13 16:07:13.854: V/DalvikLauncher(18033): launch application method: [public static void com.sun.javafx.application.LauncherImpl.launchApplication(java.lang.Class,java.lang.Class,java.lang.String[])]
    05-13 16:07:13.871: V/FXEntity(18033): Called Surface changed [1080, 1740], format 4
    05-13 16:07:13.871: V/FXActivity native(18033): [JVDBG] SURFACE created native android window at 0xe7c99d08, surface = 0xffac4f10
    05-13 16:07:13.871: V/FXEntity(18033): Called Surface redraw needed
    05-13 16:07:13.878: V/FXEntity(18033): Called Surface redraw needed
    05-13 16:07:13.993: I/System.out(18033): Prism pipeline init order: es2
    05-13 16:07:13.993: I/System.out(18033): Using native-based Pisces rasterizer
    05-13 16:07:13.993: I/System.out(18033): Using dirty region optimizations
    05-13 16:07:13.993: I/System.out(18033): Using system sized mask for primitives
    05-13 16:07:13.993: I/System.out(18033): Not forcing power of 2 sizes for textures
    05-13 16:07:13.993: I/System.out(18033): Using hardware CLAMP_TO_ZERO mode
    05-13 16:07:13.993: I/System.out(18033): Opting in for HiDPI pixel scaling
    05-13 16:07:14.000: I/System.out(18033): Prism pipeline name = com.sun.prism.es2.ES2Pipeline
    05-13 16:07:14.010: I/System.out(18033): Loading ES2 native library ... prism_es2_monocle
    05-13 16:07:14.023: I/System.out(18033):    succeeded.
    05-13 16:07:14.023: I/System.out(18033): GLFactory using com.sun.prism.es2.MonocleGLFactory
    05-13 16:07:14.054: I/GLASS(18033): I have to Call dlopen libGLESv2.so
    05-13 16:07:14.055: I/GLASS(18033): handle = 0xf76fcd04
    05-13 16:07:14.055: I/GLASS(18033): I have to Call dlopen libEGL.so
    05-13 16:07:14.056: I/GLASS(18033): handle = 0xf76fc9c4
    05-13 16:07:14.057: I/GLASS(18033): Binding to libactivity.so
    05-13 16:07:14.058: I/GLASS(18033): GetNativeWindow = 0xf3762da1, getDensitiy = 0xf3762dad
    05-13 16:07:14.058: V/FXEntity(18033): notify_glassHasStarted called in FXActivity. register device now.
    05-13 16:07:14.079: D/mali_winsys(18033): new_window_surface returns 0x3000
    05-13 16:07:14.089: I/System.out(18033): (X) Got class = class com.sun.prism.es2.ES2Pipeline
    05-13 16:07:14.104: I/System.out(18033): Initialized prism pipeline: com.sun.prism.es2.ES2Pipeline
    05-13 16:07:14.127: I/DENSITY(18033): GETDENSITY, answer = 3.000000
    05-13 16:07:14.185: I/System.out(18033): Maximum supported texture size: 8192
    05-13 16:07:14.186: I/System.out(18033): Maximum texture size clamped to 2048
    05-13 16:07:14.186: I/System.out(18033): Non power of two texture support = true
    05-13 16:07:14.186: I/System.out(18033): Maximum number of vertex attributes = 16
    05-13 16:07:14.186: I/System.out(18033): Maximum number of uniform vertex components = 4096
    05-13 16:07:14.186: I/System.out(18033): Maximum number of uniform fragment components = 4096
    05-13 16:07:14.186: I/System.out(18033): Maximum number of varying components = 60
    05-13 16:07:14.186: I/System.out(18033): Maximum number of texture units usable in a vertex shader = 16
    05-13 16:07:14.186: I/System.out(18033): Maximum number of texture units usable in a fragment shader = 16
    05-13 16:07:14.190: I/System.out(18033): Graphics Vendor: ARM
    05-13 16:07:14.191: I/System.out(18033):        Renderer: Mali-T830
    05-13 16:07:14.192: I/System.out(18033):         Version: OpenGL ES 3.1 v1.r8p0-01dev0.bbfc5a14ef62ccdf784a9fff6af72acd
    05-13 16:07:14.216: I/System.out(18033): register device done
    05-13 16:07:14.227: W/System.err(18033):  vsync: false vpipe: true
    05-13 16:07:14.227: I/System.out(18033): [MON] Create device
    05-13 16:07:14.230: I/System.out(18033): [MON] Create device done, add done
    05-13 16:07:14.414: W/System.err(18033): Loading FontFactory com.sun.javafx.font.freetype.FTFactory
    05-13 16:07:14.414: W/System.err(18033): Subpixel: enabled
    05-13 16:07:14.434: W/System.err(18033): Freetype2 Loaded (version 2.5.0)
    05-13 16:07:14.434: W/System.err(18033): LCD support Enabled
    05-13 16:07:14.444: W/art(18033): Before Android 4.1, method void com.sun.javafx.scene.transform.TransformUtils$ImmutableTransform.ensureCanTransform2DPoint() would have incorrectly overridden the package-private method in javafx.scene.transform.Transform
    05-13 16:07:14.630: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF415078203.tmp
    05-13 16:07:14.643: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF1552782793.tmp
    05-13 16:07:14.650: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF-728135178.tmp
    05-13 16:07:14.657: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF-646868817.tmp
    05-13 16:07:14.828: W/art(18033): Before Android 4.1, method double javafx.scene.text.TextFlow.computeChildPrefAreaHeight(javafx.scene.Node, javafx.geometry.Insets) would have incorrectly overridden the package-private method in javafx.scene.layout.Region
    05-13 16:07:14.828: W/art(18033): Before Android 4.1, method double javafx.scene.text.TextFlow.computeChildPrefAreaWidth(javafx.scene.Node, javafx.geometry.Insets) would have incorrectly overridden the package-private method in javafx.scene.layout.Region
    05-13 16:07:15.067: I/System.out(18033): max rectangle texture cell size = 62
    05-13 16:07:15.084: I/System.out(18033): wrap rectangle texture = 2 x 2
    05-13 16:07:15.087: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: AlphaTexture_Color.frag
    05-13 16:07:15.106: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: Texture_Color.frag
    05-13 16:07:15.122: I/System.out(18033): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_20
    05-13 16:07:15.133: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: Solid_TextureRGB.frag
    05-13 16:07:15.150: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: FillRoundRect_Color.frag
    05-13 16:07:15.154: I/System.out(18033): Loading Prism common native library ...
    05-13 16:07:15.163: I/System.out(18033):    succeeded.
    05-13 16:07:15.177: I/System.out(18033): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_28


Q: "Error calling Driver#connect" using Hibernate This is my cfg.xml file:

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=hiber;</property>
    <property name="connection.username">Costi-PC\Costi</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <!-- Names the annotated entity class -->
    <mapping class="model.User" />

User class and Main class:
@Entity
    public class User {

        @Id
        private int userId;
        private String userName;

        public int getUserId() {..}
        public void setUserId(int userId) {..}
        public String getUserName() {..}
        public void setUserName(String userName) {..}

    }

    public class Main {

        public static void main(String[] args) {
           User user = new User();
           user.setUserId(1);
           user.setUserName("Costi");

           AnnotationConfiguration configuration = new AnnotationConfiguration();
           configuration.configure();

           SessionFactory sessionFactory = configuration.buildSessionFactory();

           Session session = sessionFactory.openSession();
           session.beginTransaction();
           session.save(user);
           session.getTransaction().commit();
           session.close();

           sessionFactory.close();

}

When I run the program i get this error:
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:132)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:118)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
    at main.Main.main(Main.java:23)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
    ... 14 more

I'm using sql server 2008.
I tried different types of cfg configuration  but none seems to work.
I believe the problem is from connection.url. I tried to change the port (1433) but nothing.
Can anyone tell what's the problem ?

A: I have Faced Same issue just i have changed the Version on mysql  server connector than works fine
    <!-- commented as it was not make to connect
       <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.34</version>
       </dependency>
   -->

added latest version of mysql connector
   <!-- added latest version of mysql connector -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.18</version>
            </dependency>

A: I know this post is almost 2 years old, but for me the questions gave me, for me, the right answer. And because people with the same question are getting this post from Google. I thought, lets add my story.
Same thing, same problem. And for me the answer was that SQL Server didn't accept connections from the outside. The tcp/ip network client configuration is standard disabled.
So it was for me a hint in the right direction.

A: I changed the version of MySql like,
From 5.1.8
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.8</version>
    </dependency>

To 8.0.19
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
    </dependency>

It works for me.
Thank you.

A: Use This with all Permission of DB
 <property name="hibernate.connection.url">jdbc:mysql://ip:3306/dbname</property><property name="hibernate.connection.username">*******</property>
     <property name="hibernate.connection.password">*******</property>

A: Try going to the command line and see if sqlserver is indeed listening to that port. On windows this would be the command:
netstat -nao | findstr 1433

Then see if the PID is Sql Server as expected in the windows (Ctr+Alt+Delete) process list.
If the server is running, try to connect to it using a SQL client GUI, see here for examples.  When you can connect to the database from an external client successfully, try again from the Java program.
Try to see also if your local firewall settings to see if the firewall is the cause for the error, although by default firewalls do not block  localhost - have a look at this answer.

A: Check you Sid in

hibernate.cfg.xml file

For Oracle Express Edition:
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>

For Oracle Enterprise Edition:
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>

A: the error is due to AnnotationConfiguration and making session by it.
you can try this solution:
@Autowired
SessionFactory sessionFactory;
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(ce);

A: I also face same problem due to some dependency issue. i solve my problem to change sql depenedency which is compatible to my current version of sql server in pom.xml file.

A: I had a same error when migrating from jTDS1.2.8 to mssql-jdbc and for me it helped removing the port number and specifying the named instance in the connection URL within hibernate.cfg.xml
From:
<property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME:1433;databaseName=mydbname;instanceName=MYINSTANCENAME;</property>

To:
  <property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME;instanceName=MYINSTANCENAME;databaseName=mydbname;</property>

Reference: https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-2017
When using Named and Multiple SQL Server Instances, to use a JDBC URL property, do the following:
jdbc:sqlserver://localhost;instanceName=instance1;integratedSecurity=true;<more properties as required>;

A: if you are using a virtual server or server that is not updated the time zone should update it.
SQL CONSOLE:
SET GLOBAL time_zone = '+3:00';

A: Wrong username or a password in a config hibernate file "hibernate.cfg.xml"

A: Please make sure that the database with which you are trying to connect has already been created in the database with the same name.

A: If you're using Hibernate 4, try switching to Hibernate 5.
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.10.Final</version>
</dependency>

This helped me resolve the error.


Q: Preloading entities with EF4 I have a bunch of classificators which will be used quite often. I wan't to preload those entities when my program starts so that I wouldn't have to do it later when any object references them.
How can this be done in EF4?

A: There's a long-ish walkthrough here:
How to Cache Entity Framework Reference Data
But profile first. Writing good projections may be faster than materializing entire entities with cached references. Even loading single referenced objects is quite fast. Don't "optimize" stuff which isn't slow.


Q: Redirecting requests over 8443 to 443 One of our applications was previously configured to serve SSL from tomcat over port 8443. We're migrating this application to a new environment and switching to using nginx to handle SSL termination rather than tomcat (which will operate over 8080). I would like the ability for folks to be able to connect to the new environment over 8443 but get redirected to 443 (to support anyone's old bookmarks or links).
Currently have rulesets to redirect 80 to 443, and a full ssl_certificate set defined for listening on 443, but no luck trying a variety of methods to listen on 8443 and redirect to itself over 443.
Any suggestions?

A: Just define a separate server for port 8443, and do a redirect from there.  You'd obviously still have to have a proper certificate for your 8443 server, too.
server {
  listen 8443 ssl;
  server_name example.com;
  ssl_...;
  return 301 https://example.com$request_uri;
}


Q: Python hashlib: TypeError: object supporting the buffer API required I am writing a client/server program for class which allows the client to send messages to the server using a variety of different encryption techniques.  Right now, I'm in the middle of implementing symmetric encryption, and the server is throwing me an error when I attempt to hash the public key that it receives from the client during the initial key distribution.  I am not very familiar with these libraries so I'm not quite sure what the cause of this error is.
My server code:
from Crypto.Random import *
from Crypto.PublicKey import RSA
import hashlib

import socket

s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))

c = None
addr = None

s.listen(5)
while True:
   c, addr = s.accept()
   print ('Got connection from', addr)
   break
c.send('You have connected to the server.\nPlease select one of the following communication options by entering the corresponding number.\n1. Public Key Encryption\n2. Symmetric Key Encryption\n3. Digital Signature\n4. Hash'.encode('ascii'))
#receive user option, this will get used in code I add in later
option = c.recv(1024).decode()
#receive and process the public key
pKey = RSA.importKey(c.recv(2048).decode())
#receive the original digest
digest = c.recv(2048).decode()
#hash the received key
hash_object = hashlib.sha1(pKey)
newDigest = hash_object.hexdigest()

if newDigest == digest:
    print("Success")
else:
    print("Failure")

My client code:
from Crypto import Random
from Crypto.PublicKey import RSA
import hashlib
import socket

s = socket.socket()
host = socket.gethostname()
port = 12345
inLoop = True

s.connect((host, port))
print(s.recv(1024).decode())
while(True):
    option = input("Select an option: ")
    print(option)
    s.send(option.encode())
    if (option == '1'):
        #Begin handshake
        random = Random.new().read
        key = RSA.generate(1024,random)
        pKey = key.publickey().exportKey()
        hash_object = hashlib.sha1(pKey)
        hex_digest = hash_object.hexdigest()
        #send public key
        s.send(pKey)
        #send digest
        s.send(hex_digest.encode())

    elif(option == 2):
        while(inLoop == True):
            ""
    elif(option == 3):
        while(inLoop == True):
            ""
    elif(option == 4):
        while(inLoop == True):
            ""
    else:
        print("Please enter a valid option.")

s.close()

Right now a great deal of this is unfinished, but the specific problem I am having is that the client creates a public RSA key, and hashes it, and sends the public key and the hex_digest to the server.  The server receives the public key and decodes it into a string, and then turns it into an RSA key, but hashlib gives me an error once I attempt to hash the key.  When the server reaches the line hash_object = hashlib.sha1(pKey), I receive an error: TypeError: object supporting the buffer API required
I am not sure what this means; I've done a lot of research.  I do not know how to fix this, but for some reason the server will not hash the key.

A: I'm an idiot.  I was doing hash_object = hashlib.sha1(pKey), but pKey is an RSA key, not a string, so I needed to do hash_object = hashlib.sha1(pKey.exportKey()) instead.


Q: Asp.Net Core Web APi and Azure AD auth I have to create a web app with these kinds of requirements:

*

*SPA (Angular 9)

*SPA call to Web API (Asp.net core 3.1)

*I have to use the Azure AD for
the authentication (I created the tenant)

*I have to use Microsoft Graph API

I read different guides and studied the examples at the link
azure ad auth samples
but they do not cover my requirements.
I read this guide a web api that calls a web api that use a desktop application but after changing the code i receive the 401 unouthorized error.
Can anyone help me?
P.S. : Due unsuitable examples, i currently no have exutable code
Thanks a lot

A: You can check the MSAL For Angular document for how to authenticate user and acquire access token  . And this code sample is for Angular 9 .
If you want to directly call Microsfot Graph in Angular application , you can directly acquire Microsoft Graph's scopes as the document show , MSAL will help acquiring access token for Microsoft Graph . If you want to call Microsoft Graph from web api application , propagate the delegated user identity and permissions , you can use OAuth 2.0 On-Behalf-Of flow and follow the code sample as your shown , and use fiddler or developer tools to trace the requests and troubleshoot the 401 problem .


Q: When to use lib.es2015.d.ts vs @types/core-js? It seems lib.es2015.d.ts that ships with the Typescript compiler conflicts with the @types/core-js package if they are both being referenced.
This post indicates that the solution is either:

*

*Change es6 to es5 in compilerOptions's lib property. This way TypeScript won’t include ES6 type definitions.

*Remove core-js from node_modules. This way TypeScript will use only its internal ES6 type definitions.

What I don't understand is why does @types/core-js then even exist, and when is it useful, since the compiler already ships with these definitions?


Q: How do EDMFunction work? We had a developer who attempted to filter on a numeric ID property using a string:
var student = (from s in dbStudents
        where s.StudentId.ToString() == "2"
        select s).FirstOrDefault();

This won't work, as ToString() cannot be translated into SQL by the EF Provider.
One solution was provided works, but I honestly am unclear about why it works:
[EdmFunction("SqlServer", "STR")]
public static string ConvertToString(double? number)
{
   return number.HasValue ? number.ToString() : null;
}

And the query now looks like:
var student = (from s in Students
        where ConvertToString((double) s.LanguageId).Trim() == "2"
        select s).FirstOrDefault();

My understanding is this query should be building up an expression tree, but it appears that we have a CLR method being executed in the middle? I had thought that we could only use methods where the provider understood how it could be translated into SQL.
The SQL looks right, can anyone tell me how we got from:
return number.HasValue ? number.ToString() : null;

to
SELECT TOP (1)
[Extent1].[StudentId] AS [StudentId],
[Extent1].[Name] AS [Name]
FROM [dbo].[Student] AS [Extent1]
WHERE N'2' = (LTRIM(RTRIM(STR( CAST( [Extent1].[StudentId] AS float)))))

A: The Entity Framework uses only the information in the attribute to convert the method call to SQL. The implementation is not used in this case.

A: The EdmFunction attribute calls the specified method in SQL. The implementation you have in C# will be ignored. So in your case STR method is called at SQL end.
You can have your method as:
[EdmFunction("SqlServer", "STR")]
public static string ConvertToString(double? number)
{
   throw new NotSupportedException("Direct calls not supported");
}

and still it would work.
See: EDM and Store functions exposed in LINQ

How it works
When a method with the EdmFunction attribute is detected within a LINQ
  query expression, its treatment is identical to that of a function
  within an Entity-SQL query. Overload resolution is performed with
  respect to the EDM types (not CLR types) of the function arguments.
  Ambiguous overloads, missing functions or lack of overloads result in
  an exception. In addition, the return type of the method must be
  validated. If the CLR return type does not have an implicit cast to
  the appropriate EDM type, the translation will fail.

As a side note, you can also use SqlFunctions.StringConvert like:
var student = (from s in Students
        where  SqlFunctions.StringConvert((double) s.LanguageId)).Trim() == "2"
        select s).FirstOrDefault();


Q: unable to itherate through the array perl I have this perl script:
my %perMpPerMercHash;

foreach my $sheet () {   #proper ranges specified
    foreach my $row ( ) {    #proper ranges specified
        #required variables declared.
        push(@{$perMpPerMercHash{join("-", $mercId, $mpId)}}, $mSku);
    }
}

#Finally 'perMpPerMercHash' will be a hash of array`
foreach my $perMpPerMerc ( keys %perMpPerMercHash ) {
    &genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
}

sub genFile {
    my ( $outFileName, @skuArr ) = @_;
    my $output = new IO::File(">$outFileName");
    my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
 #mpId is generated.
    &prepareMessage($writer, $mpId, @skuArr);
}

sub prepareMessage {
    my ( $writer,  $mpId, @skuArr ) = @_;
    my $count = 1;
    print Dumper \@skuArr;    #Printing correctly, 8-10 values.
    foreach my $sku ( @skuArr ) {   #not iterating.
        print "loop run" , $sku, "\n";   #printed only once.
    }
}

Can somebody please help why this is happening. I am new to perl and could not understand this anomaly.
EDIT:
output of Dumper:
$VAR1 = [
          'A',
          'B',
          'C',
        ];

A: When you do
&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});

You're passing a reference to an array.
So in
sub genFile {
    my ( $outFileName, @skuArr ) = @_;

You have to do :
sub genFile {
    my ( $outFileName, $skuArr ) = @_;

and then use @$skuArr.
Have a look at references
The modified genFile sub will be:
sub genFile {
    my ( $outFileName, $skuArr ) = @_;
    my $output = new IO::File(">$outFileName");
    my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
 #mpId is generated.
    &prepareMessage($writer, $mpId, @$skuArr);
}

And the other sub don't need to be modified.
Or you can pass always skuArr  by reference:
&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
...
sub genFile {
    my ( $outFileName, $skuArr ) = @_;
    ...
    &prepareMessage($writer, $mpId, $skuArr);
}

sub prepareMessage {
    my ( $writer,  $mpId, $skuArr ) = @_;
    my $count = 1;
    print Dumper $skuArr;
    foreach my $sku ( @$skuArr ) {
        print "loop run" , $sku, "\n";
    }
}


Q: mootools accordion styling problem I just built my first mootools accordion, but it is adding a lot of inline styles which is just ruining my UI. I can set up a inline style with !important keyword but it will just make my css maintenance a nightmare. any ideas how to get rid of the inline styles
It is just this
<script language="javascript">
   window.addEvent('domready', function() {

 //create our Accordion instance
 var myAccordion = new Accordion($('accordion'), 'div.subTreeHeader', 'div.accordionElement', {
 opacity: false, fixedHeight:400

 });

});

</script>

A: Well this is quite old question, I answer it because I run to it when looking for the same problem.
Actually Mootools Acordion adds this much inline CSS:
padding-top: 0px; border-top-style:
none; padding-bottom: 0px; border-bottom-style: none;
overflow: hidden; opacity: 1;

The solutions I found for this are fixes that have to be applied after calling the new Fx.Accordion. I also agree that feels wrong to fix with !important CSS fixing. So I also looked for other options.
Option 1, set back the css as you want:
$$('.acordion3_content').setStyles({
    border: '3px solid #0F0',
    'overflow-y': 'auto',
});

Option 2, create one more div inside or outside it. I did this option to get a scroll div I could have events connected to. Like this I could have a scroll inside the accordion's content without it being affected of Fx.Acordion's CSS.


Q: Updating the Jpanel of a class After some advice on using jpanel - I'm new to java and playing around with the GUI elements.
Bascially what I'm curious about is if I can set up a Jpanel in one class, then somehow add labels etc to the that container, but from another class.
Is this possible ? or do i have to set the entire GUI up in one class, but then I guess I would have the same issue, if I wanted to update those fields I had set up in the main class from another class?
Apologies I don't really have any code that's usefull to demostrate here - I'm just trying to get the idea going, working out if its possible before I go ahead. And I'm not even sure if this is possible. Any advice would be greatly appreciated.
Thanks

A: As long as you have a reference to the JPanel, you can add whatever GUI-element you want, by calling add(JComponent comp) on the JPanel.
So, you can do something like this:
class Panel extends JPanel{

    ...

}

class Main{

    public Main(JPanel thePanel){
        thePanel.add(new JButton("Hello"));
    }
}

Was this what you were looking for?
You can also update the fields added to the panel from another class, if you have a public  accessor-method set up, in the class. So in your panel class, you have a method:
public JButton getButton(){
    return button;
}

Then you can access the button from whatever class with a reference to your panel class, like this:
panel.getButton().setText("Some text");

Note that the button could just as well be public, then you could simply call the method directly: panel.button.setText("Some text"); but this is not considered good code, as it violates some general good OOP practices, not relevant to mention here.


Q: F# Split list into sublists based on comparison of adjacent elements I've found this question on hubFS, but that handles a splitting criteria based on individual elements. I'd like to split based on a comparison of adjacent elements, so the type would look like this:
val split = ('T -> 'T -> bool) -> 'T list -> 'T list list

Currently, I am trying to start from Don's imperative solution, but I can't work out how to initialize and use a 'prev' value for comparison. Is fold a better way to go?
//Don's solution for single criteria, copied from hubFS
let SequencesStartingWith n (s:seq<_>) =
    seq { use ie = s.GetEnumerator()
          let acc = new ResizeArray<_>()
          while ie.MoveNext() do
             let x = ie.Current
             if x = n && acc.Count > 0 then
                 yield ResizeArray.to_list acc
                 acc.Clear()
             acc.Add x
          if acc.Count > 0 then
              yield  ResizeArray.to_list acc }

A: This is an interesting problem! I needed to implement exactly this in C# just recently for my article about grouping (because the type signature of the function is pretty similar to groupBy, so it can be used in LINQ query as the group by clause). The C# implementation was quite ugly though.
Anyway, there must be a way to express this function using some simple primitives. It just seems that the F# library doesn't provide any functions that fit for this purpose. I was able to come up with two functions that seem to be generally useful and can be combined together to solve this problem, so here they are:
// Splits a list into two lists using the specified function
// The list is split between two elements for which 'f' returns 'true'
let splitAt f list =
  let rec splitAtAux acc list =
    match list with
    | x::y::ys when f x y -> List.rev (x::acc), y::ys
    | x::xs -> splitAtAux (x::acc) xs
    | [] -> (List.rev acc), []
  splitAtAux [] list

val splitAt : ('a -> 'a -> bool) -> 'a list -> 'a list * 'a list

This is similar to what we want to achieve, but it splits the list only in two pieces (which is a simpler case than splitting the list multiple times). Then we'll need to repeat this operation, which can be done using this function:
// Repeatedly uses 'f' to take several elements of the input list and
// aggregate them into value of type 'b until the remaining list
// (second value returned by 'f') is empty
let foldUntilEmpty f list =
  let rec foldUntilEmptyAux acc list =
    match f list with
    | l, [] -> l::acc |> List.rev
    | l, rest -> foldUntilEmptyAux (l::acc) rest
  foldUntilEmptyAux [] list

val foldUntilEmpty : ('a list -> 'b * 'a list) -> 'a list -> 'b list

Now we can repeatedly apply splitAt (with some predicate specified as the first argument) on the input list using foldUntilEmpty, which gives us the function we wanted:
let splitAtEvery f list = foldUntilEmpty (splitAt f) list

splitAtEvery (<>) [ 1; 1; 1; 2; 2; 3; 3; 3; 3 ];;
val it : int list list = [[1; 1; 1]; [2; 2]; [3; 3; 3; 3]]

I think that the last step is really nice :-). The first two functions are quite straightforward and may be useful for other things, although they are not as general as functions from the F# core library.

A: How about:
let splitOn test lst =
    List.foldBack (fun el lst ->
            match lst with
            | [] -> [[el]]
            | (x::xs)::ys when not (test el x) -> (el::(x::xs))::ys
            | _ -> [el]::lst
         )  lst []

the foldBack removes the need to reverse the list.

A: Having thought about this a bit further, I've come up with this solution. I'm not sure that it's very readable (except for me who wrote it).
UPDATE Building on the better matching example in Tomas's answer, here's an improved version which removes the 'code smell' (see edits for previous version), and is slightly more readable (says me).
It still breaks on this (splitOn (<>) []), because of the dreaded value restriction error, but I think that might be inevitable.
(EDIT: Corrected bug spotted by Johan Kullbom, now works correctly for [1;1;2;3]. The problem was eating two elements directly in the first match, this meant I missed a comparison/check.)
//Function for splitting list into list of lists based on comparison of adjacent elements
let splitOn test lst =
    let rec loop lst inner outer = //inner=current sublist, outer=list of sublists
        match lst with
        | x::y::ys when test x y -> loop (y::ys) [] (List.rev (x::inner) :: outer)
        | x::xs ->                  loop xs (x::inner) outer
        | _ ->                      List.rev ((List.rev inner) :: outer)
    loop lst [] []

splitOn (fun a b -> b - a > 1) [1]
> val it : [[1]]

splitOn (fun a b -> b - a > 1) [1;3]
> val it : [[1]; [3]]

splitOn (fun a b -> b - a > 1) [1;2;3;4;6;7;8;9;11;12;13;14;15;16;18;19;21]
> val it : [[1; 2; 3; 4]; [6; 7; 8; 9]; [11; 12; 13; 14; 15; 16]; [18; 19]; [21]]

Any thoughts on this, or the partial solution in my question?

A: "adjacent" immediately makes me think of Seq.pairwise.
let splitAt pred xs =
    if Seq.isEmpty xs then
        []
    else
        xs
        |> Seq.pairwise
        |> Seq.fold (fun (curr :: rest as lists) (i, j) -> if pred i j then [j] :: lists else (j :: curr) :: rest) [[Seq.head xs]]
        |> List.rev
        |> List.map List.rev

Example:
[1;1;2;3;3;3;2;1;2;2]
|> splitAt (>)

Gives:
[[1; 1; 2; 3; 3; 3]; [2]; [1; 2; 2]]

A: I would prefer using List.fold over explicit recursion.
let splitOn pred = function
    | []       -> []
    | hd :: tl ->
        let (outer, inner, _) =
            List.fold (fun (outer, inner, prev) curr ->
                            if pred prev curr
                            then (List.rev inner) :: outer, [curr], curr
                            else outer, curr :: inner, curr)
                      ([], [hd], hd)
                      tl
        List.rev ((List.rev inner) :: outer)

A: I like answers provided by @Joh and @Johan as these solutions seem to be most idiomatic and straightforward. I also like an idea suggested by @Shooton. However, each solution had their own drawbacks.
I was trying to avoid:

*

*Reversing lists

*Unsplitting and joining back the temporary results

*Complex match instructions

*Even Seq.pairwise appeared to be redundant

*Checking list for emptiness can be removed in cost of using Unchecked.defaultof<_> below

Here's my version:
let splitWhen f src =
    if List.isEmpty src then [] else
    src
    |> List.foldBack
        (fun el (prev, current, rest) ->
            if f el prev
            then el , [el]          , current :: rest
            else el , el :: current , rest
        )
        <| (List.head src, [], [])               // Initial value does not matter, dislike using Unchecked.defaultof<_>
    |> fun (_, current, rest) -> current :: rest // Merge temporary lists
    |> List.filter (not << List.isEmpty)         // Drop tail element


Q: invoking functions defined by flet in another function I have a collection of functions defined in foo that I want to also want to use in bar. I have these functions defined in foo because I want foo to be self-contained -- otherwise I know that I can define these functions externally (globally) to be accessible to foo and bar and other functions, or define both foo and bar within a labels construct in which these functions are defined only for foo and bar. In any case, I would like for foo to be distributable without the external functions or the labels structure. Hence the challenge.
This is what I have so far (I am using Emacs Lisp in this case), but what I have now ends up defining the local functions in foo globally when I invoke bar. Any suggestions how to define local variables/functions in bar "on the fly"?
(defun foo (x)
  (flet ((addone (x) (1+ x))
     (addtwo (x) (+ 2 x)))
    (addtwo x)))

(defun bar (x)
  (let* ((fnlist (car (cdaddr (symbol-function 'foo))))
     (nfn (length fnlist))
     (ifn nil)
     (bar-body '(addone x))
     (i 0))
    (eval (append
       ;; local symbol names
       ;; to which function definitions will be set
       (list 'let (mapcar 'car fnlist))
       ;; set function definitions
       (list '(while (< i nfn)
            (setq ifn (nth i fnlist))
            (eval `(fset ',(car ifn) ,(append (list 'lambda) (cdr ifn))))
            (setq i (1+ i))))
       ;; function invocation
       (list bar-body)))))

Function application:
(foo 1) ;;=> 3

(bar 1) ;;=> 2

(addone 1) ;;=> 2 ?should not be defined outside of bar?

A: This isn't self-contained, so it's not really an answer; but it's different to the other options you mentioned, so I'll add it anyway.
(defmacro with-foo-functions (&rest forms)
  `(flet ((addone (x) (1+ x))
          (addtwo (x) (+ 2 x)))
     ,@forms))

(defun foo (x)
  (with-foo-functions
   (addtwo x)))

(defun bar (x)
  (with-foo-functions
   (addone x)))

A: Emacs Lisp has dynamic binding. This is different from the lexical binding used by pretty much all other Lisps. For example, if you try to do the following in Common Lisp, you will get an error message saying that FOO is not defined:
(defun bar ()
  (foo 10))

(flet ((foo (x) (1+ x)))
  (bar))

In Emacs Lisp, however, since FOO is dynamically bound this will return 11 as the binding of FOO is available in BAR.
Emacs Lisp does not provide lexical bindings for functions, so in order to achieve the same thing in Emacs Lisp you'll have to fake it by binding a lambda to a lexical variable and then use a macro to hide the FUNCALL:
(lexical-let ((foo #'(lambda (x) (1+ x))))
  (macrolet ((foo (x) `(funcall foo ,x)))
    (foo 10)))

The other answer to this question suggests the use of a macro instead of the flet. This works, but it results in unnecessary code duplication. My solution prevents this at the expense of having to either write the macrolet part, or using funcall every time you want to call the function. One could write a macro to wrap all of this inside a lexical flet version if this is something that is needed often.


Q: Why does HashSet not implement ICollection? I am going to write a library to traverse an object graph (like some kind of serialization).
You will need to judge if an object is a collection in the traverse, so the ICollection came out of my mind. (string has also implemented IEnumerable)
But it is really weird that almost all containers in Collections have implemented ICollection except HashSet only implemented ICollection<T>...
I have checked out almost all common containers in System.Collections namespace:
ArrayList : IList, ICollection, IEnumerable, ICloneable
BitArray : ICollection, IEnumerable, ICloneable
Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable
Queue : ICollection, IEnumerable, ICloneable
SortedList : IDictionary, ICollection, IEnumerable, ICloneable
Stack : ICollection, IEnumerable, ICloneable
Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, IDeserializationCallback
HashSet<T> : ISerializable, IDeserializationCallback, ISet<T>, ICollection<T>, IEnumerable<T>, IEnumerable
LinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
Queue<T> : IEnumerable<T>, ICollection, IEnumerable
SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
SortedSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
Stack<T> : IEnumerable<T>, ICollection, IEnumerable

Is this a bug? Or there are some reason behind?

A: ICollection isn't anywhere near as useful now as it was with .NET 1.1 when there was no ICollection<T> offering greater type safety. There's very little one can usefully do with ICollection that one can't do with ICollection<T>, often with greater efficiency and/or type safety, especially if one writes generic methods for those cases where one might want to do something with collections of different element types.
This though begs the question of why the likes of List<T> did implement ICollection. But when List<T> was introduced with .NET 2.0 all legacy code was using ICollection and ArrayList, not ICollection<T> and List<T>. Upgrading code to use List<T> rather than ArrayList can be a pain, especially if it means having to either immediately change all uses of ICollection it would hit to use ICollection<T> or, even worse, double up because a method was being hit with the List<T> that was also being hit with other non-generic collections and so versions of the method would be needed for each. Implementing ICollection eased the upgrade path by allowing people to be more piecemeal in how they took advantage of generic collections.
When HashSet<T> came out generics had been in use for three years already, and there was not a previous non-generic hash-set type provided by the framework, so there was less of an upgrade pain, and hence less of a motivation for supporting ICollection.


Q: Why mangled names found within an exe? I have an MS C/C++ statically linked release exe (no debug info on it), that does not export any symbol, but when browsing it with a hex viewer I see things like
.?AVElxInterface@@
.?AV?$CBufferRefT@H@@
.?AV?$CBufferT@H@@
.?AV?$CBufferRefT@PAVElxInterface@@@@

of course they are the mangled names of certain classes/members provided by the internal C++ modules.
why are they there? how can avoid exposing them?

A: Personally, I don't see any reason to over-hide this data, as it supplies no clue to people who view it on how to utilize these symbols to do something "bad". However, if that's really a huge problem for you, i.e. you are afraid of being sort of reverse-engineered somehow, then you may opt to code obfuscation. For example, Semantic Designs offer a product for these purposes and claim that it's of high quality. I've never had a chance to try that stuff myself. Keep in mind that it's commercial.


Q: EF Core: Column with ValueGeneratedOnAdd trows "Cannot insert explicit value for identity column..." I have ASP.NET MVC 5 application that uses Entity Framework 6.2. This app creates some records in MS SQL server.
I have to process this records in AWS lambda function. For this purpose, I created c# .NET Core v2.0 lambda function. There I generate models from existed DB as described in the next article - Getting Started with EF Core on ASP.NET Core with an Existing Database.
Generated models look like:
public partial class Request
{
    public int EntityId { get; set; }
    public Result Result { get; set; }
}
public partial class Result
{
    public int EntityId { get; set; }
    public Request Entity { get; set; }
}

And OnModelCreating:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Request>(entity =>
    {
        entity.HasKey(e => e.EntityId);
        entity.ToTable("Request", "mySchema");
    });

    modelBuilder.Entity<Result>(entity =>
    {
        entity.HasKey(e => e.EntityId);
        entity.ToTable("Result", "mySchema");
        entity.HasIndex(e => e.EntityId).HasName("IX_EntityId");
        entity.Property(e => e.EntityId).ValueGeneratedOnAdd();
        entity.HasOne(d => d.Entity)
            .WithOne(p => p.Result)
            .HasForeignKey<Result>(d => d.EntityId)
            .OnDelete(DeleteBehavior.ClientSetNull)
            .HasConstraintName("FK_mySchema.Result_mySchema.Request_EntityId");
    });
}

In the lambda function, I am processing a request and  setting result:
using (var db = new DataContext(connection))
{
    var request = db.Request.First();
    request.Result = new Result();
    db.SaveChanges();
}

On the save operation I got the exception:
Cannot insert explicit value for identity column in table 'Result' when IDENTITY_INSERT is set to OFF.
I checked different way to solve this issue. But there are already set ValueGeneratedOnAdd function in model creating method.
Also, I tried to add [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to Result.EntityId  - without any success.
What did I miss in my implementation?

A: You are trying to initialize request.Result with new Result() which has no values.  That may cause this error.


Q: Win32 ToolTip disappears never to re-appear with Commctl 6 I'm creating a ToolTip window and adding tools to it using the flags
TTF_IDISHWND | TTF_SUBCLASS. (c++, win32)
I have a manifest file such that my program uses the new WindowsXP themes
(comctrl32 version 6).
When I hover over a registered tool, the tip appears.
Good.
When I click the mouse, the tip disappears.
Ok.
However, moving away from the tool and back
again does not make the tip re-appear. I need to hover over a different tool
and then come back to my tool to get the tip to come back.
When I remove my manifest file (to use the older non-XP comctrl32), the
problem goes away.
After doing some experimentation, I discovered the following differences
between ToolTips in Comctl32 version 5 (old) and Comctl32 version 6 (new):

*

*New TTF_TRANSPARENT ToolTips (when used In-Place) actually return
HTCLIENT from WM_NCITTEST if a mouse button is down, thus getting
WM_LBUTTONDOWN and stealing focus for a moment before vanishing. This causes
the application's border to flash.

*Old TTF_TRANSPARENT ToolTips always return HTTRANSPARENT from WM_NCHITTEST,
and thus never get WM_LBUTTONDOWN themselves and never steal focus. (This seems to be just aesthetic, but may impact the next point...)

*New ToolTips seem not to get WM_TIMER events after a mouse-click, and
only resume getting (a bunch of) timer events after being de-activated and
re-activated. Thus, they do not re-display their tip window after a mouse
click and release.

*Old ToolTips get a WM_TIMER message as soon as the mouse is moved again
after click/release, so they are ready to re-display their tip.
Thus, as a comctl32 workaround, I had to:

*

*subclass the TOOLTIPS_CLASS window and always return HTTRANSPARENT from
WM_NCHITTEST if the tool asked for transparency.

*avoid using TTF_SUBCLASS and rather process the mouse messages myself so
I could de-activate/re-activate upon receiving WM_xBUTTONUP.
I assume that the change in internal behavior was to accommodate the new "clickable" features in ToolTips like hyperlinks, but the hover behavior appears to be thus broken.
Does anyone know of a better solution than my subclass workaround? Am I missing some other point?

A: You're not the only one who has hit compatablity issues with tooltips between these DLLS.
I too have had nothing but trouble with the new tooltips in the themable common controls. We have already been monkeying with mouse messages and active/deactivating the tips before adding the manifest and theming our application - so it sounds like what your doing isn't too crazy.
We're still living with problems with TTN_NEEDTEXT messages being send constantly as the mouse moves (not just when hovering), positioning problems with large tips (maybe not something new), and odd unicode messages being sent instead of the ANSI versions (which I plan to post as a question at some point).

A: I don't know, but this sounds like a really "hard" problem (in the sense that all real-world) problems are really hard. I bet the underlying problem is something to do with the setting of the focus. Windows that manually do that are evil and generally suffer from all manner of bugs.


Q: Can't import modules I've searched for this problem and tried different solutions but can't fix it.
In my Django project I have different apps and a non-app directory called 'testing_utils' with modules which serve for a testing purposes. In particular I want to import all available models to file dummy_factory.py. However when I simply import modules from my apps like so:
from abc import ABC
from datetime import date
from users.models import User

I get the error message

ModuleNotFoundError: No module named 'users'

Which is strange since I definetley can import models to some_app.views.py and access them.
Here's an example of my project's directory:
/home/user/dev/project/
▸ project/
▾ testing_utils/
    dummy_factory.py
▾ users/
  ▸ __pycache__/
  ▸ migrations/
  ▸ templates/
  ▸ tests/
    __init__.py
    admin.py
    apps.py
    models.py
    views.py
  manage.py*

A: /home/user/dev/project/ needs to be in your PYTHONPATH to be able to be imported.
If your testing_utils is meant to be local only, the easiest way to accomplish this is to add:
import sys
sys.path.append('/home/user/dev/project/')

... in dummy_factory.py before importing the module.
Solutions that would be more proper would be to install users (how exactly you'd make your package installable depends on your system and what version of Python and Pip you need to support), or to use a virtualenv that automatically adds the right directories to PYTHONPATH.


Q: How to call specific method of portlet.java class rather then overide serveResource method? I want some help in liferay with ajax.
Right now I am calling the ajax method from my view.jsp page to submit some data.
Here is sample code I am using in view.jsp:
<%@ include file="/init.jsp"%>

<portlet:actionURL name="AddTest" var="add1" />
<portlet:resourceURL id="AddTest" var="AddTest"></portlet:resourceURL>

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

    <script type="text/javascript">
    function addToDo(addToDo){
        var todo =document.getElementById('toDo').value;
        $.ajax({
            url :addToDo,
              data: {"todo":todo,"CMD":"addToDo"},
              type: "GET",
              dataType: "text",
            success: function(data) {
                  $("#toDoList").html(data);
            }
        });
    }
    </script>
</head>

<body>

    <portlet:resourceURL var="addToDo" id="addToDo"></portlet:resourceURL>

    <form>
        <input type="text" name="toDo" id="toDo">
        <button name="Add" type="button" onclick="addToDo('<%=addToDo%>')">Add</button>
        <div id="toDoList">

        </div>
    </form>
</body>
</html>

and in my portlet.java class there is one method which is called by this ajax call:
@Override
public void serveResource(ResourceRequest request, ResourceResponse response){
    if(request.getParameter("CMD").equals("addToDo")) {

        System.out.println("came here for add");

        mediatype userToDo = new mediatypeImpl();
        //userToDo.setMediaId(12345);
        try {
            userToDo.setPrimaryKey((CounterLocalServiceUtil.increment()));
            userToDo.setMedianame(request.getParameter("todo"));
            mediatypeLocalServiceUtil.addmediatype(userToDo);
        }
        catch (SystemException e) {
            e.printStackTrace();
        }
    }
}

So my question is that right now it is just caling by default @override method from any ajax class.
But how can I call specific method of portlet.java class on ajax call?
I am new bee in ajax. So please guide me anyways u can.....
I got following error when calling ajax with url of following
<portlet:actionURL name="ajax_AddAdvertise" var="addToDo" windowState="<%= LiferayWindowState.EXCLUSIVE.toString()%>"> </portlet:actionURL>

06:47:03,705 ERROR [http-bio-8080-exec-23][render_portlet_jsp:154] java.lang.NoSuchMethodException: emenu.advertise.portlet.RestaurantPortlet.ajax_AddAdvertise(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
    at java.lang.Class.getMethod(Class.java:1605)

my process action method as follows
 @ProcessAction(name = "ajax_AddAdvertise")
    public void ajax_AddAdvertise(ResourceRequest request,ResourceResponse response) {

}

A:
how can I call specific method of portlet.java class on ajax call?

I think we can't have two different versions of serveResource methods like we do for action methods atleast not with the default implementation.
If you want different methods you would have to go the Spring MVC (@ResourceMapping) way to have that.
Still, you can define different logic in your serveResource method using the resourceId as follows (a full example):
In the JSP:
<portlet:resourceURL var="myResourceURL" id="myResourceID01" />

In the portlet class the serveResource method will contain the following code:
String resourceID = request.getResourceID();

if(resoureID.equals("myResourceID01")) {
   // do myResourceID01 specific logic
} else {
   // else do whatever you want
}

Please keep in mind [Important]
In a portlet you should not use <html>, <head>, <body> tags since portlets generate fragment of the page and not the whole page. Even if it is allowed your resultant page will not be well-formed and will behave differently on different browsers. And moreover the javascript which modifies DOM element will be totally useless.
Edit after this comment:
You can also use ajax with action methods:
People use <portlet:actionURL> with ajax generally for <form>-POST.
For this the actionURL is generated in a slightly different way in your jsp like this:
<portlet:actionURL name="ajax_AddAdvertise" var="addToDo" windowState="<%= LiferayWindowState.EXCLUSIVE.toString()%>">
</portlet:actionURL>

And in your portlet you can have (as in the question):
@ProcessAction(name = "ajax_AddAdvertise")
public void ajax_AddAdvertise(ActionRequest request, ActionResponse response) {
// ... your code
}


Q: Vue Material - Triggering MdTableAlternateHeader visibility I'm looking for a way to trigger the MdAlternateHeader visibility - or maybe to reset its count state.
The app in question has this multi-selection MdTable in which I implemented a delete function per row. But on data erasing, the alternate header still hold the md-selected class set to true (refeered to the deleted and previously selected element/row). As well as the related computed props (isInSelectedItems and isMultipleSelected).
How can I change these state? I was thinking about to trigger a "selected" or "clicked" event on the row befote its deletion, but I'm missing something on the way.
Thanks in advance for the help.

A: Ok, I got it.
I inspected the framework data and noticed this md-selected-value prop, contained in MdTable component. After declaring the prop in my component:
props: [
    // ...
        'mdSelectedValue'
    ],

I update its value through a second array, delegated to track what elements are being selected for deletion:
data: () => ({
    selezionato = []
})

then I listen for any change in selection:
<md-table v-model="cercato" @md-selected="onSelezionato" md-sort="codice" md-sort-order="asc" md-card md-fixed-header :md-selected-value="selezionato">

In my delete function, after every deletion I reset the the new selezionato value, in order to disable the alternate header:
this.selezionato = []

That's it.


Q: Item not showing in list view after added to database After I add the items in database they show only after I restart the app. How to fix this? I have tried using notifyDataSetChanged() but not sure if i did good.
Fragment showing ListView and Button which calls Add Item Activity:
    @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v =inflater.inflate(R.layout.tab_1,container,false);

    Button button = (Button)v.findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), NewData.class);
            startActivityForResult(intent, 0);}});

    listView = (ListView)v.findViewById(R.id.listView);
    listDataAdapter = new ListDataAdapter(getActivity().getApplicationContext(),R.layout.row_layout);
    listView.setAdapter(listDataAdapter);

    userDbHelper = new UserDbHelper (getActivity().getApplicationContext());
    sqLiteDatabase = userDbHelper.getReadableDatabase();
    cursor = userDbHelper.getInformations(sqLiteDatabase);
    if(cursor.moveToFirst()){
        do {
            String nr1, nr2, nr3;
            nr1 = cursor.getString(0);
            nr2 = cursor.getString(1);
            nr3 = cursor.getString(2);
            DataProvider dataProvider = new DataProvider(nr1, nr2, nr3);
            listDataAdapter.add(dataProvider);}
        while (cursor.moveToNext());}

Add item Activity:
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.additemactivity);
    number_1 = (EditText)findViewById(R.id.number11);
    number_2 = (EditText)findViewById(R.id.number12);
    number_3 = (EditText)findViewById(R.id.number13);

    Button button1=(Button)findViewById(R.id.shtobtn);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String number1 = number_1.getText().toString();
            String number2 = number_2.getText().toString();
            String number3 = number_3.getText().toString();

            userDbHelper = new UserDbHelper(context);
            sqLiteDatabase = userDbHelper.getWritableDatabase();
            userDbHelper.addInformations(number1, number2, number3, sqLiteDatabase);
            Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_SHORT).show();
            userDbHelper.close();
            Intent intent=new Intent();
            setResult(RESULT_OK, intent);
            finish();}});

List Data Adapter:
   @Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    LayoutHandler layoutHandler;
        if (row == null){
            LayoutInflater layoutInflater =(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.row_layout,parent,false);
            layoutHandler = new LayoutHandler();
            layoutHandler.NUMER1=(TextView)row.findViewById(R.id.number11);
            layoutHandler.NUMER2=(TextView)row.findViewById(R.id.number12);
            layoutHandler.NUMER3=(TextView)row.findViewById(R.id.number13);
            row.setTag(layoutHandler);}
    else { layoutHandler = (LayoutHandler)row.getTag();}
    DataProvider dataProvider = (DataProvider)this.getItem(position);
    layoutHandler.NUMER1.setText(dataProvider.getNum1());
    layoutHandler.NUMER2.setText(dataProvider.getNum2());
    layoutHandler.NUMER3.setText(dataProvider.getNum3()); return row;

A: Add listView.notifyDataSetChanged(); after list is updated.

A: Create one public method in adapter class which is notifyDataSetChanged()

A: If you are using SQLite DB then to automatically populated the updated database values into your list view, you should extend your custom adapter with CursorAdapter. Once you fetch data in cursor it will automatically show you the updated values;
    public class CustomAdapter extends CursorAdapter {

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.your_list_item, parent, false);
       // return null;
    }

    @Override
    public Object getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

    }
 }

A: In your Fragment
private SharedPreferences.Editor editor;
private SharedPreferences sharedpreferences;
UpdatingReceiver updatingReceiver;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup  container, @Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context);
    editor = sharedpreferences.edit();
    editor.putString("some unique key", name);
    String name = "Inside";
}
  @Override
protected void onPause() {
    super.onPause();
    editor = sharedpreferences.edit();
    String name = "Outside";
    editor.putString("some unique key", name);
    editor.commit();
}
@Override
protected void onStart() {
    super.onStart();
    updatingReceiver = new UpdatingReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("updating receiver unique key");
    registerReceiver(updatingReceiver, intentFilter);

}

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(updatingReceiver);
}
class UpdatingReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //list all the data
        //set adapter
        //notifyDataSetChanged
    }
}

So you can come to know if you are in inside the fragment or outside the fragment. Based on that you should trigger from your activity.
In your Activity, after you added the code in db just call the receiver based on inside or outside. So it will update immediately.
private SharedPreferences.Editor editor;
private SharedPreferences sharedpreferences;
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
String prefsString = sharedpreferences.getString("some unique key", "");
if (prefsString=="Inside")
{
   Intent broadCast = new Intent();
                broadCast.setAction("updating receiver unique key");
                sendBroadcast(broadCast);
}

A: The solution:
    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {adapter.notifyDataSetChanged();}


Q: Django App - Ajax Auto-complete After 2 Characters and 1s Delay I have this piece of code in my Django app to create simple auto-complete search suggestion box. How do I limit the Ajax to at least 2 characters and how can I add lets say 1sec delay for the Ajax to execute the search query?
$(function(){

$('#search').keyup(function() {

    $.ajax({
        type: "POST",
        url: "/search/",
        data: {
            'search_text' : $('#search').val(),
            'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
        },
        success: searchSuccess,
        dataType: 'html'
    });

});

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}

A: Assuming that #search is probably a text input field, you can add the following code right before your ajax request:
// get the value that the user has typed
var v = $(this).val();
// don\'t go on if less than 3 chars or
// some other key was pressed that did not change the data
if (v.length < 3 || v == $(this).data('prev-val')) return;
// set the old value as the new one
$(this).data('prev-val', v);
// now call ajax

Following a comment in the question, this does not deal with any time delay. A timer could easily be used to trigger the ajax request, and cancel any previous timer before setting a new one. But this would probably make matters more complicated for no good reason.


Q: $.each is looping over each character in my json and displaying undefined i need to loop over the below json but the below code is looping over each character in my json and displaying "undefined": (is there anything wrong with the below json??? Any help is appreciated)
{"news_id":"1","news_title":"News Title One","news_date":"2012-03-20","news_pic":"album-bb[6].jpg","news_desc":"Here goes the news title one Here goes the news title one Here goes the news title one Here goes the news title one.","gallid":"3"}
{"news_id":"2","news_title":"News Title Two","news_date":"2012-04-14","news_pic":"174863_163190093755777_2032987021_q.jpg","news_desc":"News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two.","gallid":"0"}

This is my code which is being fired on click event:
var phpNews;
var NewsObject;

$(document).ready(function () {

    $("#btnNewsPage").click(function()
    {
        $.post("server/news.php",null,function(e){
            NewsObject = e;
            $.mobile.changePage("#NewsPage");
        });
    });

    $('#NewsPage').live('pagebeforeshow',function(event, ui){
        var list;
        $.each(NewsObject, function(k,v){
            list = v.news_title;
        });

        $("#displayNews").html(list);
    });

})

A: Looks like, your NewsObject isn't a JSON object but string. It could happen because JQuery can't guess the response type, so you, probably, need to specify dataType for your $.post request (documentation):
$.post("server/news.php", null, function(e){ ... }, 'json');

P.S. Also your JSON not looks valid, i expect to see something like {'a':'b'}, but you have {'a':'b'} {'c':'d'}.
Updated. Based on the comments below, i would suggest you to use next PHP code for your server/news.php:
<?php

require "../includes/config.php";
require "../includes/h.conn.php";
require "../includes/admin.id.php";

$strSQL = "select * from news where admin_id=" .$admin_id;
$objRS = mysql_query($strSQL);
$News_Obj = array();

while ($row = mysql_fetch_assoc($objRS)) {
    $record = array (
               "news_id" => $row['news_id'],
               "news_title" => $row['news_title'],
               "news_date" => $row['news_date']
    );
    $News_Obj[] = $record;
}

// don't forget to clear after yourself: mysql_free_result, disconnect

header("Content-type: application/json");
echo json_encode($News_Obj);
?>

Also you can use Firebug to see what exactly returns the script and which HTTP or Javascript errors happen when you do a request.


Q: WCF Site Blocked by McAfee, how to unblock without turning off firewall McAfee's firewall was blocking me from using a WCF client I made in C# .NET over a local network until I disabled it.  How can I keep the firewall up and add an exception or something for my stie hosted in IIS?  Like when the firewall is up, navigating to http://mark-pc from the other computers comes up with nothing but if you turn off the firewall it comes up with my locally hosted IIS site (which is what I want).  I dont want to turn off the whole firewall so how can I just let that connection go out?
Even when I allow Port 80 though McAfee, it doesn't work.  They can view it in a browser but trying to ping mark-pc fails.


Q: Xamarin.Forms navigation stack flow I'm trying to work out the correct way of structuring the navigation for my Xamarin.Forms application.
Please note the LoginPage is currently set as the application's MainPage.
The intended (visual) structure is as follows:
CheckPermissionsPage ➜ LoginPage ➜ HomePage
I am following a MVVM structure, so my LoginPageViewModel is displaying a modal of CheckPermissionsPage within it's constructor as so:
await Application.Current.MainPage.Navigation.PushModalAsync(new CheckPermissionsPage());
The idea is that the check permissions page validates the application has permissions to specific services and if it does, the page automatically closes. The user must then login to the application, after which the HomePage is displayed.
How would I structure the LoginPage so that the CheckPermissionsPage modal can be displayed/hidden based on permissions state. Consequently, after a successful login, the HomePage is displayed (without an option to return to the LoginPage). Thanks!

A: I ended up changing the application MainPage to navigate throughout the pages. So my initial application main page is now the CheckPermissionsPage. Should permissions be granted I then run Application.Current.MainPage = new NavigationPage(new LoginPage());. After logging in, the HomePage is displayed with Application.Current.MainPage = new NavigationPage(new HomePage());. This probably isn't the most ideal solution, but it does allow me to prevent back navigation for my LoginPage.


Q: Delaying events in a game loop with Android? If you have a game loop thread in Android that draws to a surfaceview and you require a couple of seconds delay to perform animation, how do you go about doing this?


Q: Control the iterations of triple nested loop in list comprehension, Python I have 2 lists which I need to iterate through:
hits_idx2 = [ 0, 1, 2]
common_b = [ [835,1234,2345] , [223,544] , [423,1234]  ]

in order to produce the following output:

0, 835
  0, 1234
  0, 2345
  1, 223
  1, 544
  2, 423
  2, 1234

I created a nested loop using list comprehensions and a check to see if the element returned at the each iteration if the last element in each sublist, if it not the loop should continue, if it is it should go to the next element of hits_idx2 and iterate through the second sublist in common_b:
for x,y in [(x,y) for x in hits_idx2 for ind in hits_idx2 for y in common_b[ind] if y!=common_b[ind][-1]]:
    print (x,y)

but unfortunately I am getting the following:

0 835
  0 1234
  0 223
  0 423
  1 835
  1 1234
  1 223
  1 423
  2 835
  2 1234
  2 223
  2 423

I am kinda stuck, any help more than welcome. thanks!
I solved it as follows:
for h,y in [ (h,common) for h, common in [(h, common) for h, commons in zip(hits_idx2, common_b) for common in commons] ]:
    print(h,y)


Q: How do I run a single test in Scala? I'm going through the scala labs and I can't seem to figure out how to run a single test.
I run test in sbt and I get 23 failing tests for me to fix. I want to run just the HelloWorldExercise.scala. How would I do this?

A: sbt "testOnly HelloWorldExercise"


Q: Angular2 input data getting lost on button click I have created Angular2 code like this to get the data on button click

             <input #newData [(ngModel)]="data.id" type="text" >
             <select #newCategory [(ngModel)]="i.index" class="input-bars">
              <option *ngFor="let data of field" [value]="data.value">{{data.value}}</option>
            </select>

        <button class="btn btn-success (click)="addData(newData.value, newCategory.value)">ADD</button>

    addData(value, dropValue){

        this.Data[index] = value;
    }

But when the button is clicked the data on the input field is getting lost in ui. How to keep it when the button is clicked and display on the ui as well??

A: I'll hazard a guess that you're working in a form, so add type="button" to the button <button class="btn btn-success" (click)="addData(newData.value)">ADD</button>. That should prevent it from thinking the form is submitting and clearing the data.


Q: reading lines of text in a nonblocking way In a C program I want to read text lines from stdin.
At the same time I want to handle data coming from another file descriptor.
I tried to use poll to wait for any of the two source to become readable and handle them accordingly. However poll needs bare file descriptors and for reading whole lines with something like fgets I need a FILE handle.
I can use fileno or fdopen to "convert" them, but using both in a mixed way does not seem to be a good idea.
Therefore, is there a good way to wait for lines of text without blocking or threading?

A: You can use whatever you want for multiplexing (select(), poll(), epoll_wait()). But you shouldn't read from stdin with fgets() because multiplexing knows nothing about if we've got complete line or no. So it may block in some cases. You should write custom line reading function, that will indicate that there is no complete line yet and return immediately.


Q: Decimal Module in Python Why does this code output 25 although I used the decimal module. I tried it on the calculator and it outputted 26.28.
from decimal import *
getcontext().prec = 2

targetPrice = 40
currentPrice = 56.5
winChance = 0.9
stopLoss = 23
lossChance = 0.1

expectancy =100 * abs(((Decimal(targetPrice) -  Decimal(currentPrice)) / Decimal( currentPrice))) *  Decimal(winChance)
print(expectancy)

A: You're getting inexact results because you're rounding down to two decimal places after every calculation.  Your calculator isn't doing that.
With no rounding.
>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.2920353982300884955752212389')

With rounding:
>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.28')

It only gets worse after that.


Q: Unable to build c++ application using nw-gyp build. Error: error MSB6006: "CL.exe" exited with code -1073741515 I have tried to set up nw-gyp on Windows 8.1 x64 by following the following link:
nw-gyp installation guide
For this I installed:

*

*Python v2.7

*Node v4.2.2 (Setted its path too in environment variable)

*npm v2.14.7

*node-webkit v0.12.3

*Microsoft Visual Studio C++ 2012 for Windows Desktop Express version From Here
after this I installed nw-gyp using the following command.

*

*npm install -g nw-gyp

Now I tried to run the demo app provided here nw-gyp Example
Now I configure the app using command:

*

*nw-gyp configure --target=0.12.3

0.12.3 is my node webkit version. The configuration is successful and I am able to get the build folder. But further when I try to build the addon using command

*

*nw-gyp build

I get the following error
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x64.targets(146,5): error MSB6006: "CL.exe" exited with code -1073741515. [E:\PacificCX\testSecond\build\binding.vcxproj]

Here is the full log:
E:\PacificCX\testSecond>nw-gyp build
gyp info it worked if it ends with ok
gyp info using nw-gyp@0.12.4
gyp info using node@4.2.2 | win32 | x64
(node) child_process: options.customFds option is deprecated. Use options.stdio
instead.
gyp info spawn C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
gyp info spawn args [ 'build/binding.sln',
gyp info spawn args   '/clp:Verbosity=minimal',
gyp info spawn args   '/nologo',
gyp info spawn args   '/p:Configuration=Release;Platform=x64' ]
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppBuild.targets(29
7,5): warning MSB8003: Could not find WindowsSDKDir variable from the registry.
  TargetFrameworkVersion or PlatformToolset may be set to an invalid version nu
mber. [E:\PacificCX\testSecond\build\binding.vcxproj]
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x
64.targets(146,5): error MSB6006: "CL.exe" exited with code -1073741515. [E:\Pa
cificCX\testSecond\build\binding.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Users\kamaldeep.singh\AppData\Roam
ing\npm\node_modules\nw-gyp\lib\build.js:267:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:200:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\kamaldeep.sin
gh\\AppData\\Roaming\\npm\\node_modules\\nw-gyp\\bin\\nw-gyp.js" "build"
gyp ERR! cwd E:\PacificCX\testSecond
gyp ERR! node -v v4.2.2
gyp ERR! nw-gyp -v v0.12.4
gyp ERR! not ok

Someone please help me solve this out. Thanks in advance.
Here is the link to my complete sample program. Download Sample

A: solved this problem by updating Visual Studio 2012.


Q: Getting text after URL in asp.net / URL Rewriting (sort of!) My app is a very simple "one page" type app-
It has Default.aspx
I'm basically trying to get, for example:

www.myappurl.com/this is my text

I want to get hold of "this is my text" from the above example.
This will be displayed on the page (for now)
I didn't really want to have to use any complext url rewriting things for this...
(My hosting provider uses IIS6)
I tried using a 404 handler, but this is a bit long winded, and i'm using shared hosting, that can't set the "execute url" on custom 404 pages.
Any other ideas?

A: You can add a mapping for all requests with the * extension to the ASP.NET isapi dll (GET/POST) verbs. You will need to uncheck the "verify file is on disk" checkbox when mapping the extension in IIS. (In IIS7 integrated mode, you map the extension in the web.config as well). Note that this will caause everything to be served by asp.net, even images and script files, which can slow things down.
Then create a handler mapping in your web.config to a http handler you create.
From there, in the ProcessRequest() method of the handler, you have access to the HttpContext that spawned the request and can manipulate the URL from there.
That is the easiest option, you could also create a HttpModule, or have the default page at root redirect to http://www.domain.com/default.aspx/this is my text, in the code-behind of default.aspx, you will be able to get the text following the page and slash.


Q: docker push to nexus 3 - invalid checksum digest format Though I am able to successfully push a newly pulled docker image to Nexus 3 docker hosted repo, an error like "invalid checksum digest format" is thrown at the end. I pulled "jenkins:latest" from dockerhub, then tagged it and then pushed it to a nexus docker hosted repo.
f3e4e0468545: Pushed
656120ad8c56: Pushed
30f9a83f20f3: Pushed
78dbfa5b7cbc: Pushed
invalid checksum digest format

I know Nexus 3 is not LTS yet, but want to be sure that its not my environment settings. I have an insecure docker registry on 18443

docker info
Containers: 1
 Running: 0
 Paused: 0
 Stopped: 1
Images: 53
Server Version: 1.10.1
Storage Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 89
 Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
 Volume: local
 Network: bridge null host
Kernel Version: 3.16.0-53-generic
Operating System: Ubuntu 14.04.3 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 3.86 GiB

Client:
 Version:      1.10.1
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   9e83765
 Built:        Thu Feb 11 19:27:08 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.10.1
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   9e83765
 Built:        Thu Feb 11 19:27:08 2016
 OS/Arch:      linux/amd64

A: Docker version 1.10 was not out when Nexus 3.0m7 was released.  We are working on adding support for it now.  This specific issue is being tracked here:
https://issues.sonatype.org/browse/NEXUS-9766
UPDATE: This issue/ticket is resolved now in Nexus Repository Manager 3.0.0-03.  For upgrade instructions see https://support.sonatype.com/hc/en-us/articles/217967608-How-to-Upgrade-Nexus-3-Milestone-m7-to-3-0-0-Final.


Q: iPhone didreceivememorywarning strategy If i have a array of employees for example in my viewcontroller. Then I get the notification of low memory and the app is also not the active one.
At this point I should save the list of employees in a DB right ? so that when the user reactivate the app again, it will go through the viewDidLoad and from here I can reload the data from the DB?
Is this a good strategy?
I'm fairly new into iPhone dev.

A: You should save any unsaved changes as soon as your app enters the background. Your app could be terminated at any point in the background without ever receiving any notifications of any kind. If your data isn't saved, it will be lost when the user restarts the app.
With regard to memory warnings, these are more likely to happen in the foreground. Once your app is in the background, it is suspended and won't get any notifications. If your app is running under iOS 5 or earlier then a memory warning could result in a view controller's viewWillUnload method being called. When that view controller needs to be displayed again, its viewDidLoad will be called again. Under iOS 6, this doesn't happen anymore. viewWillUnload is deprecated.


Q: Eigen::SparseTriangularView I am trying to switch some code from Eigen 3.2.10 to 3.3. I am running into compile errors with this method declaration
/// \brief Returns template expression for the lower triangular part of A.
Eigen::SparseTriangularView < SystemMatrixType, Eigen::Lower >
    getLowerTriangular() const;

producing error C2143: syntax error : missing ';' before '<'.
It looks like SparseTriangularView has been renamed or replaced. What should SparseTriangularView or this whole declaration be replaced by?

A: Just use TriangularView < SystemMatrixType, Eigen::Lower >. Triangular and Selfadjoint views of dense and sparse expressions have been unified in 3.3.


Q: How do I get the body in a SOAP response when I have a ClientTransportException In SoapUI/Postman I am sending this request

Notice how I am getting a 401 Unauthorized, but I am getting a response body. The 401 is expected.
Now I am trying to send this message with jax-ws. I intercept the messageresponse with a handler.
My handler looks like this:
public class SHandler implements SOAPHandler<SOAPMessageContext> {
    @Override
    public Set<QName> getHeaders() {
        System.out.println(">>>>>>>>>>> GetHeaders");
        return null;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext soapMessageContext) {
        boolean isRequest = (Boolean) soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (!isRequest) {
            try {
                System.out.println(soapMessageContext.getMessage().getSOAPBody().getValue(););
            } catch (SOAPException e) {
                e.printStackTrace();
            }
        }
        System.out.println(">>>>>>>>> Message");
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext soapMessageContext) {
        try {
            System.out.println(soapMessageContext.getMessage().getSOAPBody().getValue());
        } catch (SOAPException e) {
            e.printStackTrace();
        }
        System.out.println(">>>>>>>>>>> HandleFault");
        return true;
    }

    @Override
    public void close(MessageContext messageContext) {
        System.out.println(">>>>>>>>>>> Close");
    }
}

I would expect to get a return value from the request, but I get null. I only see this response in my console:
com.sun.xml.ws.client.ClientTransportException: The server sent HTTP status code 401: Unauthorized
How do I get the body that is shown in the Postman request?
 Some more context information:
The jax-ws service that makes requests to the blurred out endpoint
@WebServiceClient(
        name = "LIReceiveMessageService",
        targetNamespace = "http://uic.cc.org/UICMessage",
        wsdlLocation = "src/main/java/nl/rls/ci/soapinterface/UICCCMessageProcessingInboundWS.wsdl"
)
public class LIReceiveMessageService
        extends Service {
    ....
}

The messageResolver I added using this oracle guide.
LIReceiveMessageService service = new LIReceiveMessageService();
service.setHandlerResolver(new MyHandlerResolver());