text:
Q: Can I organize Doctrine entities or their mapping files into subfolders? I have tried this directory structure for my mapping files:
/config/doctrine/Place.orm.yml
/config/doctrine/Place/Type.orm.yml
/config/doctrine/Place/Price.orm.yml

And have pointed to the corresponding Entity in my mapping file like this:
Project\TestBundle\Entity\Place\Type:
  type: entity
  table: place_type
  id:
    id:
      type: integer
      generator: { strategy:AUTO }
  fields:
    name:
      type: string
      length: 255

But this returns an error. The system can't seem to detect the mapping file for Entity.

A: Long story short, this is possible.
If you have folder structure inside your bundle's Entity folder, it's simple. You have to name your ORM files using entity namespace part below of Entity namespace and replacing \ with ..
So if, for example, you have Project\TestBundle\Entity\Place\Type entity, the ORM file (located in config/doctrine folder inside bundle) will have name Place.Type.orm.yml.
If you want to use as Doctrine entities classes from outside of Entity folder (or even outside of the bundle folder), it gets a little bit complicated, but still possible. Doctrine Bundle allows to define custom mapping locations for your classes in its configuration.
Again - example. If you have your entities inside of Project\Test namespace (in folder src/Project/Test), you can define mapping like this:

app/config/config*.yml

doctrine:
  orm:
    MyCustomDomain:
          mapping:              true
          type:                 yml
          dir:                  %kernel.root_dir%/config/projecttest
          alias:                ProjectTest
          prefix:               Project\Test
          is_bundle:            false

In fact, Doctrine Bundle does something similar automatically, that's why you can put all of your classes in Entity subfolder and fear no more.
The prefix is namespace prefix. Folder is the path to folder with configuration files. Alias is interesting - it allows to use simpler object names in DQL queries and mapping files. Symfony's TestBundle:Test syntax works on the same premise - TestBundleis the alias for all entities in TestBundle. is_bundle tells Doctrine, that the entities are outside of Symfony bundle and require a little bit different treatment.
There are some caveats in defining your own mapping. Mapper works using 'first match' rule on prefix. So if you declare your mapping on too broad namespace prefix, it can override other mappings.
Nevertheless, it is useful sometimes. For example, if you want to map classes from "foreign" library directly to Doctrine. Or are creating a library not completely tied to Symfony and want to keep some of your classes outside of the bundle.

A: If you want to organize your doctrine Entities into subfolders
for example: src/AppBundle/Entity/subfolder/MyEntity.php
then the corresponding ORM file should look like:
src/Resources/config/Doctrine/subfolder.MyEntity.orm.yml
Don't make subfolders inside src/Resources/config/Doctrine/*
*Note: If you have a look at the Doctrine config docs it looks like it may be possible to configure a different location for your orm.yml file using:
doctrine:
      orm:
        # An array of mappings, which may be a bundle name or     something else
        mapping_name:
              mapping:              true
              type:                 ~
              dir:                  ~
              alias:                ~
              prefix:               ~
              is_bundle:            ~

but I have not tried this. maybe someone else can confirm to improve this answer?

A: with @ORM annotations all you need is ::class,
here is example:
/**
 * @ORM\ManyToOne(targetEntity=User::class)
 */
private User $accountant;

don't forget to import User like this
use App\Entity\Subfolder\User;


text:
Q: Testing Custom Grails Taglib with Service and Plugin Dependencies I have a custom taglib that needs to make calls to a service method, which in turn uses the Wslite plugin to send and receive SOAP messages. The taglib looks something like this.
class myTagLib {
    def myService
    def thisTag = {
        def parametersFromService = myService.method("argument")
        out << render(template:'/myFolder/myView',
        model:parametersFromService)
    }
}

I'm trying to construct a test for this taglib. My test is something like:
void testThisTag() {
    def appliedTagLib = applyTemplate('<thisTag attr="value" />')
    def parametersFromService = myService.method("argument")
    def renderedTemplate = render(template:'/myFolder/myView',
        model:parametersFromService)
    assertEquals appliedTagLib, renderedTemplate
}

I started by writing this as a Unit test. I tried the simple MockFor(MyService) annotation, as well as mocking them in a more elaborate fashion, but myService object was always null when the taglib tried to invoke it.
Given that, I decided it best to simply do this as an integration test; that would get me access to the plugin and service, no problemo.
However, the applyTemplate method only works if your test class extends the GroovyPagesTestCase. If you do that though, the render method doesn't work, at least not in an integration test. I know that applyTemplate and render do work alongside each other in a unit test for a taglib, as I've tested other taglibs this way.
I seem to be between a rock and a hard place. To get access to the service, plugin, and the SOAP service they invoke, I need an integration test. To use the applyTemplate() method, I need to extend the GroovyPagesTestCase, but that breaks the render method. I've tried adding import grails.test.GroovyPagesTestCase to my test class, and then invoking the applyTemplate method off of it, but that results in a missing method exception.
Thoughts?
The Grails version is 2.0.1, but I could upgrade to 2.2.1 if that would help (our site is in transition).
---Addendum-----
elias suggested that I could inject an instance of grails.gsp.PageRenderer to get a working render method. I've tried constructing one:
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine
import grails.gsp.PageRenderer

...
def pageRenderer

...
void setUp() {
    context = grailsApplication.mainContext
    taglib = context.getBean(myTagLib.class.name)
    pageRenderer = new PageRenderer(new GroovyPagesTemplateEngine(context.getServletContext()))
}

But receive this error:
java.lang.NullPointerException: Cannot invoke method findTemplateByPath() on null object
at grails.gsp.PageRenderer.renderViewToWriter(PageRenderer.groovy:120)
at grails.gsp.PageRenderer.render(PageRenderer.groovy:77)
at MyTagLibIntegrationTests.testThisTag(MyTagLibIntegrationTests.groovy:37)

A: I was struggling with something similar some days ago, here is how I solved it:

*

*Keep the test as in integration test (don't need to extend anything)

*Grab the instance of the taglib bean with grailsApplication.mainContext.getBean

*Test it using a method call

And that's it! :)
class MyTagLibTests {
    def grailsApplication
    def taglib

    @Before
    void setUp(){
        // grab the taglib instance from Spring context
        taglib = grailsApplication.mainContext.getBean(MyTagLib.class.name)
    }

    @Test
    void myTestAboutThisTag() {
        def thisTagArgs = [:] // set up the arguments here
        assert 'shouldResultThis' == taglib.thisTag(thisTagArgs).toString()
    }
}

A: So, what I ultimately did was to extend the GroovyPagesTestCase in order to get applyTemplate, then inject the groovyPageRenderer as elias suggested. Persnickity note: you must call your injected PageRenderer groovyPageRenderer in order for spring to do all the appropriate wiring for you. So my test class finally looked like:
class myTaglibIntegrationTests extends GroovyPagesTestCase {
    PageRenderer groovyPageRenderer
    def imageService
    @Test
    void testThisTag() {
        def appliedTagLib = applyTemplate('<thisTag attr="value" />')
        def parametersFromService = myService.method("argument")
        def renderedTemplate = groovyPageRenderer.render(template:'/myFolder/myView',
            model:parametersFromService)
        assertEquals appliedTagLib, renderedTemplate
    }
}

A: A cleaner solution would use the GroovyPageUnitTestMixin as it already contains a render method.
@grails.test.mixin.TestMixin(grails.test.mixin.GroovyPageUnitTestMixin)
class myTaglibIntegrationTests {

    def myService

    @Test
    void testThisTag() {
        def appliedTagLib = applyTemplate('<thisTag attr="value" />')
        def parametersFromService = myService.method("argument")
        def renderedTemplate = render(template:'/myFolder/myView',
                                      model:parametersFromService)
        assertEquals appliedTagLib, renderedTemplate
    }
}

A good write-up on some simple taglib testing can be found here: http://mrhaki.blogspot.com/2013/05/grails-goodness-testing-views-and.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: .NET MVC: A Q when changing the value in controller Thanks everyone's effort of helping me out, basically I'm facing a problem in controller below, just make it simple and easy:
Controller C{

       public list<model> a;
       //used in action A, if it's a searched list, then don't initialize;
       public bool searched = false;

       public ActionResult A(){
          if(searched){
             ViewBag.a = a;
          }else
          //initial the list
          a = db.model.where();
          .....
          return view()
       }

       //return a result list when people search by keywords
       public ActionResult B(string str){
          a = db.model.where(d=> d.id = str);
          search = true;
       }

    }

But, it turned out that the value of both a and researched never changed after B called
Did I miss some critical knowledge in .NET MVC?
Any related articles are very welcomed
Thanks

A: You're probably thinking the state will be preserved between two web requests. But when the web request ends, the entire controller is destroyed and the set information is lost unless it is stored in a persistent data store like Session or a database.
If I understand your code correctly, if you refactor your code slightly, you can probably achieve your searching functionality under one action, and you wouldn't need to store the data persistently.

A: Controller C will be recreated on each request, so even though the values are updated after B is called, the next request for A will require the creation of controller C so a an search will be reinstantiated.
You might want to make the local variables static.


text:
Q: Javascript class import call expects exactly one argument so I read a couple of question similar to mine but unfortunately it wasn't so similar or I just couldn't figure it out.
without further ado, this my export in Book.js
export default Book;

and my import in script.js
import Book from "./Book.js";

and link in html
<script type="module" src="script.js"> </script>
<script type="module" src="Book.js"> </script>

So basically how to fix class import call expects exactly one argument?
or just how to import the class and using it in main script properly ?
hope get approved and posted like it supposed to be ,
thanks in advance.
EDIT : SOLVED => for some reason it was not a code thing, I reseted dev tools in chrome and Firefox and everything worked.


text:
Q: Create fixture list from given teams I've a list of teams as below:
|Team|
|---|
|A|
|B|
|C|

What would be the pandas/python way to create the following table of fixtures:
|Home Team|Away Team|
|---|---|
|A|B|
|A|C|
|B|A|
|B|C|
|C|A|
|C|B|

Each team plays the other team twice (home and away).


text:
Q: In Angular : i can't get the value from $scope's properties There is a button on the page, I expected control it show or hide by different properties value:
cancel

This is my data obj:
$scope.designedTimeList.push({
            from: $scope.fromTime,
            duration: $scope.durationTime,
            theme: $scope.theme,
            plan: $scope.plan,
            status: '0'
        });

Right now, I want to match the time between fromTime and realtime:
var date = new Date();

        var hour = date.getHours();
        var minute = date.getMinutes();

        var existHour = +($scope.designedTimeList[0].from.subString(0, 2));
        var existMinute = $scope.designedTimeList[0].duration;
        // i just wanna get the first element in the `designedTimeList`

        if (existHour == hour && existMinute >= minute) {
            $scope.designedTimeList[0].status = '1';
        } else if (existHour < hour || (existHour == hour && existMinute < minute)) {
            $scope.designedTimeList[0].status = '-1';

        }

But when I use this:
$scope.designedTimeList[0].from.subString(0, 2);
$scope.designedTimeList[0].duration;

it log TypeError: Cannot read property 'from' of undefined,TypeError: Cannot read property 'duration' of undefined
the data in the $scope.designedTimeList is like this:
[{duration: "15 min",from: "2 am",plan: "test",status: "0",theme: "test"},{},{}...]

Please tell me what's the problem and how to figure it out.
cancel code :
    var checkTime = function() {

        var date = new Date();

        var hour = date.getHours();
        var minute = date.getMinutes();

        // var temp = $scope.

            var existHour = +($scope.designedTimeList[0].from.subString(0, 2));
            var existMinute = $scope.designedTimeList[0].duration;

            if (existHour == hour && existMinute >= minute) {
                $scope.designedTimeList[0].status = '1';
            } else if (existHour < hour || (existHour == hour && existMinute < minute)) {
                $scope.designedTimeList[0].status = '-1';

            }

            console.log($scope.designedTimeList[0]);

            $timeout(checkTime, 1000 * 60 * 1);

    }

            $timeout(checkTime,0);

A: Before pushing in an array you have to tell that $scope.designedTimeList is an array.
so you have to write
$scope.designedTimeList = [];

and after that
$scope.designedTimeList.push({
        from: $scope.fromTime,
        duration: $scope.durationTime,
        theme: $scope.theme,
        plan: $scope.plan,
        status: '0'
    });

another thing, you have to write susbstring not "subString"
i.e
$scope.designedTimeList[0].from.substring(0, 2);


text:
Q: How to open a JavaFX Window only once time I have a JavaFX application and I need simple to avoid user from opening the same window inside the application more than once.
I tried to find some solution, but nothing get applicable.
As a sample... I have a window that give me payments options, its not a modal, it's a new stage. While I click the button to open that window, it's open, doesn't matter if there is another instance of this same stage running, simple open new windows every click. I want to avoid this. Like switch to the already opened stage window when click the button, or simply miss the click if that window is already opened.

A: You just need to keep track of the stage and only open a new one if its not already shown.  You could also choose to disable the Button if the new window is showing, but I prefer to have the new window simply brought back in front so the user knows it's there.
You can do this by creating a reference to your Stage and then checking if it is null or showing within the button's event handler.
Here is an MCVE to demonstrate:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    /**
     * Reference to the new Window that will allow only one instance at a time.
     */
    private Stage newWindowStage;

    public static void main(String[] args) {

        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        VBox root = new VBox(5);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(10));

        Button openWindow = new Button("Open Window");

        // **********************************************************************************************
        // Set the button to open the new Window Stage
        // **********************************************************************************************
        openWindow.setOnAction(event -> {

            // **********************************************************************************************
            // Check if the Stage is already showing.
            // **********************************************************************************************
            if (newWindowStage == null || !newWindowStage.isShowing()) {

                // **********************************************************************************************
                // The new window is not currently open, so create/show it
                // **********************************************************************************************
                newWindowStage = new Stage();
                newWindowStage.setWidth(300);
                newWindowStage.setHeight(300);
                newWindowStage.setScene(new Scene(
                        new VBox(
                                new Label("New Window!")
                        )
                ));
                newWindowStage.show();
            } else {
                // **********************************************************************************************
                // The window is already open, so bring it to the front of focus
                // **********************************************************************************************
                newWindowStage.toFront();
            }

        });

        root.getChildren().add(openWindow);

        primaryStage.setScene(new Scene(root));
        primaryStage.setWidth(200);
        primaryStage.setHeight(200);
        primaryStage.setTitle("Test Application");
        primaryStage.show();
    }
}


text:
Q: How to make intermediate object file not a library using qmake? Filesystem layout:
MyProject
|_ myproject.pro
|_ FuncA
   |_ core.cpp
   |_ core.h
   |_ core.pro
|_ app
   |_ main.cpp
   |_ app.pro

I want just to compile "core.cpp" in FuncA to make a object file not a library. That is "gcc -c core.cpp". And in app I want to make main program linking core.o created previously.
In this case how do I make core.pro? Which TEMPLATE should I use?

A: Use can use generic app template for core.pro. It will create intermediate core.o anyway, which you can link later in app.pro like so:
LIBS += $$PWD/../FuncA/core.o

A: I solved this problem with "static library config" so that it will not make ".so" libs and then link that static library with main program.
TEMPLATE = lib
CONFIG += staticlib


text:
Q: C# ошибка Expected: not equal to 0 But was: 0 Решаю данную задачу https://ulearn.me/Course/basicprogramming2/Praktika_Readonly_bytes__1a5e39b3-9b7f-46c5-bb3c-ab024f2c8714
По заданию создал класс ReadonlyBytes
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace hashes
{
    public class ReadonlyBytes : IEnumerable<byte>
    {
        private readonly byte[] byteArray;
        private readonly int hashCode;
        public int Length { get; }

        public ReadonlyBytes(params byte[] array)
        {
            if (array == null)
            {
                throw new ArgumentNullException();
            }

            Length = array.Length;
            byteArray = array;
            hashCode = GetHashCode();
        }

        public override string ToString()
        {
            var result = new StringBuilder("[");
            result.Append(String.Join(", ", byteArray));
            result.Append("]");
            return result.ToString();
        }

        public override int GetHashCode()
        {
            UInt64 result = 0;
            UInt64 p = 16777619;
            var shift = Length / 50;
            for (var i = 0; i < Length; i += 1 + shift)
            {
                result ^= (uint)byteArray[i];
                result = (result * p) % int.MaxValue;
            }
            return (int)(result);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            var castedObj = obj as ReadonlyBytes;
            if (this.hashCode != castedObj.hashCode || this.Length != castedObj.Length)
            {
                return false;
            }
            else
            {
                for (var i = 0; i < this.Length; i++)
                    if (this[i] != castedObj[i])
                        return false;
                return true;
            }
        }

        public byte this[int index] => byteArray[index];

        public IEnumerator<byte> GetEnumerator()
        {
            for (var i = 0; i < Length; i++)
                yield return byteArray[i];
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

Все тесты данный код проходит, но при попытке послать данное решение выводит лог

Как минимум один из тестов не пройден! Название теста:
  HashCodeDiffers_IfArraysDiffersOnTheLastElementOnly Сообщение:
  Expected: not equal to 0   But was:  0
Стек вызовов:    at
  checking.ReadonlyBytes_HiddenTests.HashCodeDiffers_IfArraysDiffersOnTheLastElementOnly()
  Когда может возникать эта ошибка? И как это можно исправить?

A: Убрать sift совсем, а вычисления производить в конструкторе. В GetHashCode() возвращать результат.


text:
Q: Unfortunately, App has stopped (Android Development) I just started android development in 2 days and this is the error that I cannot solve "Unfortunately, [App] has stopped".
This is what I'm planning to do with the APP.

*

*show the UI that will tell the user that by pressing ok  the app will start making a log file.

*when the OK button is pressed, it will run in the background (don't need UI) and will wait for the notification from other app and will write the text from the notification to the log file.
This is my AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notificationnotifier"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.notificationnotifier.GetNotification"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.example.notificationnotifier.MonitorNotification"
            android:label="@string/app_name" android:exported="false">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

    </application>

</manifest>

This is GetNotification.java
public class GetNotification extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_notification);

        Button okButton = (Button) findViewById(R.id.OKButton);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent getNotification = new Intent("com.example.notificationnotifier.MonitorNotification");
                startActivity(getNotification);
            }
        }) ;

        Button cancel = (Button) findViewById(R.id.Cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        }) ;

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }
}

This is MonitorNotification.java
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.view.accessibility.AccessibilityEvent;

public class MonitorNotification extends AccessibilityService{

    @Override
    public void onAccessibilityEvent(AccessibilityEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onInterrupt() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onServiceConnected() {
        // TODO Auto-generated method stub
    //  super.onServiceConnected();
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
          info.feedbackType = 1;
              info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
          info.notificationTimeout = 100;
          setServiceInfo(info);
    }
}

This is the logcat
[updated]
02-04 10:31:17.947: E/Trace(1108): error opening trace file: No such file or directory (2)
02-04 10:31:18.648: D/gralloc_goldfish(1108): Emulator without GPU emulation detected.
02-04 10:31:21.128: D/AndroidRuntime(1108): Shutting down VM
02-04 10:31:21.148: W/dalvikvm(1108): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
02-04 10:31:21.169: E/AndroidRuntime(1108): FATAL EXCEPTION: main
02-04 10:31:21.169: E/AndroidRuntime(1108): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.notificationnotifier/com.example.notificationnotifier.MonitorNotification}: java.lang.ClassCastException: com.example.notificationnotifier.MonitorNotification cannot be cast to android.app.Activity
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.os.Looper.loop(Looper.java:137)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.app.ActivityThread.main(ActivityThread.java:4745)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at java.lang.reflect.Method.invokeNative(Native Method)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at java.lang.reflect.Method.invoke(Method.java:511)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at dalvik.system.NativeStart.main(Native Method)
02-04 10:31:21.169: E/AndroidRuntime(1108): Caused by: java.lang.ClassCastException: com.example.notificationnotifier.MonitorNotification cannot be cast to android.app.Activity
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
02-04 10:31:21.169: E/AndroidRuntime(1108):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
02-04 10:31:21.169: E/AndroidRuntime(1108):     ... 11 more
02-04 10:31:23.268: I/Process(1108): Sending signal. PID: 1108 SIG: 9

A: Replace this line:
Intent getNotification = new Intent("com.example.notificationnotifier.MonitorNotification");

by this one:
Intent getNotification = new Intent(GetNotification.this,
        MonitorNotification.class);

Hope it helps.

A: Add the below code in your manifest file:

 <service android:name=".MyAccessibilityService"
     android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
 <intent-filter>
     <action android:name="android.accessibilityservice.AccessibilityService" />
 </intent-filter>
 . . .
</service>

A: Declaration
An accessibility is declared as any other service in an AndroidManifest.xml but it must also specify that it handles the "android.accessibilityservice.AccessibilityService" Intent. Failure to declare this intent will cause the system to ignore the accessibility service. Additionally an accessibility service must request the BIND_ACCESSIBILITY_SERVICE permission to ensure that only the system can bind to it. Failure to declare this intent will cause the system to ignore the accessibility service. Following is an example declaration:
 <service android:name=".MyAccessibilityService"
     android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
 <intent-filter>
     <action android:name="android.accessibilityservice.AccessibilityService" />
 </intent-filter>
 . . .
</service>

A: I know now what the problem was, my friend told me that it should be startService not startActivity in the getNotification.java
the correct way to call it is
startService(getNotification);

not
startActivity(getNotification);

I'm extending AccesibilityService in the class in MonitorNotification.java. :D


text:
Q: Apache Derby db error ClassNotFoundException I am using Eclipse with WindowsBuilder.   I have created a small simple project to open an existing Derby db and I am getting the following error:-
java.lang.ClassNotFoundException; org.apache.derby.jdbc.EmbeddedDriver
with a call to ClassForName(driver) where driver is "org.apache.derby.jdbc.EmbeddedDriver".
After googling I made sure that my Windows 7 CLASSPATH includes the following:-
c:\program files\eclipse\plugins\db-derby-10.8.2.2-bin\lib\derby.jar;c:\program files\eclipse\plugins\db-derby-10.8.2.2-bin\lib\derbytools.jar;.
I still have the same problem and I am wondering how to check that the classpath entries above actually point to the driver resource.
Any help appreciated.

A: Have You added the derby db .jar file to the projects Java Build Path?

A: I had same problem and just added C:\Program Files\Java\jdk1.7.0_25\db\lib to the Project properties -> Run/Debug settings -> Classpath -> User entries -> Add External JARs and it works.
No need to:

Windows 7 CLASSPATH includes the following:- c:\program
  files\eclipse\plugins\db-derby-10.8.2.2-bin\lib\derby.jar;c:\program
  files\eclipse\plugins\db-derby-10.8.2.2-bin\lib\derbytools.jar;.


text:
Q: Get informations from .pkgx I have tried the prestage content way to get packages for some of my new distribution point and I was wondering if it was any possibility to get the revision version of the .pkgx application created.
In that way, I will be able to see if my .pkgx have to be updated.

A: Create a .ini file and save the information you get while creating the .pkgx application (like the revision).
In that case, you'll be able to test the revision and "update" it(delete the .pkgx and create a new one).


text:
Q: passport component registration field (MODULE_NOT_FOUND) after mounting loopback 3 inside loopback4 I am trying to upgrade from loopback 3 to loopback 4 using "mounting strategy" according to the documentation.
while trying to run the app using npm start, i am getting the following error:

node -r source-map-support/register .

Cannot start the application. { Error: Cannot find module
  '../../node_modules/loopback-component-passport/lib/models/utils.js'
      at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
      at Function.Module._load (internal/modules/cjs/loader.js:562:25)
      at Module.require (internal/modules/cjs/loader.js:692:17)
      at require (internal/modules/cjs/helpers.js:25:18)
      at Object. (C:\Data\myComp\app\myapp_docker\services\myapp_auth\lb3app\server\utils\providerUtils.js:2:15)
      at Module._compile (internal/modules/cjs/loader.js:778:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
      at Module.load (internal/modules/cjs/loader.js:653:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
      at Function.Module._load (internal/modules/cjs/loader.js:585:3)
      at Module.require (internal/modules/cjs/loader.js:692:17)
      at require (internal/modules/cjs/helpers.js:25:18)
      at Object. (C:\Data\myComp\app\myapp_docker\services\fauth\lb3app\server\server.js:6:25)
      at Module._compile (internal/modules/cjs/loader.js:778:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
      at Module.load (internal/modules/cjs/loader.js:653:32) code: 'MODULE_NOT_FOUND' } npm ERR! code ELIFECYCLE npm ERR! errno 1

I checked and i have the module in the node_modules directory and the utils.js file.

A: I had to search in all my app files for the string "node_modules" and I found that the relative path for that directory was incorrect. had to add one more "../" before the node_modules.


text:
Q: Checking for an empty result (PHP, PDO, and MySQL) What am I doing wrong here? I'm simply retrieving results from a table and then adding them to an array. Everything works as expected until I check for an empty result...
This gets the match, adds it to my array and echoes the result as expected:
$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today', $today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null;
    exit();
}

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $this->id_email[] = $row['id_email'];
    echo $row['id_email'];
}

$db = null;
return true;

When I try to check for an empty result, my code returns 'empty', but no longer yields the matching result:
$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null;
    exit();
}

if ($sth->fetchColumn()) {
    echo 'not empty';
    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $this->id_email[] = $row['id_email'];
        echo $row['id_email'];
    }
    $db = null;
    return true;
}
echo 'empty';
$db = null;
return false;

A: $sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");

$sql->execute();

$fetch = $sql->fetch(PDO::FETCH_ASSOC);

// if not empty result
if (is_array($fetch))  {
    $_SESSION["userMember"] = $fetch["username"];
    $_SESSION["password"] = $fetch["password"];
    echo 'yes this member is registered';
}else {
    echo 'empty result!';
}

A:
what I'm doing wrong here?

Almost everything.
$today = date('Y-m-d'); // no need for strtotime

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR

$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while

return count($this->id_email); // no need for the everything else

Effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.

A: If you have the option of using fetchAll() then, if there are no rows returned, it will just be an empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))

will return the number of rows returned.

A: You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:
$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

// I would usually put this all in a try/catch block, but I kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
    $db = null;
    exit();
}

$result = $sth->fetch(PDO::FETCH_OBJ)

if(!isset($result->id_email))
{
    echo "empty";
}
else
{
    echo "not empty, value is $result->id_email";
}

$db = null;

Of course this is only for a single result, as you might have when looping over a dataset.
I thought I would weigh in as I had to deal with this lately.

A: You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there are any results. You do
if ($sth->rowCount() > 0) {
  ... got results ...
} else {
   echo 'nothing';
}

Relevant documentation is here: PDOStatement::rowCount

A: One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup.  If there is no data, I simply return "No data found..." or something to that effect.  If there is data, then go forward, build the headers and loop through the content, etc.  Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out.  Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
    // non-repetitive markup code here
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

A: Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different database or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyway, so I went this way).
$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today', $today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null;
    exit();
}

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $this->id_email[] = $row['id_email'];
    echo $row['id_email'];
}
$db = null;

if (count($this->id_email) > 0) {
    echo 'not empty';
    return true;
}
echo 'empty';
return false;

A: I only found one way that worked...
$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");

//if (!is_array($quote)) {  didn't work
//if (!isset($quote)) {  didn't work

if (count($quote) == 0) {   //yep the count worked.
    echo 'Record does not exist.';
    die;
}


text:
Q: CSS - How can I align my radio buttons? This is my HTML form code:

        <form action="<?php echo $__SERVER["PHP_SELF"];?>" method="post">

                <input type="radio" name="tableNames" value="<?php echo $tempName; ?>" > <?php echo $tempName ?>

                    <input type="submit" value="submit">
                    <input type="reset" value="reset">

        </form>

this is my current css:
#myForm {
    margin: auto;
    width: 700px;
}
#myForm form {
    background-color: #E0E0E0;
    text-align: center;
    padding: 5px;
}
#myForm table {
    margin: auto;
    width: 60%;
    padding: 15px;
}

this is what my form looks like right now:

How can i align the radio button's buttons

A: you could wrap the inputs in a div, then center that div and give it text-align left.

#myForm {
  margin: auto;
  width: 700px;
}
#myForm form {
  background-color: #E0E0E0;
  text-align: center;
  padding: 5px;
}
#myForm table {
  margin: auto;
  width: 60%;
  padding: 15px;
}
.test {
  width: 300px;
  margin: 0 auto;
  text-align: left;
}

  <form method="post">

        <input type="radio" name="tableNames" value="asdasd123123">asdasdasd

        <input type="radio" name="tableNames" value="asd">asdasdasd

        <input type="radio" name="tableNames" value="asdasdasdas?>">123

        <input type="radio" name="tableNames" value="123123123123">asdasdasd1231231231231231231231

          <input type="submit" value="submit">

          <input type="reset" value="reset">

  </form>

A: Use this css
------------------------

 #myForm form {
    background-color: #E0E0E0;
    text-align: left;
    padding: 5px;
}

A: I'm not seeing where the multiple radio boxes are being generated, but I suggest placing all of them within the same TD if you want to continue to use a table to organize content.
Otherwise, you could place a second
 tag inside the
 you already have, and set custom dimensions for the width, padding, margin of this inner
.

A:

label,input{
  float:left;
  }

  <form action="" method="post">

      <input type="radio" name="tableNames1" value="1">1
      <input type="radio" name="tableNames2" value="2">2
      <input type="radio" name="tableNames3" value="3">3
      <input type="radio" name="tableNames4" value="4">4

          <input type="submit" value="submit">

          <input type="reset" value="reset">

  </form>

A: It's gonna be a bit messy, but I've think I found the right solution.
Something like this: JS Fiddle

#myForm {
    margin: auto;
    width: 700px;
}
#myForm form {
    background-color: #E0E0E0;
    padding: 5px;
}
#myForm table {
    margin: auto;
    width: 60%;
    padding: 15px;
    text-align: center;
}
.radio_holder{
  width: 45%;
  display:inline-block;

}
.radio_label_holder {
  display:block;
  text-align: right;
}
label{
  width:53%;
  display:inline-block;
  text-align:left;
}
.all_radio{
  display:block;
  margin:auto;
  width:60%;
}

        <form>

            <input type="radio" id="administrators" name="tableNames" value="administrators" > administrators

            <input type="radio" id="bookings" name="tableNames" value="bookings" > bookings

            <input type="radio" id="rooms" name="tableNames" value="rooms" > rooms

            <input type="radio" id="customers" name="tableNames" value="customers" > customers

                    <input type="submit" value="submit">
                    <input type="reset" value="reset">

        </form>

A: You better place the radio button in ...
<input type="radio" name="tableNames" value="<?php echo $tempName; ?>" > <?php echo $tempName ?>

become:
<input type="radio" name="tableNames" value="<?php echo $tempName; ?>" > <?php echo $tempName ?>

It's aligning with the html.


text:
Q: import phpexcel codeigniter except current cell value i want to import from excel using php excel from my codeigniter with current cell containt current text

cell1
cell2

A
1

B
2

C
3

i want just cell except B in cell1 to insert database
my controller
public function import_excel(){
    if (isset($_FILES["fileExcel"]["name"])) {
        $path = $_FILES["fileExcel"]["tmp_name"];
        $object = IOFactory::load($path);
        foreach($object->getWorksheetIterator() as $worksheet)
        {
            $highestRow = $worksheet->getHighestRow();
            $highestColumn = $worksheet->getHighestColumn();
            for($row=2; $row<=$highestRow; $row++)
            {
                $cell1= $worksheet->getCellByColumnAndRow(0, $row)->getValue();
                $cell2= $worksheet->getCellByColumnAndRow(1, $row)->getValue();

                $temp_data[] = array(
                    'cell1'  => $cell1,
                    'cell2'   => $cell2,

                );

            }
        }

        if($cell1 == 'B'){

        }else{
            $this->load->model('M_Admin');
            $insert = $this->M_Admin->insert($temp_data);

        }

but this failed and data still insert. please help me and many thanks you for help.

A: I never use phpexcel before, but if it's array and consider that $cell1 is a string/text, I guess you can try to use this:
        for($row=2; $row<=$highestRow; $row++)
        {
            $cell1= $worksheet->getCellByColumnAndRow(0, $row)->getValue();
            $cell2= $worksheet->getCellByColumnAndRow(1, $row)->getValue();

            //cell value you want to hide
            if ($cell1 == 'B') {
                $cell1 = 'xxx'; //overwrite that value into something
            }

            $temp_data[] = array(
                'cell1'  => $cell1,
                'cell2'   => $cell2,

            );

        }

note: I'm using codeigniter 3


text:
Q: Android Room, how to save an entity with one of the variables being a sealed class object I want to save in my Room database an object where one of the variables can either be of on type or another. I thought a sealed class would make sense, so I took this approach:
sealed class BluetoothMessageType() {
    data class Dbm(
        val data: String
    ) : BluetoothMessageType()

    data class Pwm(
        val data: String
    ) : BluetoothMessageType()
}

Or even this, but it is not necessary. I found that this one gave me even more errors as it did not know how to handle the open val, so if I find a solution for the first version I would be happy anyway.
sealed class BluetoothMessageType(
    open val data: String
) {
    data class Dbm(
        override val data: String
    ) : BluetoothMessageType()

    data class Pwm(
        override val data: String
    ) : BluetoothMessageType()
}

Then the Entity class
@Entity(tableName = MESSAGES_TABLE_NAME)
data class DatabaseBluetoothMessage(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0L,
    val time: Long = Instant().millis,
    val data: BluetoothMessageType
)

I have created a TypeConverter to convert it to and from a String as well, so I assume that it is not a problem.
First, is this possible? I assume this should function in a similar way that it would with an abstract class, but I have not managed to find a working solution with that either. If it is not possible, what sort of approach should I take when I want to save some data that may be either of one or another type if not with sealed classes?

A: We faced such problem when we tried using Polymorphism in our domain, and we solved it this way:
Domain:
We have a Photo model that looks like this:
sealed interface Photo {
    val id: Long

    data class Empty(
        override val id: Long
    ) : Photo

    data class Simple(
        override val id: Long,
        val hasStickers: Boolean,
        val accessHash: Long,
        val fileReferenceBase64: String,
        val date: Int,
        val sizes: List<PhotoSize>,
        val dcId: Int
    ) : Photo
}

Photo has PhotoSize inside, it looks like this:
sealed interface PhotoSize {
    val type: String

    data class Empty(
        override val type: String
    ) : PhotoSize

    data class Simple(
        override val type: String,
        val location: FileLocation,
        val width: Int,
        val height: Int,
        val size: Int,
    ) : PhotoSize

    data class Cached(
        override val type: String,
        val location: FileLocation,
        val width: Int,
        val height: Int,
        val bytesBase64: String,
    ) : PhotoSize

    data class Stripped(
        override val type: String,
        val bytesBase64: String,
    ) : PhotoSize
}

Data:
There is much work to do in our data module to make this happen. I will decompose the process to three parts to make it look easier:
1. Entity:
So, using Room and SQL in general, it is hard to save such objects, so we had to come up with this idea. Our PhotoEntity (Which is the Local version of Photo from our domain looks like this:
@Entity
data class PhotoEntity(
    // Shared columns
    @PrimaryKey
    val id: Long,
    val type: Type,

    // Simple Columns
    val hasStickers: Boolean? = null,
    val accessHash: Long? = null,
    val fileReferenceBase64: String? = null,
    val date: Int? = null,
    val dcId: Int? = null
) {
    enum class Type {
        EMPTY,
        SIMPLE,
    }
}

And our PhotoSizeEntity looks like this:
@Entity
data class PhotoSizeEntity(
    // Shared columns
    @PrimaryKey
    @Embedded
    val identity: Identity,
    val type: Type,

    // Simple columns
    @Embedded
    val locationLocal: LocalFileLocation? = null,
    val width: Int? = null,
    val height: Int? = null,
    val size: Int? = null,

    // Cached and Stripped columns
    val bytesBase64: String? = null,
) {
    data class Identity(
        val photoId: Long,
        val sizeType: String
    )

    enum class Type {
        EMPTY,
        SIMPLE,
        CACHED,
        STRIPPED
    }
}

Then we have this compound class to unite PhotoEntity and PhotoSizeEntity together, so we can retrieve all data required by our domain's model:
data class PhotoCompound(
    @Embedded
    val photo: PhotoEntity,
    @Relation(entity = PhotoSizeEntity::class, parentColumn = "id", entityColumn = "photoId")
    val sizes: List<PhotoSizeEntity>? = null,
)

2. Dao
So our dao should be able to store and retrieve this data. You can have two daos for PhotoEntity and PhotoSizeEntity instead of one, for the sake of flexibility, but in this example we will use a shared one, it looks like this:
@Dao
interface IPhotoDao {

    @Transaction
    @Query("SELECT * FROM PhotoEntity WHERE id = :id")
    suspend fun getPhotoCompound(id: Long): PhotoCompound

    @Transaction
    suspend fun insertOrUpdateCompound(compound: PhotoCompound) {
        compound.sizes?.let { sizes ->
            insertOrUpdate(sizes)
        }

        insertOrUpdate(compound.photo)
    }

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrUpdate(entity: PhotoEntity)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrUpdate(entities: List<PhotoSizeEntity>)
}

3. Adapter:
After solving the problem of saving data to SQL database, we now need to solve the problem of converting between domain and local entities. Our Photo's converter aka adapter looks like this:
fun Photo.toCompound() = when(this) {
    is Photo.Empty -> this.toCompound()
    is Photo.Simple -> this.toCompound()
}

fun PhotoCompound.toModel() = when (photo.type) {
    PhotoEntity.Type.EMPTY -> Photo.Empty(photo.id)
    PhotoEntity.Type.SIMPLE -> this.toSimpleModel()
}

private fun PhotoCompound.toSimpleModel() = photo.run {
    Photo.Simple(
        id,
        hasStickers!!,
        accessHash!!,
        fileReferenceBase64!!,
        date!!,
        sizes?.toModels()!!,
        dcId!!
    )
}

private fun Photo.Empty.toCompound(): PhotoCompound {
    val photo = PhotoEntity(
        id,
        PhotoEntity.Type.EMPTY
    )

    return PhotoCompound(photo)
}

private fun Photo.Simple.toCompound(): PhotoCompound {
    val photo = PhotoEntity(
        id,
        PhotoEntity.Type.SIMPLE,
        hasStickers = hasStickers,
        accessHash = accessHash,
        fileReferenceBase64 = fileReferenceBase64,
        date = date,
        dcId = dcId,
    )

    val sizeEntities = sizes.toEntities(id)
    return PhotoCompound(photo, sizeEntities)
}

And for the PhotoSize, it looks like this:
fun List<PhotoSize>.toEntities(photoId: Long) = map { photoSize ->
    photoSize.toEntity(photoId)
}

fun PhotoSize.toEntity(photoId: Long) = when(this) {
    is PhotoSize.Cached -> this.toEntity(photoId)
    is PhotoSize.Empty -> this.toEntity(photoId)
    is PhotoSize.Simple -> this.toEntity(photoId)
    is PhotoSize.Stripped -> this.toEntity(photoId)
}

fun List<PhotoSizeEntity>.toModels() = map { photoSizeEntity ->
    photoSizeEntity.toModel()
}

fun PhotoSizeEntity.toModel() = when(type) {
    PhotoSizeEntity.Type.EMPTY -> this.toEmptyModel()
    PhotoSizeEntity.Type.SIMPLE -> this.toSimpleModel()
    PhotoSizeEntity.Type.CACHED -> this.toCachedModel()
    PhotoSizeEntity.Type.STRIPPED -> this.toStrippedModel()
}

private fun PhotoSizeEntity.toEmptyModel() = PhotoSize.Empty(identity.sizeType)

private fun PhotoSizeEntity.toCachedModel() = PhotoSize.Cached(
    identity.sizeType,
    locationLocal?.toModel()!!,
    width!!,
    height!!,
    bytesBase64!!
)

private fun PhotoSizeEntity.toSimpleModel() = PhotoSize.Simple(
    identity.sizeType,
    locationLocal?.toModel()!!,
    width!!,
    height!!,
    size!!
)

private fun PhotoSizeEntity.toStrippedModel() = PhotoSize.Stripped(
    identity.sizeType,
    bytesBase64!!
)

private fun PhotoSize.Cached.toEntity(photoId: Long) = PhotoSizeEntity(
    PhotoSizeEntity.Identity(photoId, type),
    PhotoSizeEntity.Type.CACHED,
    locationLocal = location.toEntity(),
    width = width,
    height = height,
    bytesBase64 = bytesBase64
)

private fun PhotoSize.Simple.toEntity(photoId: Long) = PhotoSizeEntity(
    PhotoSizeEntity.Identity(photoId, type),
    PhotoSizeEntity.Type.SIMPLE,
    locationLocal = location.toEntity(),
    width = width,
    height = height,
    size = size
)

private fun PhotoSize.Stripped.toEntity(photoId: Long) = PhotoSizeEntity(
    PhotoSizeEntity.Identity(photoId, type),
    PhotoSizeEntity.Type.STRIPPED,
    bytesBase64 = bytesBase64
)

private fun PhotoSize.Empty.toEntity(photoId: Long) = PhotoSizeEntity(
    PhotoSizeEntity.Identity(photoId, type),
    PhotoSizeEntity.Type.EMPTY
)

That's it!
Conclusion:
To save a sealed class to Room or SQL, whether as an Entity, or as an Embedded object, you need to have one big data class with all the properties, from all the sealed variants, and use an Enum type to indicate variant type to use later for conversion between domain and data, or for indication in your code if you don't use Clean Architecture. Hard, but solid and flexible. I hope Room will have some annotations that can generate such code to get rid of the boilerplate code.
PS: This class is taken from Telegram's scheme, they also solve the problem of polymorphism when it comes to communication with a server. Checkout their TL Language here: https://core.telegram.org/mtproto/TL
PS2: If you like Telegram's TL language, you can use this generator to generate Kotlin classes from scheme.tl files: https://github.com/tamimattafi/mtproto
EDIT: You can use this code generating library to automatically generate Dao for compound classes, to make it easier to insert, which removes a lot of boilerplate to map things correctly.
Link: https://github.com/tamimattafi/android-room-compound
Happy Coding!

A: In my case I did the following:
sealed class Status2() {
object Online : Status2()
object Offline : Status2()

override fun toString(): String {
    return when (this) {
       is Online ->"Online"
        is Offline -> "Offline"
    }
  }
}

class StatusConverter{
@TypeConverter
fun toHealth(value: Boolean): Status2 {
    return if (value){
        Status2.Online
    } else{
        Status2.Offline
    }
}

@TypeConverter
fun fromHealth(value: Status2):Boolean {
    return when(value){
        is Status2.Offline -> false
        is Status2.Online -> true
    }
  }
}

@Dao
interface CourierDao2 {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertStatus(courier: CourierCurrentStatus)

@Query("SELECT * FROM CourierCurrentStatus")
fun getCourierStatus(): Flow<CourierCurrentStatus>
}

@Entity
 data class CourierCurrentStatus(
 @PrimaryKey
 val id: Int = 0,
 var status: Status2 = Status2.Offline
)

and it works like a charm


text:
Q: iPhone app using different language than the one set in OS / device? Is it possible to have my app running in a different language than the one that is set in the OS? I want to have a language switch in my app's setting menu, where the user can e.g. select german for the app, while his system is running in english.
From what I've already read, it seems it's not possible without having my own localization mechanism…
What do you think?

A: it can be done easily although it took me weeks to work out how ;-)
I have an iPhone app called iDEX which is a Romanian dictionary. On the iPad, Romanian is not available as a UI language, so I wanted to give the user the option of selecting Romanian in the application settings, as the device settings do not include it.
What you have to do is internationalize the app and localize it as usual. Then, in the main method, set the AppleLanguages key of the standard NSUserDefaults to the language and country of your choice, like so
int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSArray arrayWithObject:@"ro_RO"] forKey:@"AppleLanguages"];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool drain];
    return retVal;
}

It is imperative that you set the AppleLanguages key before you run UIApplicationMain(), because it is at that point that the UIKit framework is loaded and the default language determined.
It also important that you specify both language and country (eg, @"ro_RO" and not just @"ro") otherwise your app might crash when setting the key.
By doing this, all calls to NSBundle that support localization will look for the language that you have programatically established, as opposed to the one set on the device.
Hope that helps...

A: You need to implement your custom resource loading mechanism to achieve that. For example you will no longer be able to use NSLocalizedString macro or [NSBundle pathForResource:]. You will always have to specify paths including the localization (as in de.lproj/MyStrings.strings instead of just MyStrings.strings). I would suggest against doing this unless absolutely necessary.


text:
Q: Recording CPU time for GA algorithm in Matlab using optimization toolbox I am using global optimization toolbox to run genetic algorithm on Matlab. However, I do not see any documentation or function to record the CPU time.

A: You can use the function cputime explained here. It returns time in seconds. Although, tic and toc are a better choice for measuring performance in Matlab codes.
A sample code :
startTime = cputime;
% GA Code
endTime = cputime;
cpu_time_consumed = endTime - startTime;

A: I realized that this can also be done using the "Run and Time" option available in Matlab.


text:
Q: Problem redirecting to 10.0.2.2 when using Facebook OAuth with Android Emulator I have a Xamarin.Forms app targeting Android and iOS communicating with an ASP.NET Core backend. I need to implement social authentication for the app - Facebook and Google for now. Following this Microsoft guide I added Xamarin.Essentials.WebAuthenticator in my mobile app, created the appropriate authentication endpoints and added Facebook auth middleware.
Now my problem is that I'm using an Android emulator for development and in order for me to communicate with my server backend (hosted on my developer machine) I need to use the special IP address 10.0.2.2 as described here.  The problem is that in order for the OAuth workflow to work I need to list 10.0.2.2 as a Valid redirect URL in the Facebook developer portal.
The problem with this is that I get an which says that "This can't be a Facebook URL" which means that the URL is not whitelisted. That means that whenever I try to authenticate through the Android emulator using the 10.0.2.2:44351 address to refer to my backend, I get error from Facebook saying that "This URL is not whitelisted under "Valid OAuth Redirect URIs".
How can I work around this?


text:
Q: Create new file with other name if file name already exist in python For the moment my script can create a file and the content. However, I would like to have a way in my code to directly noticed if the file already exists, and then if it exists, it creates a new file which will not be Y but Y_2 or Y with the current date. So I can have a history of my file created.
customername = "X"
workspacename = "Y"

structureDict = {
    "attribute": ["attributes/screens"],

    "content": ["containers",
                "dataProcessing",
                "fields",
                "properties",
                "sources",
                "structures",
                "usages"],

    "types": ["containers/types",
              "dataProcessing/types",
              "fields/types",
              "properties/types",
              "sources/types",
              "structures/types",
              "usages/types"]
}

for category in structureDict:
    for endpoint in structureDict[category]:
        print (category, endpoint)

def writeContentToFile(mode, customername, workspacename, category, endpoint, jsonContent):
    path = os.path.join(os.getcwd(), customername, workspacename, category)
    Path(path).mkdir(parents=True, exist_ok=True)

    with open(path + "/" + endpoint + '.json', mode, encoding='utf-8') as f:
        json.dump(jsonContent, f, ensure_ascii=False, indent=4)

        f.close()

for category in structureDict:
    for endpoint in structureDict[category]:

        endpointFilename = endpoint

        if category in ["attribute", "types"]:
            endpointFilename = endpoint.replace("/", "_")

        url = url_X + endpoint

        params = {"versionId":Workspace_id,
                "includeAccessData":"true",
                  "includeAttributes":"true",
                  "includeLinks":"true"
                 }

        jsonResponse = requests.get(url, params=params, headers={"Authorization":accessToken}).json()

        writeContentToFile('a', customername, workspacename, category, endpointFilename, jsonResponse)

        try:
            jsonResponsePages = jsonResponse['pages']

            if int(jsonResponsePages) != 1:
                for i in range(2, jsonResponsePages+1, 1):

                    params["page"] = str(i)
                    jsonResponse = requests.get(url=url, params = params, headers={"Authorization":accessToken}).json()['results']

                    writeContentToFile('a', customername, workspacename, category, endpointFilename, jsonResponse)

        except:
            print(endpoint)
            next

A: I don't think I understood your question well. but from what I got I can help you this much:
for checking if exists you can use os.path.exists(path_to_file) and putting it in a while loop would give you ability to check for existence of your file name and assign a new one (Y_2) if needed
def writeContentToFile(mode, customername, workspacename, category, endpoint, jsonContent):
    path = os.path.join(os.getcwd(), customername, workspacename, category)
    Path(path).mkdir(parents=True, exist_ok=True)

    c = 1
    while os.path.exists(path + "/" + (endpoint if c == 1 else endpoint + f'_{c}') + '.json'): c += 1
    with open(path + "/" + (endpoint if c == 1 else endpoint + f'_{c}') + '.json', mode, encoding='utf-8') as f:
        json.dump(jsonContent, f, ensure_ascii=False, indent=4)

A: You just need to make a small change in your writeContentToFile function
import os
from datetime import datetime

def writeContentToFile(mode, customername, workspacename, category, endpoint, jsonContent):
    path = os.path.join(os.getcwd(), customername, workspacename, category)
    date = datetime. now(). strftime("%Y_%m_%d") #getting the current date

    new_endpoint=endpoint[:] #Creating a new endpoint value
    index=2 #setting the counter to 2

    while os.path.exists(os.path.join(path, new_endpoint)): #keep on checking Y_DATE_2 , Y_DATE_3 until filename is unique
        new_endpoint=endpoint+'_'+date+'_'+index
        index+=1

    Path(path).mkdir(parents=True, exist_ok=True)

    with open(path + "/" + new_endpoint + '.json', mode, encoding='utf-8') as f:
        json.dump(jsonContent, f, ensure_ascii=False, indent=4)

        f.close()

Explanation:
What we are doing is that first we are getting the current date as you need, then we are creating a new variable new_endpoint and then we are checking if the current filename exists and until it exists we will keep on adding _1, _2 ,_3... to the filename until we have a a filename which is unique.


text:
Q: Call a javascript function infinitely I'm new to JS , and I just wonder if it's possible to create kind of a loop with 2 functions .. example:
function a() {
    var myvar =1;
    b();
}
function b(){
    var myvar =2;
    a();
}
a();

I get this result when I try to run it "Uncaught SyntaxError: Unexpected end of input"

A: The method you're trying is very risky for a potential memory leak.
The method you should use is by calling setInterval. Where 3000 means the number milliseconds before each iteration.
setInterval(
    function(){
        alert("Hello");
    },
    3000
);

See https://www.w3schools.com/jsref/met_win_setinterval.asp

A: Yes you can do this, but there are a few things to keep in mind:

*

*This may cause a memory leak, and can slow your user's browser

*Looping between two functions without a delay will exceed maximum stack size

You could use setInterval of course, but it's not very flexible.
A function I like to use is written a little like this:
(function(delay, callback){
    var loop = function(){
        callback();
        setTimeout(loop, delay);
    }; loop();
})(1000, function(){console.log('Hello World!')});

It logs 'Hello World!' every 1000ms, or 1 second.
Another way to do this is by simply referencing itself in a timeout, like this:
function sayHello(){
    console.log('Hello World!');
    setTimeout(sayHello, 1000);
}; sayHello();

..or better yet, a permanent solution:
function loopFunction(delay, callback){
    var loop = function(){
        callback();
        setTimeout(loop, delay);
    }; loop();
};

loopFunction(1000, function(){console.log('Hello World!')});

To call two functions every other interval, you could either create a toggle switch, or call the second function a little bit later with setTimeout.


text:
Q: Stop $.ajax on beforeSend I have this jQuery ajax call:
$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(){
        if(1 == 1) //just an example
        {
            return false
        }
    },
    complete: function(){
        console.log('DONE');
    }
});

I want to stop the ajax call under the beforeSend if the condition returns true but return false does not stop the ajax call.
How can I stop the ajax call on the beforeSend?
======= UPDATE =========
return false works as well.

A: $.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr, opts){
        if(1 == 1) //just an example
        {
            xhr.abort();
        }
    },
    complete: function(){
        console.log('DONE');
    }
});

A: beforeSend:function(jqXHR,setting)
{
    // if(setting.url != "your url") jqXHR.abort();
    if(1 == 1) //just an example
    {
        jqXHR.abort();
    }
}

A: xhr.done();
this works for me
$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr){
        if(1 == 1) //just an example
        {
            return false
        };
        xhr.done(); //this works for me
    },
    complete: function(){
        console.log('DONE');
    }
});

http://api.jquery.com/jquery.ajax/
jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

A: Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort().
var test = $.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(){
        if(1 == 1) //just an example
        {
            test.abort();
            return false
        }
    },
    complete: function(){
        console.log('DONE');
    }
});


text:
Q: Automatic deployment of windows desktop application I work on commercial (windows) desktop application that is subjected to frequent changes, and is installed on multiple locations. Application should only be available to existing users. Until now each change was applied through downloaded installer. I would like to create some form of automatic update architecture.
I would like to know is there some built in windows solution to that problem, either through windows or .NET framework?

A: The usual way to do this is to update an application that is packaged into a Windows installer msi using group policy. Its quite easy to do as long as you're a doman admin in an AD domain.


text:
Q: Replace a content in a Text file in python From a text file want to replace the content to *
for example in a text file, I want to replace all the content after the password:

A: You can use this regex after reading and before writing.
import re
pattern = 'password'
string = file.read()
result = re.split(pattern, string)
newtext=result[0]


text:
Q: Installing mvtnorm package on new R 3.3.0 I'm using a linux server to run my R codes. Recently, the R software on the server has been updated to the newest 3.3.0 version. Since then, I've got a lot of problems installing different packages. In specific, I'm trying to simply install "mvtnorm" package by running:
install.packages("mvtnorm", repos="http://R-Forge.R-project.org", dependencies=T)

But I get an error:
ERROR: compilation failed for package 'mvtnorm'

The error is much longer. I'm copying below in case if you want to see more details.
I really appreciate your help as I'm completely clueless what to do.
Thanks,

Full Error:
install.packages("mvtnorm", repos="http://R-Forge.R-project.org", dependencies=T)
Installing package into '/home/akhavans/R/x86_64-redhat-linux-gnu-library/3.3'
(as 'lib' is unspecified)
trying URL 'http://R-Forge.R-project.org/src/contrib/mvtnorm_1.0-5.tar.gz'
Content type 'application/x-gzip' length 337237 bytes (329 KB)
==================================================
downloaded 329 KB

* installing *source* package 'mvtnorm' ...
** libs
gcc -m64 -std=gnu99 -I/usr/include/R -DNDEBUG  -I/usr/local/include    -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fpic -fPIC   -c C_FORTRAN_interface.c -o C_FORTRAN_interface.o
gcc -m64 -std=gnu99 -I/usr/include/R -DNDEBUG  -I/usr/local/include    -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fpic -fPIC   -c miwa.c -o miwa.o
gfortran -m64   -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -I/usr/lib64/gfortran/modules  -c mvt.f -o mvt.o
mvt.f:5.72:

     &                   MAXPTS, ABSEPS, RELEPS, ERROR, VALUE, INFORM )
                                                                        1
Warning: Line truncated at (1)
mvt.f:86.33:

      SUBROUTINE MVSUBR( N, W, NF, F )
                                 1
Warning: Unused dummy argument 'nf' at (1)
mvt.f:200.72:

      SUBROUTINE MVVLSB( N,W,R,DL,INFI, A,B,COV, Y, DI,EI, ND, VALUE )
                                                                        1
Warning: Line truncated at (1)
mvt.f:368.72:

                  IF ( INFI(I) .NE. 0 ) Y(I) =        MVTDNS( 0, AMIN )
                                                                        1
Warning: Line truncated at (1)
mvt.f:369.72:

                  IF ( INFI(I) .NE. 1 ) Y(I) = Y(I) - MVTDNS( 0, BMIN )
                                                                        1
Warning: Line truncated at (1)
mvt.f:874.72:

      DOUBLE PRECISION FUNCTION MVBVT( NU, LOWER, UPPER, INFIN, CORREL )
                                                                        1
Warning: Line truncated at (1)
mvt.f:1045.72:

         bvt = atan2(-snu*(hkn*qhrk+hpk*hkrn),hkn*hkrn-nu*hpk*qhrk)/tpi
                                                                        1
Warning: Line truncated at (1)
mvt.f:1199.72:

> install.packages("mvtnorm", repos="http://R-Forge.R-project.org", dependencies=T)
Installing package into '/home/akhavans/R/x86_64-redhat-linux-gnu-library/3.3'
(as 'lib' is unspecified)
trying URL 'http://R-Forge.R-project.org/src/contrib/mvtnorm_1.0-5.tar.gz'
Content type 'application/x-gzip' length 337237 bytes (329 KB)
==================================================
downloaded 329 KB

* installing *source* package 'mvtnorm' ...
** libs
gcc -m64 -std=gnu99 -I/usr/include/R -DNDEBUG  -I/usr/local/include    -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fpic -fPIC   -c C_FORTRAN_interface.c -o C_FORTRAN_interface.o
gcc -m64 -std=gnu99 -I/usr/include/R -DNDEBUG  -I/usr/local/include    -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fpic -fPIC   -c miwa.c -o miwa.o
gfortran -m64   -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -I/usr/lib64/gfortran/modules  -c mvt.f -o mvt.o
mvt.f:5.72:

     &                   MAXPTS, ABSEPS, RELEPS, ERROR, VALUE, INFORM )
                                                                        1
Warning: Line truncated at (1)
mvt.f:86.33:

      SUBROUTINE MVSUBR( N, W, NF, F )
                                 1
Warning: Unused dummy argument 'nf' at (1)
mvt.f:200.72:

      SUBROUTINE MVVLSB( N,W,R,DL,INFI, A,B,COV, Y, DI,EI, ND, VALUE )
                                                                        1
Warning: Line truncated at (1)
mvt.f:368.72:

                  IF ( INFI(I) .NE. 0 ) Y(I) =        MVTDNS( 0, AMIN )
                                                                        1
Warning: Line truncated at (1)
mvt.f:369.72:

                  IF ( INFI(I) .NE. 1 ) Y(I) = Y(I) - MVTDNS( 0, BMIN )
                                                                        1
Warning: Line truncated at (1)
mvt.f:874.72:

      DOUBLE PRECISION FUNCTION MVBVT( NU, LOWER, UPPER, INFIN, CORREL )
                                                                        1
Warning: Line truncated at (1)
mvt.f:1045.72:

         bvt = atan2(-snu*(hkn*qhrk+hpk*hkrn),hkn*hkrn-nu*hpk*qhrk)/tpi
                                                                        1
Warning: Line truncated at (1)
mvt.f:1199.72:

         FINEST(K) = FINEST(K) + ( FINVAL(K) - FINEST(K) )/( 1+VARPRD )
                                                                        1
Warning: Line truncated at (1)
mvt.f:1391.72:

            VALUES(J) = VALUES(J) + ( FS(J) - VALUES(J) )/( 2*K-1 )
                                                                        1
Warning: Line truncated at (1)
gcc -m64 -std=gnu99 -I/usr/include/R -DNDEBUG  -I/usr/local/include    -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fpic -fPIC   -c mvtnorm-init.c -o mvtnorm-init.o
gfortran -m64   -fpic  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -I/usr/lib64/gfortran/modules  -c tvpack.f -o tvpack.o
tvpack.f:65.52:

      DOUBLE PRECISION ONE, ZRO, EPS, ZROS(3), HS(3), TVT, TVTL
                                                    1
Warning: Unused variable 'hs' declared at (1)
tvpack.f:65.45:

      DOUBLE PRECISION ONE, ZRO, EPS, ZROS(3), HS(3), TVT, TVTL
                                             1
Warning: Unused variable 'zros' declared at (1)
tvpack.f: In function 'adonet':
tvpack.f:201: warning: 'fin' may be used uninitialized in this function
gcc -m64 -std=gnu99 -shared -L/usr/lib64/R/lib -ldl -lpthread -lc -lrt -lcurl -lidn -lssh2 -lssh2 -lssl -lcrypto -lssl -lcrypto -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lldap -lz -lrt -o mvtnorm.so C_FORTRAN_interface.o miwa.o mvt.o mvtnorm-init.o tvpack.o -ldl -lpthread -lrt /builddir/build/BUILD/R-3.3.0/zlib-1.2.8/target/usr/lib64/libz.a /builddir/build/BUILD/R-3.3.0/bzip2-1.0.6/target/usr/lib64/libbz2.a /builddir/build/BUILD/R-3.3.0/xz-5.2.2/target/usr/lib64/liblzma.a /builddir/build/BUILD/R-3.3.0/pcre-8.38/target/usr/lib64/libpcre.a /builddir/build/BUILD/R-3.3.0/curl-7.48.0/target/usr/lib64/libcurl.a -lcurl -lidn -lssh2 -lssl -lcrypto -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lldap -lz -lgfortran -lm -L/usr/lib64/R/lib -lR
gcc: /builddir/build/BUILD/R-3.3.0/zlib-1.2.8/target/usr/lib64/libz.a: No such file or directory
gcc: /builddir/build/BUILD/R-3.3.0/bzip2-1.0.6/target/usr/lib64/libbz2.a: No such file or directory
gcc: /builddir/build/BUILD/R-3.3.0/xz-5.2.2/target/usr/lib64/liblzma.a: No such file or directory
gcc: /builddir/build/BUILD/R-3.3.0/pcre-8.38/target/usr/lib64/libpcre.a: No such file or directory
gcc: /builddir/build/BUILD/R-3.3.0/curl-7.48.0/target/usr/lib64/libcurl.a: No such file or directory
make: *** [mvtnorm.so] Error 1
ERROR: compilation failed for package 'mvtnorm'
* removing '/home/akhavans/R/x86_64-redhat-linux-gnu-library/3.3/mvtnorm'

The downloaded source packages are in
    '/lv_scratch/tmp/RtmpbuSB0J/downloaded_packages'
Warning message:
In install.packages("mvtnorm", repos = "http://R-Forge.R-project.org",  :
  installation of package 'mvtnorm' had non-zero exit status


text:
Q: Threejs drag points I have to generate a huge number of objects that I can drag individually. Also these objects are limited to a plane form (e.g. rect or circle).
At first I worked with simple CircleGeometries, that are placed inside another geometrie (plane). Also dragging them is very easy but as expected the performance is very very poor for about 200000 of them.
I then decided to use points /particleSystem. The positioning inside a plane works very well but I can't get it managed to make the individual points of the particle system draggable. I found the interactive particles example in the threejs documentation but still have no clou, how to combine them with dragcontrols.
This is my code for creating the particle system and fill a plane with these points:
//Create a plane geometrie, that is later filled with points
var geometry2 = new THREE.CircleGeometry(30,32);
var material2 = new THREE.MeshBasicMaterial( {color: 0x666666, side: THREE.DoubleSide, wireframe:true} );
var mat1 = new THREE.MeshBasicMaterial( {color: 0x00ff00, wireframe:false} );
var plane1 = new THREE.Mesh(geometry2, material2);
geometries.push(plane1);    //push to object for draggable elements
scene.add(plane1);

var positionsX;

       positionsX = inGeometry.inGeometry(plane1.geometry,  200000); // get positions for points inside plane1

      var geometry = new THREE.Geometry();
      for (var i = 0; i < positionsX.length; i++) {
                geometry.vertices.push(positionsX[i]);  //add positions to vertices

      }
      console.log(geometry);

      //Create Particle system
      var material = new THREE.PointsMaterial({ size:0.02, color: 0xffffff });
      particleSystem = new THREE.Points(geometry, material);
      scene.add(particleSystem);
      console.log(particleSystem);

  var dragGeo = new DragControls(geometries, camera, container); //dragging

Can anybody please help?
Thanks

A:
Just a rough example of how you can drag points:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(1.25, 7, 7);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.PlaneBufferGeometry(10, 10, 10, 10);
geometry.rotateX(-Math.PI * 0.5);

var plane = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
  wireframe: true,
  color: "red"
}));
scene.add(plane);

var points = new THREE.Points(geometry, new THREE.PointsMaterial({
  size: 0.25,
  color: "yellow"
}));
scene.add(points);

var raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 0.25;
var mouse = new THREE.Vector2();
var intersects = null;
var plane = new THREE.Plane();
var planeNormal = new THREE.Vector3();
var currentIndex = null;
var planePoint = new THREE.Vector3();
var dragging = false;

window.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mousemove", mouseMove, false);
window.addEventListener("mouseup", mouseUp, false);

function mouseDown(event) {
  setRaycaster(event);
  getIndex();
  dragging = true;
}

function mouseMove(event) {
  if (dragging && currentIndex !== null) {
    setRaycaster(event);
    raycaster.ray.intersectPlane(plane, planePoint);
    geometry.attributes.position.setXYZ(currentIndex, planePoint.x, planePoint.y, planePoint.z);
    geometry.attributes.position.needsUpdate = true;
  }
}

function mouseUp(event) {
  dragging = false;
  currentIndex = null;
}

function getIndex() {
  intersects = raycaster.intersectObject(points);
  if (intersects.length === 0) {
    currentIndex = null;
    return;
  }
  currentIndex = intersects[0].index;
  setPlane(intersects[0].point);
}

function setPlane(point) {
  planeNormal.subVectors(camera.position, point).normalize();
  plane.setFromNormalAndCoplanarPoint(planeNormal, point);
}

function setRaycaster(event) {
  getMouse(event);
  raycaster.setFromCamera(mouse, camera);
}

function getMouse(event) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/91/three.min.js"></script>


text:
Q: Xcode C++ Project - Set custom entry point Where can I set entry point for my C++ Xcode project?
In Visual Studio I set the entry point in the project's properties under the "Linker" menu.
I could not find that in Xcode.


text:
Q: Must Understand check failed for header soapenv error in communicating with WAS I am calling a java webservice sitting on Websphere Application Server(WAS) from Websphere Enterprise Service Bus(WESB).
Provider has enabled security using JAAS.
So,I created WS-Security username token client policy set for my module.
The trace of my outbound call from WESB looks like
<soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<s:Security xmlns:s="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soapenv:mustUnderstand="1">
  <s:UsernameToken>
    <s:Username>**username**</s:Username>
    <s:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">**password**</s:Password>
  </s:UsernameToken>
</s:Security>

But the provider is expecting the Security payload to be sent as below with some namespace in Username tag
<soapenv:Header>
  <wsse:Security wsse:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
     <wsse:UsernameToken>
        <wsse:Username wsu:Id="UsernameToken-1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">**username**</wsse:Username>
        <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">**password**</wsse:Password>
     </wsse:UsernameToken>
  </wsse:Security>

I am getting the below error while invoking the java service
AxisEngine    E org.apache.axis2.engine.AxisEngine receive Must Understand check failed for header soapenv : {http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security
                                 org.apache.axis2.AxisFault: Must Understand check failed for header soapenv : {http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security
    at org.apache.axis2.jaxws.handler.HandlerUtils.checkUnprocessed(HandlerUtils.java:196)
    at org.apache.axis2.jaxws.handler.HandlerUtils.checkMustUnderstand(HandlerUtils.java:163)
    at org.apache.axis2.jaxws.server.EndpointController.inboundHeaderAndHandlerProcessing(EndpointController.java:363)
Is it the correct way to handle JAAS by creating WS Security client policy set or do I have to handle in different way.

A: That wsu namespace that is on that UsernameToken in the 2nd example is there for wsu:Id.  The wsu:Id is only needed if something will reference the element.  You have nothing referencing the element, so it is not required.
If you were getting an error because the security handler didn't like the fact that the wsu:Id was missing, you would get a SoapSecurityException, not a MustUnderstand check.
A MustUnderstand check means that you have sent a header for which no handler in the runtime has marked as processed.  Either there is no handler registered to handle it or no registered handler marked the header.  For security headers, this usually means that there are no WS-Security constraints applied.
You can verify that there are no WS-Security constraints applied by sending a message with no Security header.
If you send a message that includes a Security header like your 2nd example?
Do you have security constraints on you client for responses?  You will get this same error if you have no constraints for responses but the server sent a Security header in the response.
This is what I would do:
1) Enable a WS-Security trace on the WAS server
com.ibm.ws.webservices.wssecurity.=all:com.ibm.wsspi.wssecurity.=all:com.ibm.ws.wssecurity.=all:com.ibm.websphere.wssecurity.=all:com.ibm.xml.soapsec.=all:com.ibm.ws.webservices.trace.=all:com.ibm.ws.websvcs.trace.=all:com.ibm.ws.wssecurity.platform.audit.=off:com.ibm.ws.webservices.multiprotocol.AgnosticService=all:com.ibm.ws.websvcs.utils.SecurityContextMigrator=all
2) Restart the server
3) Send the message from the client
4) Search the trace for 'bound http'.
4a) You should see the Inbound HTTP SOAP Request
4b) search again
4c) You should see Outbound HTTP SOAP Response
4ci) Does the response have the expected response or a fault?
4cii) If the response is a fault, then you have a server issue
4cii) If the expected response, does the response contain a Security header?
4ciii) If yes, then the MustUnderstand check came from the client and you most likely need to apply security response constraints to your client.
5) If, in step 4, you determined that you have a server issue, search backwards in the trace for something that looks like this (on the current thread):
WSSecurityCon 3   isServerSide == true
WSSecurityCon 3   No PolicyType Binding
5a) If you see this, then you do not have security constraints applied to your provider application.  Here are some instructions for applying a UsernameToken policy in WebSphere (assuming that your app is JAX-WS):
https://www-01.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/twbs_stand_alone_security_token.html
And for those that delete my posts because they have links:
Configuring a policy set and bindings for a stand-alone security token (UsernameToken or LTPA Token)
You can secure web services by configuring the message-level WS-Security policy set and bindings for a stand-alone security token that is either a Lightweight Third Party Authentication (LTPA) token or a Username token.
Before you begin
This task assumes that the service provider and client that you are configuring are in the JaxWSServicesSamples application. See the documentation on accessing samples to learn how to obtain and install this application. Specify the following trace specification on your server to enable you to debug any future configuration problems that might occur.
=info:com.ibm.wsspi.wssecurity.=all:com.ibm.ws.webservices.wssecurity.=all:
com.ibm.ws.wssecurity.=all: com.ibm.xml.soapsec.=all: com.ibm.ws.webservices.trace.=all:
com.ibm.ws.websvcs.trace.=all:com.ibm.ws.wssecurity.platform.audit.=off:
If LTPA tokens are used, you must enable the application security on the application servers that are used for both the client and the service.
About this task
This topic describes how to configure a WS-Security policy set and provider bindings for a Username token or an LTPA token. For simplicity, this procedure demonstrates how to remove the timestamp, digital signature, and encryption attributes from the policy; however, you might want to include these attributes in your final configuration. To learn more, see the documentation on configuring a policy set and bindings for Asymmetric XML digital signature or XML encryption with client and provider application specific bindings.
In this task, default provider general bindings are used for the provider application to consume the tokens. If a caller configuration is required, an application-specific binding will be added for the provider.

Procedure
Create the custom policy set.
    In the administrative console, click Services > Policy sets > Application Policy sets.
    Click New.
    Specify Name = OneTokenPolicy.
    Click Apply.
    Under Policies, click Add > WS-Security.
Edit the custom policy set
    Remove digital signature, encryption, and timestamp.
        In the administrative console, clickWS-Security > Main Policy.
        Deselect Message level protection.
        Click Apply.
    Add the UsernameToken or LTPA token.
        Under Policy details, click Request token policies.
        Select Add Token Type.
        If you want to use a UsernameToken, select UserName. If you want to use an LTPA token, select LTPA.

        Token name=myToken.
        Click OK.
Configure the client to use the OneTokenPolicy policy set.
    In the administrative console, click Applications > Application types > WebSphere enterprise applications > JaxWSServicesSamples > Service client policy sets and bindings.
    Select the web services client resource.
    Click Attach Policy Set.
    Select OneTokenPolicy .
Create a custom binding for the client.
    Select the web services resource again.
    Click Assign Binding.
    Click New Application Specific Binding to create an application-specific binding
    Specify the bindings configuration name. name: oneTokenClientBinding
    Click Add > WS-Security
    If the Main Message Security Policy Bindings' panel does not display, select WS-Security.
Edit the custom binding for the client.
    Edit the identity token generator to send the identity username.
        Click request:myToken.
        Click Apply.
        Click Callback handler. User name=(yourUserid) Password=(yourPassword)
    Avoid trouble Avoid trouble: This is a userid/password that is valid on the user registry on the provider's system. If you are using LTPA tokens, the userid/password must be valid on both the consumer and provider registries.
    (Optional) If configuring a UsernameToken, add the following WS-Security custom properties:

    *com.ibm.wsspi.wssecurity.token.username.addNonce=true
    *com.ibm.wsspi.wssecurity.token.username.addTimestamp=true

    These custom properties are added because they are specified on the UsernameToken consumer default general bindings. If we do not specify those properties here, you will either need to remove those properties from the default provider general bindings or create application-specific bindings for the provider that does not include those properties.
    Click OK.
    Click Save
Configure the provider to use the OneTokenPolicy policy set.
    In the administrative console, click Applications > Application types > WebSphere enterprise applications > JaxWSServicesSamples > Service provider policy sets and bindings
    Select the web services provider resource (OneTokenPolicy)
    Click Attach Policy Set.
    Select OneTokenPolicy
    Note: Since no bindings are attached to the provider application, it will use the default provider general bindings for the token consumers.
(Optional) If you want to create a Caller configuration for the provider, create custom bindings for the provider.
    Select the web services provider resource again.
    Click Assign Binding
    Click New Application Specific Binding to create an application-specific binding
    Specify Bindings configuration name:oneTokenProvBinding
    Click Add > WS-Security
    If the Main Message Security Policy Bindings' Panel does not display, select WS-Security
(Optional) If a Caller configuration will be created, edit the custom bindings for the provider.
    Click Caller > New. Name: myCaller.
        If using a UsernameToken, enter the following:
            Caller identity local name: http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#UsernameToken
        If using an LTPA token, enter the following:
            Caller identity local name: LTPAv2
            Caller identity local URI: http://www.ibm.com/websphere/appserver/tokentype
    Click OK.
Click Save to save your configuration changes.
Restart the client provider.
    Stop the client and the provider
    Restart the client and the provider
Test the Service.
    Point your web browser at the JaxWSServicesSamples: http://localhost:9080/wssamplesei/demo
    Avoid trouble Avoid trouble: Make sure you provide the correct hostname and port if your profile is not on the same machine or the port is not 9080.
    Select Message Type Synchronous Echo
    Make sure Use SOAP 1.2 is not selected
    Enter a message and click Send Message. The sample application should reply with JAXWS==>Message.

Results

The JaxWSServicesSamples web services application is configured to generate and consume a UsernameToken or LTPA token in the request message.


text:
Q: Python auto completion in Visual Studio 2015 I have a trouble in Python auto completion in Visual Studio 2015 (not VS Code).
When I use another library(?) such as tensorflow,
tensorflow's functions and variables are helped by Visual Studio's intellisense and work well.
But Python's basic functions are not helped by intellisense (e.g. print(), import). When Ctrl+space is pressed they show up, but not automatically. So I always have to type print() fully or press Ctrl+space all time.
I really want to make them (e.g. print(), import, def) shown up automatically.


text:
Q: Retrieve DIV-content inside a Form I have been searching for help from various forums and similar posts, but without any progress.
I have three pages, one that lets me insert information about projects into my database, a second that show the images and names of every project in the database, and a third page which I want to have a function that shows the image and name of the selected project in the second page.
Code on the second page(dashboardadmin.php):
<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

$conn = mysqli_connect("localhost","root","","wildfire");

if(mysqli_connect_errno())
{
    echo mysqli_connect_error();
}

$sql= "SELECT pid, project_name, image, image_type FROM project";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_array()) {

echo "<form action='omprojekt.php' method='post'>

    "." ".$row['project_name']."

    <input type='submit' name='submit' value='Choose' />
   </form>";

}
}

else {
    echo "0 results";
}

mysqli_close($conn);

        ?>

Code on the third page (omprojekt.php):
<?php
   /* Tried both of the $val variables but of course only one at a time. This is only to show you what I have tried. */

$val = isset($_POST['comp']) ? $_POST['comp'] : '';
$val = $_POST['comp'];

if(isset($_POST['submit'])){

echo "$val";
}

?>

In the last code you can see that I have two $val variables, but I have only used one of them at a time in my codes. The purpose of showing both of them here is to show you that I have tried both of them.
What I want to do is to make the third page show the image and name of the selected project in the second page. As you see, I have tried to retrieve the content from the DIV using the same "name". The problem is that the third page(omprojekt.php) doesn't show any content at all, and not even any errors.

A: You're expecting the div to submit like an input, but it won't, because it's not an input. So put it in an input.
if ($result->num_rows > 0) {
    while($row = $result->fetch_array()) {
        // Don't use and id attribute because you're in a loop and you might have multiple id's with the same value.
        echo "<form action='omprojekt.php' method='post'>

                "." ".$row['project_name']."

            <input type='hidden' name='pid' value='".$row['pid']."'>
            <input type='hidden' name='project_name' value='".$row['project_name']."'>
            <input type='submit' name='submit' value='Choose' />
       </form>";
    }
}

Then on the next page,
$val = (isset($_POST['pid']) && isset($_POST['project_name'])) ?
    " {$_POST['project_name']}" : '';

For the sake of completeness, there are a few other things wrong with your code.
1) The width and height attributes on the iamge should have quotes, and do not accept "px", they are just numbers. If you want to use "px" you should use style instead.
2) You should be escaping user input before running it through your query.

A: Data will only be sent from a <form> to the action script if it exists in an <input...> HTML tag. You cannot pick data out of randon
 tags etc.
So you could do this by using a hidden input field like this ( this is only one way )
if ($result->num_rows > 0) {
    while($row = $result->fetch_array()) {

       echo "<form action='omprojekt.php' method='post'>

                 " .
                  $row['project_name']."

             <input type='hidden' name='comp' value='" . $row['pid'] . "' />
             <input type='submit' name='submit' value='Choose' />
             </form>";

    }
}

Now when you get to omprojekt.php the $_POST['comp'] variable will exist.
You can have as many hidden input fields as you like so if you want to pass the project_name as well just add another hidden field.


text:
Q: Is there anything wrong with passing a message to the user using a query parameter? Currently, in my node JavaScript application, I use the query parameters that you can pass to a route to display a message to the user.
For instance, I may redirect the user after an operation to /profile?message=Profile Updated and pass req.query.message into my view and display the message.
Is there anything inherently wrong with this approach for handling messages to the user? I like this approach as it doesn't require any additional modules and dependencies to work.