问:
Oracle Object Relational Database inserting records into a table with reference to a derived table
I have the following structure below and I want to add a record into project table. The problem with the following INSERT is that on the place of customer_t I have to select a record from user table while inserting but I want to select only customers (and not staff members). Basically customer_t and staff_t inherit from user_t (table: user).

You can look at same insert but for service_t, it works fine because I'm selecting from a table, but in this case, there is no table for customer.

I'm not so experience with this ORM. Any idea how to solve it?

```<code>INSERT INTO project VALUES (
  1,
  'Project name',
  'Description',
  ( SELECT REF(u) AS customer_t
    FROM   "USER" u
    WHERE  idno = 1
    AND    VALUE(u) IS OF TYPE (customer_t)
  ),
  ( SELECT REF(s) FROM service s WHERE serviceno = 1)
);
</code>```

Error message:

```<code>Error starting at line : 1 in command -
INSERT INTO project VALUES (1, 'Project name', 'Logo', (SELECT REF(u) AS customer_t FROM "USER" u WHERE idno = 1 AND VALUE(u) IS OF TYPE (customer_t)), (SELECT REF(s) FROM service s WHERE serviceno = 1))
Error at Command Line : 1 Column : 72
Error report -
SQL Error: ORA-00932: inconsistent datatypes: expected REF C##EX_TEST.CUSTOMER_T got REF C##EX_TEST.USER_T
00932. 00000 -  "inconsistent datatypes: expected %s got %s"
*Cause:
*Action:
</code>```

SQL:

CREATE TYPE name_t AS OBJECT (
  first_name     VARCHAR2(32),
  last_name      VARCHAR2(32)
);

CREATE TYPE address_t AS OBJECT (
  province       VARCHAR2(32),
  street         VARCHAR2(32),
  city           VARCHAR2(32),
  postal_code    VARCHAR2(10)
);

CREATE TYPE user_t AS OBJECT (
  idno           NUMBER,
  email          VARCHAR2(40),
  password       VARCHAR2(32),
  name           name_t,
  address        address_t,
  phone          VARCHAR2(15),
  MAP MEMBER FUNCTION get_idno RETURN NUMBER
) NOT FINAL;

CREATE TYPE rank_t AS OBJECT (
  rankno       NUMBER,
  name         VARCHAR2(40),
  description  VARCHAR2(60)
);

CREATE TABLE "RANK" OF rank_t (
  PRIMARY KEY (rankno),
  UNIQUE (name)
);

INSERT INTO "RANK" VALUES (1, 'User', 'Simple a user');
INSERT INTO "RANK" VALUES (2, 'Manager', 'Manager');
INSERT INTO "RANK" VALUES (3, 'Administrator', 'Admin');

CREATE TYPE customer_t UNDER user_t (

);

CREATE TYPE staff_t UNDER user_t (
  salary       NUMBER(7,2),
  rank         REF rank_t
);

CREATE TABLE "USER" OF user_t (
  PRIMARY KEY (idno),
  UNIQUE (email));

CREATE TYPE service_t AS OBJECT (
  serviceno    NUMBER,
  name         VARCHAR2(40),
  description  VARCHAR2(60)
);

CREATE TABLE service OF service_t (PRIMARY KEY (serviceno));

CREATE TYPE project_t AS OBJECT (
  projectno    NUMBER,
  name         VARCHAR2(40),
  description  VARCHAR2(60),
  customer     REF customer_t,
  service      REF service_t
);

CREATE TABLE project OF project_t (PRIMARY KEY (projectno));
```

答:
You don't need a separate table for a customers; just insert the types into the USER table.

If you want to put a customer in then insert a customer_t type:

INSERT INTO "USER" VALUES(
  customer_t(
    1,
    'person1@customer.example.com',
    'abcdefg',
    name_t( 'One', 'Uno' ),
    address_t( 'province','street', 'city', '12345' ),
    '0123456789'
  )
);
```

<p>If you want to insert a user then use <code>user_t</code> or insert values without a type:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO "USER" VALUES(
    2,
    'person2@user.example.com',
    'abcdefg',
    name_t( 'Two', 'Dos' ),
    address_t( 'province','street', 'city', '12345' ),
    '0123456789'
);
</code>```

If you want to insert a staff member then use staff_t:

INSERT INTO "USER" VALUES(
  staff_t(
    3,
    'person3@staff.example.com',
    'abcdefg',
    name_t( 'Three', 'Tres' ),
    address_t( 'province','street', 'city', '12345' ),
    '0123456789',
    12345.67,
    (SELECT REF(r) FROM "RANK" r WHERE rankno = 2 )
  )
);
```

<p>Then the data will have the correct types (which you can extract using <code>SYS.ANYDATA</code>) and use the <code>TREAT</code> function to convert a super-type to a sub-type:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT idno,
       email,
       SYS.ANYDATA.getTypeName( SYS.ANYDATA.convertObject( VALUE(u) ) ) As type,
       TREAT(VALUE(u) AS staff_t).salary AS salary,
       TREAT(VALUE(u) AS staff_t).rank.name AS rank
FROM   "USER" u
</code>```

outputs:

```
IDNO | EMAIL                        | TYPE                                   |   SALARY | RANK
---: | :--------------------------- | :------------------------------------- | -------: | :------
   1 | person1@customer.example.com | FIDDLE_KPHUNVHPVRKOYQBWVAQS.CUSTOMER_T |     <em>null</em> | <em>null</em>
   2 | person2@user.example.com     | FIDDLE_KPHUNVHPVRKOYQBWVAQS.USER_T     |     <em>null</em> | <em>null</em>
   3 | person3@staff.example.com    | FIDDLE_KPHUNVHPVRKOYQBWVAQS.STAFF_T    | 12345.67 | Manager
```

and:

SELECT idno,
       email
FROM   "USER" u
WHERE  VALUE(u) IS OF TYPE (customer_t)
```

<p>outputs:</p>

<blockquote>
```
IDNO | EMAIL
---: | :---------------------------
   1 | person1@customer.example.com
```
</blockquote>

<p>and your insert needs to convert the <code>REF</code> from the <code>user_t</code> super-type to the <code>customer_t</code> sub-type using the <code>TREAT</code> function:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO project VALUES (
  1,
  'Project name',
  'Description',
  ( SELECT TREAT( REF(u) AS REF customer_t )
    FROM   "USER" u
    WHERE  idno = 1
    AND    VALUE(u) IS OF TYPE (customer_t)
  ),
  ( SELECT REF(s) FROM service s WHERE serviceno = 1)
);
</code>```

db<>fiddle here

Body:
I have the following structure below and I want to add a record into project table. The problem with the following INSERT is that on the place of customer_t I have to select a record from user table while inserting but I want to select only customers (and not staff members). Basically customer_t and staff_t inherit from user_t (table: user).

You can look at same insert but for service_t, it works fine because I'm selecting from a table, but in this case, there is no table for customer.

I'm not so experience with this ORM. Any idea how to solve it?

INSERT INTO project VALUES (
  1,
  'Project name',
  'Description',
  ( SELECT REF(u) AS customer_t
    FROM   "USER" u
    WHERE  idno = 1
    AND    VALUE(u) IS OF TYPE (customer_t)
  ),
  ( SELECT REF(s) FROM service s WHERE serviceno = 1)
);

Error message:

Error starting at line : 1 in command -
INSERT INTO project VALUES (1, 'Project name', 'Logo', (SELECT REF(u) AS customer_t FROM "USER" u WHERE idno = 1 AND VALUE(u) IS OF TYPE (customer_t)), (SELECT REF(s) FROM service s WHERE serviceno = 1))
Error at Command Line : 1 Column : 72
Error report -
SQL Error: ORA-00932: inconsistent datatypes: expected REF C##EX_TEST.CUSTOMER_T got REF C##EX_TEST.USER_T
00932. 00000 -  "inconsistent datatypes: expected %s got %s"
*Cause:
*Action:

SQL:

CREATE TYPE name_t AS OBJECT (
  first_name     VARCHAR2(32),
  last_name      VARCHAR2(32)
);

CREATE TYPE address_t AS OBJECT (
  province       VARCHAR2(32),
  street         VARCHAR2(32),
  city           VARCHAR2(32),
  postal_code    VARCHAR2(10)
);

CREATE TYPE user_t AS OBJECT (
  idno           NUMBER,
  email          VARCHAR2(40),
  password       VARCHAR2(32),
  name           name_t,
  address        address_t,
  phone          VARCHAR2(15),
  MAP MEMBER FUNCTION get_idno RETURN NUMBER
) NOT FINAL;

CREATE TYPE rank_t AS OBJECT (
  rankno       NUMBER,
  name         VARCHAR2(40),
  description  VARCHAR2(60)
);

CREATE TABLE "RANK" OF rank_t (
  PRIMARY KEY (rankno),
  UNIQUE (name)
);

INSERT INTO "RANK" VALUES (1, 'User', 'Simple a user');
INSERT INTO "RANK" VALUES (2, 'Manager', 'Manager');
INSERT INTO "RANK" VALUES (3, 'Administrator', 'Admin');

CREATE TYPE customer_t UNDER user_t (

);

CREATE TYPE staff_t UNDER user_t (
  salary       NUMBER(7,2),
  rank         REF rank_t
);

CREATE TABLE "USER" OF user_t (
  PRIMARY KEY (idno),
  UNIQUE (email));

CREATE TYPE service_t AS OBJECT (
  serviceno    NUMBER,
  name         VARCHAR2(40),
  description  VARCHAR2(60)
);

CREATE TABLE service OF service_t (PRIMARY KEY (serviceno));

CREATE TYPE project_t AS OBJECT (
  projectno    NUMBER,
  name         VARCHAR2(40),
  description  VARCHAR2(60),
  customer     REF customer_t,
  service      REF service_t
);

CREATE TABLE project OF project_t (PRIMARY KEY (projectno));

Body:
You don't need a separate table for a customers; just insert the types into the USER table.

If you want to put a customer in then insert a customer_t type:

INSERT INTO "USER" VALUES(
  customer_t(
    1,
    'person1@customer.example.com',
    'abcdefg',
    name_t( 'One', 'Uno' ),
    address_t( 'province','street', 'city', '12345' ),
    '0123456789'
  )
);

If you want to insert a user then use user_t or insert values without a type:

INSERT INTO "USER" VALUES(
    2,
    'person2@user.example.com',
    'abcdefg',
    name_t( 'Two', 'Dos' ),
    address_t( 'province','street', 'city', '12345' ),
    '0123456789'
);

If you want to insert a staff member then use staff_t:

INSERT INTO "USER" VALUES(
  staff_t(
    3,
    'person3@staff.example.com',
    'abcdefg',
    name_t( 'Three', 'Tres' ),
    address_t( 'province','street', 'city', '12345' ),
    '0123456789',
    12345.67,
    (SELECT REF(r) FROM "RANK" r WHERE rankno = 2 )
  )
);

Then the data will have the correct types (which you can extract using SYS.ANYDATA) and use the TREAT function to convert a super-type to a sub-type:

SELECT idno,
       email,
       SYS.ANYDATA.getTypeName( SYS.ANYDATA.convertObject( VALUE(u) ) ) As type,
       TREAT(VALUE(u) AS staff_t).salary AS salary,
       TREAT(VALUE(u) AS staff_t).rank.name AS rank
FROM   "USER" u

outputs:

IDNO | EMAIL                        | TYPE                                   |   SALARY | RANK
---: | :--------------------------- | :------------------------------------- | -------: | :------
   1 | person1@customer.example.com | FIDDLE_KPHUNVHPVRKOYQBWVAQS.CUSTOMER_T |     null | null
   2 | person2@user.example.com     | FIDDLE_KPHUNVHPVRKOYQBWVAQS.USER_T     |     null | null
   3 | person3@staff.example.com    | FIDDLE_KPHUNVHPVRKOYQBWVAQS.STAFF_T    | 12345.67 | Manager

and:

SELECT idno,
       email
FROM   "USER" u
WHERE  VALUE(u) IS OF TYPE (customer_t)

outputs:

IDNO | EMAIL
---: | :---------------------------
   1 | person1@customer.example.com

and your insert needs to convert the REF from the user_t super-type to the customer_t sub-type using the TREAT function:

INSERT INTO project VALUES (
  1,
  'Project name',
  'Description',
  ( SELECT TREAT( REF(u) AS REF customer_t )
    FROM   "USER" u
    WHERE  idno = 1
    AND    VALUE(u) IS OF TYPE (customer_t)
  ),
  ( SELECT REF(s) FROM service s WHERE serviceno = 1)
);

db<>fiddle here


来源: stackexchange

问:
Adding NSMutableArray A to NSMutableArray B, and then doing "removeAllObjects" on A, clears B too?
```<code>A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];
</code>```

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?

答: It is highly likely that they could be referencing the same objects. Can you check if they are?</p>

ContentLicense: CC BY-SA 3.0

Body:
A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?


问:
Set videoview position in constraint layout
main_acitivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
    <!--suppress ALL -->
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:id="@+id/main"
        tools:context=".MainActivity"
        android:layout_gravity="center"
        android:gravity="center">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Then in java I do the next

```<code>vv = (VideoView) findViewById(R.id.videoView1);

ConstraintLayout.LayoutParams pararams = (ConstraintLayout.LayoutParams) vv.getLayoutParams();
int ch=vv.getHeight();
pararams.height = vv.getWidth();

vv.setLayoutParams(pararams);
</code>```

HOW TO MAKE ELEMENT VERTICALLY CENTERED AFTER THAT? I did vv.setY, I did margins, I tried do stuff with xml - nothing work, video either in the top or stretched through all window

Currently :

I need :

答:
Create four Guidelines using constraint layout with percentage 25% from TOP , 25% from BOTTOM , 25% from RIGHT , 25% from BOTTOM and then create your VIdeoview
You can adjust percentage as per the requirement then according to the screen size it will arrange accordingly.</p>

```<code><VideoView
android:id="@+id/videoView1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/guidelinetop"
app:layout_constraintBottom_toTopOf="@id/guidelinebottom"
app:layout_constraintLeft_toRightOf="@id/guidelineleft"
app:layout_constraintRight_toLeftOf="@id/guidelineright"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
main_acitivity.xml

<?xml version="1.0" encoding="utf-8"?>

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:id="@+id/main"
        tools:context=".MainActivity"
        android:layout_gravity="center"
        android:gravity="center">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

Then in java I do the next

vv = (VideoView) findViewById(R.id.videoView1);

ConstraintLayout.LayoutParams pararams = (ConstraintLayout.LayoutParams) vv.getLayoutParams();
int ch=vv.getHeight();
pararams.height = vv.getWidth();

vv.setLayoutParams(pararams);

HOW TO MAKE ELEMENT VERTICALLY CENTERED AFTER THAT? I did vv.setY, I did margins, I tried do stuff with xml - nothing work, video either in the top or stretched through all window

Currently :

I need :

Body:
Create four Guidelines using constraint layout with percentage 25% from TOP , 25% from BOTTOM , 25% from RIGHT , 25% from BOTTOM and then create your VIdeoview
You can adjust percentage as per the requirement then according to the screen size it will arrange accordingly.

<VideoView
android:id="@+id/videoView1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/guidelinetop"
app:layout_constraintBottom_toTopOf="@id/guidelinebottom"
app:layout_constraintLeft_toRightOf="@id/guidelineleft"
app:layout_constraintRight_toLeftOf="@id/guidelineright"/>


问:
Azure Application Gateway locked down route to app service
I have setup an azure application gateway with web application firewall to route traffic to an azure app service. This requires setting up a VPN. I have followed instructions similar to this: https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-web-app-powershell

However it doesn't explain how to limit traffic to the app service only via the application gateway.

If I go into app service networking tab there is an option to use VNet integration . I thought this might be a way to lock down access through the gateway to the app service but I can't select the gateway VPN because azure tells me 'This virtual network has no gateway'.

So how to I lock down access to the app service so that only traffic which comes through the gateway can access it?

答:
In Azure Portal go to the "Access Restriction" of your Web service.
Then choose to access the application only from VNet and subnet where your application gateway resides.


问:
how to assign variable in json in restrequest c#
Here is my code.Everything works fine when I hard code message attribute in the json. I want to assign variable in 'message' attribute of the json. </p>

```<code>var client = new RestClient("172.16.255.254:2016/settings");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"c3BlZWQgZXhjZWVkZWQh\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
</code>```

答:
To avoid writing out a long JSON string manually, you can use the ubiquitous Newtonsoft.Json NuGet package to create a JSON string from an object.

```<code>using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var message = "Hello, World!";

        string json = JsonConvert.SerializeObject(new
        {
            id = 123,
            message = message
        });

        Console.WriteLine(json);

        // {"id":123,"message":"Hello, World!"}
    }
}

</code>```

DEMO: https://dotnetfiddle.net/FPFrng

You can pass any object in, I'm just creating an anonymous object here for a simple demo.

Body:
Here is my code.Everything works fine when I hard code message attribute in the json. I want to assign variable in 'message' attribute of the json.

var client = new RestClient("172.16.255.254:2016/settings");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"c3BlZWQgZXhjZWVkZWQh\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Body:
To avoid writing out a long JSON string manually, you can use the ubiquitous Newtonsoft.Json NuGet package to create a JSON string from an object.

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var message = "Hello, World!";

        string json = JsonConvert.SerializeObject(new
        {
            id = 123,
            message = message
        });

        Console.WriteLine(json);

        // {"id":123,"message":"Hello, World!"}
    }
}

DEMO: https://dotnetfiddle.net/FPFrng

You can pass any object in, I'm just creating an anonymous object here for a simple demo.


问:
Representing nested JSON as nodes in neo4j (SDN)
Here is my json

```<code>{
    "curriculum": {
        "default_language_id": 1,
        "default_language_code": "en",
        "created_by": 1,
        "depth_order": 0,
        "layer_count": 3,
        "rack_name_meta_info": [
            {
                "name": {
                    "en": "ICSE",
                    "hi": "आईसीएसई"
                },
                "icon": "icon/99.png",
                "color": "#23bd99"
            }
        ],
        "ICSE": [
            {
                "default_language_id": 1,
                "default_language_code": "en",
                "depth_order": 0,
                "rack_name_meta_info": [
                    {
                        "name": {
                            "en": "X",
                            "hi": "भदसवां"
                        },
                        "icon": "icon/99.png",
                        "color": "#23bd99"
                    }
                ]
            }
        ]
    }
}
</code>```

I want to represent this JSON as set of different nodes in Neo4j.

However the nested components are not being displayed.

The rack_name_metainfo has a field of ICSE which further opens up to various other fields.

I'm not able to display such a nested relationship in Graph.

In my model class in which type do I keep the rack_name_meta_info ?

答:
Hey one probable solution is like below

```<code>class curriculum{
   @Realtionship("HAS_RACK_INFOS")
   private List<RackName> rack_name_metainfoList;
}

class RackName{
    @Realtionship("HAS_BOARDS")
    private List<Boards> boards; //ICSE
}
</code>```

A Curriculam has a List of RanckName and further RackName has List of Boards.

Body:
Here is my json

{
    "curriculum": {
        "default_language_id": 1,
        "default_language_code": "en",
        "created_by": 1,
        "depth_order": 0,
        "layer_count": 3,
        "rack_name_meta_info": [
            {
                "name": {
                    "en": "ICSE",
                    "hi": "आईसीएसई"
                },
                "icon": "icon/99.png",
                "color": "#23bd99"
            }
        ],
        "ICSE": [
            {
                "default_language_id": 1,
                "default_language_code": "en",
                "depth_order": 0,
                "rack_name_meta_info": [
                    {
                        "name": {
                            "en": "X",
                            "hi": "भदसवां"
                        },
                        "icon": "icon/99.png",
                        "color": "#23bd99"
                    }
                ]
            }
        ]
    }
}

I want to represent this JSON as set of different nodes in Neo4j.

However the nested components are not being displayed.

The rack_name_metainfo has a field of ICSE which further opens up to various other fields.

I'm not able to display such a nested relationship in Graph.

In my model class in which type do I keep the rack_name_meta_info ?

Body:
Hey one probable solution is like below

class curriculum{
   @Realtionship("HAS_RACK_INFOS")
   private List<RackName> rack_name_metainfoList;
}

class RackName{
    @Realtionship("HAS_BOARDS")
    private List<Boards> boards; //ICSE
}

A Curriculam has a List of RanckName and further RackName has List of Boards.


问:
How to enable minification of xml and json files during apk build process?
Our app contains a lot of json and xml in res/raw and assets folders (16 Mb unpacked). They are pretty formatted. When I minifiy them through external tool and analyze apk via apk-analyzer, the end file size is considerably lower.

Is there a way to enable such minification automatically during build process?
Proguard, R8 and AGP doesn't seem to provide such functionality

my build.gradle

```<code>release {
    minifyEnabled true
    proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    shrinkResources true
}
</code>```

答:
You can use DexGuard or
try adding this to your gradle file </p>

```<code>android {
    buildTypes {
        release {
            // Enables code shrinking, obfuscation, and optimization for only
            // your project's release build type.
            minifyEnabled true

            // Enables resource shrinking, which is performed by the
            // Android Gradle plugin.
            shrinkResources true
        }
    }
}
</code>```

Body:
Our app contains a lot of json and xml in res/raw and assets folders (16 Mb unpacked). They are pretty formatted. When I minifiy them through external tool and analyze apk via apk-analyzer, the end file size is considerably lower.

Is there a way to enable such minification automatically during build process?
Proguard, R8 and AGP doesn't seem to provide such functionality

my build.gradle

release {
    minifyEnabled true
    proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    shrinkResources true
}

Body:
You can use DexGuard or
try adding this to your gradle file

android {
    buildTypes {
        release {
            // Enables code shrinking, obfuscation, and optimization for only
            // your project's release build type.
            minifyEnabled true

            // Enables resource shrinking, which is performed by the
            // Android Gradle plugin.
            shrinkResources true
        }
    }
}


问:
jest typescript property mock does not exist on type
When using jest.fn() to add a mock you can usually access the .mock property to access details such as calls, something similar to this:

```<code>test('not working', () => {
    const foo = new Foo();
    foo.addListener = jest.fn();
    foo.func(); // will call addListener with a callback
    const callback = foo.addListener.mock.calls[0][0];
    expect(callback()).toEqual(1); // test the callback
});
</code>```

When implementing the test in typescript instead of plain javascript I get the error:

error TS2339: Property 'mock' does not exist on type '(callback: () => number) => void'.

I can get rid of the error by casting to any but surely there must be a better way:

```<code>const callback = (foo.addListener as any).mock.calls[0][0];
</code>```

In this simple code the mock could be rewritten to store the argument using jest.fn(fn => { callback = fn; }); but the same error happens when using foo.addListener.mockClear() which cannot be reworked the same way.

So how can I get rid of the error, preferably without losing type-safety?

答:
For anyone getting here, a bit better than casting to any might be casting as jest.Mock

```<code>const callback = (foo.addListener as jest.Mock).mock.calls[0][0];
</code>```

Update Sep 2021

To get a mocked function that both fulfills the mocked function type and the jest mock type jest.MockedFunction can be used:

```<code>const addListenerMock = addListener as jest.MockedFunction<typeof addListener>;
</code>```

Body:
When using jest.fn() to add a mock you can usually access the .mock property to access details such as calls, something similar to this:

test('not working', () => {
    const foo = new Foo();
    foo.addListener = jest.fn();
    foo.func(); // will call addListener with a callback
    const callback = foo.addListener.mock.calls[0][0];
    expect(callback()).toEqual(1); // test the callback
});

When implementing the test in typescript instead of plain javascript I get the error:

error TS2339: Property 'mock' does not exist on type '(callback: () => number) => void'.

I can get rid of the error by casting to any but surely there must be a better way:

const callback = (foo.addListener as any).mock.calls[0][0];

In this simple code the mock could be rewritten to store the argument using jest.fn(fn => { callback = fn; }); but the same error happens when using foo.addListener.mockClear() which cannot be reworked the same way.

So how can I get rid of the error, preferably without losing type-safety?

Body:
For anyone getting here, a bit better than casting to any might be casting as jest.Mock

const callback = (foo.addListener as jest.Mock).mock.calls[0][0];

Update Sep 2021

To get a mocked function that both fulfills the mocked function type and the jest mock type jest.MockedFunction can be used:

const addListenerMock = addListener as jest.MockedFunction<typeof addListener>;


问:
Can connect but cannot write via SFTP
I'm trying to write stuff via SFTP and something strange is happening.

Here's a generic sample script:

```<code><?php

$resConnection = ssh2_connect("<url>");

if (ssh2_auth_password($resConnection, "<name>", '<password>')){
    //Initialize SFTP subsystem
    echo "connected";

    $resSFTP = ssh2_sftp($resConnection);
    $resFile = fopen("ssh2.sftp://{$resSFTP}/"."test", 'w');
    fwrite($resFile, "Testing");
    fclose($resFile);
} else {
    echo "Unable to authenticate on server";
}
</code>```

And the output for it is something like this:

```<code>root@0fb6a2a1af08:/var/www# php test.php
connected
Warning: fopen(ssh2.sftp://Resource id #5/test): failed to open stream: operation failed in /var/www/test.php on line 8

Warning: fwrite() expects parameter 1 to be resource, boolean given in /var/www/test.php on line 9

Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/test.php on line 10
</code>```

So basically it connects but cannot write anything. The same code with the same credentials works fine on another machine.

Is it possible that some specific configuration on SFTP side prevents me from writing?

答:
Ok, it is connected with this bugs:

https://bugs.php.net/bug.php?id=73597

https://bugs.php.net/bug.php?id=69981

etc

The solutions for now is to use intval around the resource string as it is said in docs: https://www.php.net/manual/ru/function.ssh2-sftp.php

```<code>$stream = fopen('ssh2.sftp://' . intval($sftp) . '/path/to/file', 'r');
</code>```

Title: Can connect but cannot write via SFTP

Body:
I'm trying to write stuff via SFTP and something strange is happening.

Here's a generic sample script:

<?php

$resConnection = ssh2_connect("<url>");

if (ssh2_auth_password($resConnection, "<name>", '<password>')){
    //Initialize SFTP subsystem
    echo "connected";

    $resSFTP = ssh2_sftp($resConnection);
    $resFile = fopen("ssh2.sftp://{$resSFTP}/"."test", 'w');
    fwrite($resFile, "Testing");
    fclose($resFile);
} else {
    echo "Unable to authenticate on server";
}

And the output for it is something like this:

root@0fb6a2a1af08:/var/www# php test.php
connected
Warning: fopen(ssh2.sftp://Resource id #5/test): failed to open stream: operation failed in /var/www/test.php on line 8

Warning: fwrite() expects parameter 1 to be resource, boolean given in /var/www/test.php on line 9

Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/test.php on line 10

So basically it connects but cannot write anything. The same code with the same credentials works fine on another machine.

Is it possible that some specific configuration on SFTP side prevents me from writing?

Body:
Ok, it is connected with this bugs:

https://bugs.php.net/bug.php?id=73597

https://bugs.php.net/bug.php?id=69981

etc

The solutions for now is to use intval around the resource string as it is said in docs: https://www.php.net/manual/ru/function.ssh2-sftp.php

$stream = fopen('ssh2.sftp://' . intval($sftp) . '/path/to/file', 'r');


问:
Where is the use of Game theory in Generative Adversarial Network
We know that the training of Generative Adversarial Networks is based on Game theory and that a Nash Equilibrium is reached during the training. But when looking on a sample of GAN using tensorflow: https://www.tensorflow.org/tutorials/generative/dcgan,

I did not find in the code where Game theory is applied and where the Nash Equilibrium is estimated.
Could someone show where we used Game theory in this code?

答:
This is more of a theoretical/conceptual answer as there is no explicit part of the code you would call game theory.

Basically, the principles of game theory are implemented as you have two networks, the Generator and the Discriminator, contesting each other (Adversarial part). In a GAN Nash equilibrium is reached when you converge i.e. when the loss of the discriminator does not get reduced at the expense of the generator and v.v. (or more formally when the action of the opponent is not affecting the decision of the player).

In the example provided, you save a model every 15 epochs to ensure that you can capture the model at Nash equilibrium or close enough to it:

    # Save the model every 15 epochs
    if (epoch + 1) % 15 == 0:
      checkpoint.save(file_prefix = checkpoint_prefix)
```

Another way would be to implement some sort of early stopping (or if you use tensorboard track the losses of the two networks to visualize convergence).

This article seems to have an extensive explanation of the Nash equilibrium for GANs.

Body:
This is more of a theoretical/conceptual answer as there is no explicit part of the code you would call game theory.

Basically, the principles of game theory are implemented as you have two networks, the Generator and the Discriminator, contesting each other (Adversarial part). In a GAN Nash equilibrium is reached when you converge i.e. when the loss of the discriminator does not get reduced at the expense of the generator and v.v. (or more formally when the action of the opponent is not affecting the decision of the player).

In the example provided, you save a model every 15 epochs to ensure that you can capture the model at Nash equilibrium or close enough to it:

    # Save the model every 15 epochs
    if (epoch + 1) % 15 == 0:
      checkpoint.save(file_prefix = checkpoint_prefix)

Another way would be to implement some sort of early stopping (or if you use tensorboard track the losses of the two networks to visualize convergence).

This article seems to have an extensive explanation of the Nash equilibrium for GANs.


问:
Error: Could not load the default credentials (Firebase function to firestore)
I am attempting to write an onCall function for Firebase Cloud Functions that performs advanced querying tasks on a firestore database (i.e. checking a text query up against AutoML natural lang to get a category, etc) but I keep running into a problem trying to query the database from the function:

```<code>Error getting documents ::  Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
    at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)
</code>```

Function:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.query = functions.https.onCall((data, context) => {
    const text = data.text;
    var results = [];
    const promise = db.collection('providers').get()
    promise.then((snapshot) => {
        console.log('marker');
        snapshot.forEach((doc) => {
            results.push({id: doc.id, data: doc.data()});
        });
        console.log('yessir');
        return {results: results};
    }).catch((err) => {
        console.log('Error getting documents :: ', err)
        console.log('nosir');
        return {results: "no results"};
    });
});
</code>```

Longer output:

```<code>Function execution started
Function execution took 8ms, finished with status code: 200
Error getting documents :: (etc, same error)
nosir
</code>```

Example 2 (no change in running):

```<code>Function execution started
Function execution took 1200 ms, finished with status code: 200
marker
yessir
</code>```

I can't figure out where this problem is coming from or how to resolve it.
Any help?

Regards.

答:
Download your firebase service account into your project and reference it like this:

  var admin = require("firebase-admin");
  var serviceAccount = require("path/to/serviceAccountKey.json");

  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "<database-url>"
  });

```

Body:
I am attempting to write an onCall function for Firebase Cloud Functions that performs advanced querying tasks on a firestore database (i.e. checking a text query up against AutoML natural lang to get a category, etc) but I keep running into a problem trying to query the database from the function:

Error getting documents ::  Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
    at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.query = functions.https.onCall((data, context) => {
    const text = data.text;
    var results = [];
    const promise = db.collection('providers').get()
    promise.then((snapshot) => {
        console.log('marker');
        snapshot.forEach((doc) => {
            results.push({id: doc.id, data: doc.data()});
        });
        console.log('yessir');
        return {results: results};
    }).catch((err) => {
        console.log('Error getting documents :: ', err)
        console.log('nosir');
        return {results: "no results"};
    });
});

Longer output:

Function execution started
Function execution took 8ms, finished with status code: 200
Error getting documents :: (etc, same error)
nosir

Example 2 (no change in running):

Function execution started
Function execution took 1200 ms, finished with status code: 200
marker
yessir

I can't figure out where this problem is coming from or how to resolve it.
Any help?

Regards.

Body:
Download your firebase service account into your project and reference it like this:

<code>
  var admin = require("firebase-admin");
  var serviceAccount = require("path/to/serviceAccountKey.json");

  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "<database-url>"
  });
</code>


答:
Use JSON.NET and serialize to json your object and send it.</p>

```<code>var myVariable = ...

string message = JsonConvert.SerializeObject(myVariable);
request.AddParameter("application/json", message);
</code>```

Title: how to assign variable in json in restrequest c#

Body:
Use JSON.NET and serialize to json your object and send it.

var myVariable = ...

string message = JsonConvert.SerializeObject(myVariable);
request.AddParameter("application/json", message);


问:
Gstreamer How to Capture Video from Specific Camera on Windows (MultipleCameras)
My problem is I have to capture video from camera but I have multiple cameras. First one is default laptop camera and second is USB-attached Camera.

The problem is there is no 'device' attribute in gstreamer sources on Windows.

In Linux, I have found  " gst-launch v4l2src device=/dev/video0 \ "

In Windows instead of v412src, autovidesrc and videotestsrc are using. However, they don't have 'device' attribute.

As I searched in web, people are using dsvideoshowsrc but I did not get how they install it or how they implemented it. Some of them used ksvideosrc.

If anyone can help how can I resolve this issue, that would be very appreciated. I know many people had this problem and will have this problem. Therefore, clean explanation would benefit us so much.

答:
ksvideosrc is good. Need to have GStreamer version 1.3 or above. Install or change to use all capture features. Typical install on windows does not come with ksvideosrc.
For ksvideosrc device-index starts from 0. If Webcam is the only video capture device, it would be device-index 0.


问:
ImportError: cannot import name 'input_reader_pb2'
working on win10 64-bit

when i trying to train my model by E:\projectx\model-master\models-master>python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config

this error appear

File "train.py", line 49, in
          from object_detection.builders import dataset_builder
        File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\builders\dataset_builder.py",
  line 27, in
          from object_detection.data_decoders import tf_example_decoder
        File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\data_decoders\tf_example_decoder.py",
  line 27, in
          from object_detection.protos import input_reader_pb2
          ImportError: cannot import name 'input_reader_pb2'

i do run protoc 3.4 protoc object_detection/protos/*.proto --python_out=.
but the error still exist
i check all thing and it is should be fine and work, it is going me mad!!

please help....
thanks

答:
As you already compiled all .proto files in object_detection/protos/ . You should see python files which have '_pb2' like eval_pb2. If you can see these then go to models/research directory and run these code one by one:

```<code>python setup.py build
python setup.py install
</code>```

Body:
As you already compiled all .proto files in object_detection/protos/ . You should see python files which have '_pb2' like eval_pb2. If you can see these then go to models/research directory and run these code one by one:

python setup.py build
python setup.py install


问:
Translate a MySql query in a Laravel query builder
```<code>SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC
</code>```

how can I Translate this  MySql query in a Laravel query builder ?

答:
```<code>$data = $this->views;
$data = $data->select(
    "apartment_id",
    DB::raw("COUNT(created_at) AS n_view"),
    DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
);
$data = $data->where("apartment_id", 36);
$data = $data->groupBy("day_view");
$data = $data->orderBy("created_at", "desc");
$data = $data->get();
</code>```

Body:
SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC

how can I Translate this  MySql query in a Laravel query builder ?


问:
How to split a dataframe and attach the splitted part in new column?
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

```<code>#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)
</code>```

答:
This is a possible solution for your example : </p>

```<code>new_df = data.frame(list(df[1,],df[2,],df[3,]))
</code>```

<p>And if you want to generalize that on a bigger data.frame : </p>

```<code>new_list = list()
for ( i in 1:dim(df)[1] ){
    new_list[[i]] = df[i,]
}
new_df = data.frame(new_list)
</code>```

Body:
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)

Body:
This is a possible solution for your example :

new_df = data.frame(list(df[1,],df[2,],df[3,]))

And if you want to generalize that on a bigger data.frame :

new_list = list()
for ( i in 1:dim(df)[1] ){
    new_list[[i]] = df[i,]
}
new_df = data.frame(new_list)


问:
Problem running a C# Console App with CLR wrapped C++ code
I followed this tutorial: How to create a CLR Wrapper of C++ for using in C#

My project builds without a problem and I use the same exact code as the tutorial.

I am trying to run the final C# Console Application. (double-clicking the built c#.exe file)

Instead of expected console output "4.1", it shows an error:

Does anyone know why does it say?:

Unhandled exception. System.BadImageFormatException:
Could not load file or assembly 'Clrcs, Version=1.0.7354.20945, Culture=neutral, PublicKeyToken=null'.
An attempt was made to load a program with incorrect format.
File name: 'ClrCs, Version=1.0.7354.20945, Culture=neutral, PublicKeyToken=null'
at Cs.Program.Main(String[] args)

All the 3 sub-projects in my solution:

- are set to target .NET Core.

- were built as Debug for x86.

- have required references.

Why am I trying to achieve this / is there a better solution for my problem?:

I want to use my SFML|OpenGL|C++ "engine" to draw 3D objects using data from a software running on JavaScript.

I discovered that this software can be connected to a C# .dll in it's .js file, so I am trying to wrap my unmanaged "engine" into  C# as .dll.

I already know it is possible to open a render window from a dll.

I tried it in a C++ console application, where I imported my "engine" as a .dll.

Next I just need to import the CLR Wrapper to a C# app as a .dll, which the mentioned tutorial explains,
but there are problems running the .exe file. And I can not figure out why.

In short:

[SFML|OpenGL]C++ as .dll >into> C++/CLR Wrapper as .dll >into> C# as .exe

Could you please help me? In any way?

答:
I feel silly for asking you this question and not making sure this option was saved.

I found a solution:

In the C# project properties -> Build -> Platform target -> changed from AnyCPU to x86.


问:
How to create and display custom component 100 times using Vanilla JS
Dears,

I have a task to create custom HTML component, display it 100 times, add button to it, which would remove it and also every 3rd component should be clickable and change color on click.
So far I have this https://codepen.io/GosiaPtak/pen/abOZmyq

```<code>class ElementList extends HTMLElement {
  constructor() {
    super();
    let counter = 100;
    const div = '';
    const btn = '';
   }
  connectedCallback() {
    this.div = document.createElement('div');
    this.div.innerHTML = 'i am div';
    this.btn = document.createElement('button');
    this.btn.innerHTML = 'Click me';
    this.div.appendChild(this.btn);
    this.appendChild(this.div);
  }
}
customElements.define('element-list', ElementList);
</code>```

but I am not able to place the while loop properly, so it would display it 100 times.

could you please help me, I am learning it from here: https://javascript.info/custom-elements

Kind regards,

答:
You are defining a custom element with your code which represents one instance of the object. To now create multiple of these just use basic javascript outside of the class definition like the code below shows.

class ElementList extends HTMLElement {
  constructor() {
    super();
    const div = '';
    const btn = '';
   }
  connectedCallback() {
    this.div = document.createElement('div');
    this.div.innerHTML = 'i am div';
    this.btn = document.createElement('button');
    this.btn.innerHTML = 'Click me';
    this.div.appendChild(this.btn);
    this.appendChild(this.div);
  }
}
customElements.define('element-list', ElementList);

for(let i = 0; i <= 100; i++) {
  let item = document.createElement('element-list');
  document.body.appendChild(item);
}
```

With this for loop and maybe a parameter which you could pass to your object you can realize things like every third should be clickable.

Body:
Dears,

I have a task to create custom HTML component, display it 100 times, add button to it, which would remove it and also every 3rd component should be clickable and change color on click.
So far I have this https://codepen.io/GosiaPtak/pen/abOZmyq

class ElementList extends HTMLElement {
  constructor() {
    super();
    let counter = 100;
    const div = '';
    const btn = '';
   }
  connectedCallback() {
    this.div = document.createElement('div');
    this.div.innerHTML = 'i am div';
    this.btn = document.createElement('button');
    this.btn.innerHTML = 'Click me';
    this.div.appendChild(this.btn);
    this.appendChild(this.div);
  }
}
customElements.define('element-list', ElementList);

but I am not able to place the while loop properly, so it would display it 100 times.

could you please help me, I am learning it from here: https://javascript.info/custom-elements

Kind regards,

Body:
You are defining a custom element with your code which represents one instance of the object. To now create multiple of these just use basic javascript outside of the class definition like the code below shows.

class ElementList extends HTMLElement {
  constructor() {
    super();
    const div = '';
    const btn = '';
   }
  connectedCallback() {
    this.div = document.createElement('div');
    this.div.innerHTML = 'i am div';
    this.btn = document.createElement('button');
    this.btn.innerHTML = 'Click me';
    this.div.appendChild(this.btn);
    this.appendChild(this.div);
  }
}
customElements.define('element-list', ElementList);

for(let i = 0; i <= 100; i++) {
  let item = document.createElement('element-list');
  document.body.appendChild(item);
}

With this for loop and maybe a parameter which you could pass to your object you can realize things like every third should be clickable.


问:
Handling input events in a MetalKit application
I created an application on OS X in Xcode using "Game" template that uses MetalKit. How do I handle input events like keyDown and keyUp? I tried adding

```<code>- (void)keyDown:(NSEvent *)theEvent
{
    NSLog( @"Key down\n" );
}

- (void)keyUp:(NSEvent *)theEvent
{
    NSLog( @"Key up\n" );
}
</code>```

into AppDelegate and GameViewController but they are not called when I press a key.

答:
As stated: you must subclass MTKView and handle keyDown in the subclass.
Also remember to set the view's class in Storyboard from MTKView to the subclass.

This is the way to get rid of those nasty beeps in a MTKView (due to unhandled keyDown).

But also as stated in the comments: if you reset the class in Storyboard to MTKView, keyDown keeps being handled (and there are no beeps). Odd.

I never got it to work without subclassing as suggested in one of the answers. How do you get a pointer to GameViewController at that stage?

Body:
I created an application on OS X in Xcode using "Game" template that uses MetalKit. How do I handle input events like keyDown and keyUp? I tried adding

- (void)keyDown:(NSEvent *)theEvent
{
    NSLog( @"Key down\n" );
}

- (void)keyUp:(NSEvent *)theEvent
{
    NSLog( @"Key up\n" );
}

into AppDelegate and GameViewController but they are not called when I press a key.


问:
Find source of "NdkCompile is no longer supported"
We have the following warning message in Android Studio 3.4.1:

WARNING: The following project options are deprecated and have been
  removed:

  android.useDeprecatedNdk

  NdkCompile is no longer supported

  Affected Modules: module1, module2, moduleN

We don't use useDeprecatedNdk or NdkCompile or use NDK at all directly ourselves, so I assume this is coming from some library we have included. How can I track down which dependency is causing this warning message?

答: I found the culprit: In ~/.gradle/gradle.properties it said android.useDeprecatedNdk=true.


问:
Submit button won't line up vertically with other fields on the same line
Can anybody shed some light on why this submit button won't line up vertically with the other form fields on the line?

http://www.e-fluential.com/offline/castoff/

答: try to increase the width of the signup class div</p>


问:
How to configure application.properties in camel tests?
I'm working on writing tests for the route
The problem is all my routes contain properties that described in application.properties file e.g

```<code>from("oracleQueue:{{oracle.queue.url}}").to("my.endpoint")
</code>```

It works fine but when I try to write a test - seems like this route can't find application.properties file with its properties.
The error:

```<code>java.lang.IllegalArgumentException: Property with key [oracle.queue.url] not found in properties from text: oracleQueue:{{oracle.queue.url}}
</code>```

My testcase:

```<code>public class RouteTest extends CamelTestSupport {

@Override
protected RoutesBuilder createRouteBuilder() {
    MyRouteBulder route = new MyRouteBulder ();
    ApplicationContext appContext = new ClassPathXmlApplicationContext("camel-context.xml");

    PropertiesComponent pc = new PropertiesComponent();
    pc.setLocation("application.properties");

    CamelContext context = new SpringCamelContext(appContext);

    context.addComponent("properties", pc);
    route.setContext(context);
    return route;
}

@Test
public void test() throws InterruptedException {
    MockEndpoint mockEndpoint = resolveMandatoryEndpoint("my.endpoint", MockEndpoint.class);
    mockEndpoint.expectedMessageCount(1);
    template.sendBody("oracleQueue:{{oracle.queue.url}}", "hello world");
    mockEndpoint.assertIsSatisfied();

}
</code>```

}

How should I set up configuration file properly?

答:
Maybe you need an absolute path for the location.

I use this to get props

```<code><bean
    class="org.apache.camel.component.properties.PropertiesComponent"
    id="properties" name="properties">
    <property name="cache" value="false"/>
    <property name="locations">
        <list>
            <value>file:${CONF}/broker.properties</value>
            <value>file:${CONF}/sops/domains/properties/a92fe32d-01c9-4c00-b2c0-b17a71503bbe.properties;optional=true</value>
        </list>
    </property>
</bean>
</code>```

Body:
I'm working on writing tests for the route
The problem is all my routes contain properties that described in application.properties file e.g

from("oracleQueue:{{oracle.queue.url}}").to("my.endpoint")

It works fine but when I try to write a test - seems like this route can't find application.properties file with its properties.
The error:

java.lang.IllegalArgumentException: Property with key [oracle.queue.url] not found in properties from text: oracleQueue:{{oracle.queue.url}}

My testcase:

public class RouteTest extends CamelTestSupport {

@Override
protected RoutesBuilder createRouteBuilder() {
    MyRouteBulder route = new MyRouteBulder ();
    ApplicationContext appContext = new ClassPathXmlApplicationContext("camel-context.xml");

    PropertiesComponent pc = new PropertiesComponent();
    pc.setLocation("application.properties");

    CamelContext context = new SpringCamelContext(appContext);

    context.addComponent("properties", pc);
    route.setContext(context);
    return route;
}

@Test
public void test() throws InterruptedException {
    MockEndpoint mockEndpoint = resolveMandatoryEndpoint("my.endpoint", MockEndpoint.class);
    mockEndpoint.expectedMessageCount(1);
    template.sendBody("oracleQueue:{{oracle.queue.url}}", "hello world");
    mockEndpoint.assertIsSatisfied();

}

}

How should I set up configuration file properly?

Body:
Maybe you need an absolute path for the location.

I use this to get props

<bean
    class="org.apache.camel.component.properties.PropertiesComponent"
    id="properties" name="properties">
    <property name="cache" value="false"/>
    <property name="locations">
        <list>
            <value>file:${CONF}/broker.properties</value>
            <value>file:${CONF}/sops/domains/properties/a92fe32d-01c9-4c00-b2c0-b17a71503bbe.properties;optional=true</value>
        </list>
    </property>
</bean>


问:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)
I know, it has been asked several times, but none of the answer gave me a solution

Here is the code (Python 2.7):

```<code>import cx_Oracle
import pandas as pd

connstr = 'MyConstr'
conn = cx_Oracle.connect(connstr)
cur = conn.cursor()

xl = pd.ExcelFile("C:\\TEMP\\for_kkod.xlsx")
df = xl.parse(0)

for i in df.index:
    s = u"insert into MY_TABLE values({0}, '{1}')".format(int(df.iloc[i]['kkod']), df.iloc[i]['kkodnev'])
    print s
    print type(s)
    cur.execute(s)
</code>```

The result of the 2 prints are this:

```<code>insert into MY_TABLE values(10, 'Készítés')
<type 'unicode'>
</code>```

As you can see the type of s is unicode but nevertheless I have this error message:

```<code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)
</code>```

I have tried with and without u"", with and without encode and decode in all possible ways but still the same error message

Any idea?

答:
Simply use the following parameters for connection:

connection = cx_Oracle.connect(connectString, encoding="UTF-8",nencoding="UTF-8")

Body:
I know, it has been asked several times, but none of the answer gave me a solution

Here is the code (Python 2.7):

import cx_Oracle
import pandas as pd

connstr = 'MyConstr'
conn = cx_Oracle.connect(connstr)
cur = conn.cursor()

xl = pd.ExcelFile("C:\\TEMP\\for_kkod.xlsx")
df = xl.parse(0)

for i in df.index:
    s = u"insert into MY_TABLE values({0}, '{1}')".format(int(df.iloc[i]['kkod']), df.iloc[i]['kkodnev'])
    print s
    print type(s)
    cur.execute(s)

The result of the 2 prints are this:

insert into MY_TABLE values(10, 'Készítés')
<type 'unicode'>

As you can see the type of s is unicode but nevertheless I have this error message:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)

I have tried with and without u"", with and without encode and decode in all possible ways but still the same error message

Any idea?


问:
Expanding a parent
 to the height of its children
I have a page structure similar to this:

```<code><body>
  <div id="parent">
    <div id="childRightCol">
      /*Content*/
    </div>
    <div id="childLeftCol">
      /*Content*/
    </div>
  </div>
</body>
</code>```

I would like for the parent div to expand in height when the inner div's height increases.

Edit:

One problem is that if the width of the child content expands past the width of the browser window, my current CSS puts a horizontal scrollbar on the parent div.  I would like the scrollbar to be at the page level. Currently my parent div is set to overflow: auto;

Can you please help me with the CSS for this?

答:
Where We’re Starting From

Here’s some boilerplate HTML and CSS. In our example, we have a parent element with two floated child elements.

/* The CSS you're starting with may look similar to this.
 * This doesn't solve our problem yet, but we'll get there shortly.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- The HTML you're starting with might look similar to this -->
<div class="containing-div">
  <div class="floating-div">
    <ul>
      <li>List Item One</li>
      <li>List Item Two</li>
      <li>List Item Three</li>
      <li>List Item Four</li>
    </ul>
  </div>
  <div class="floating-div">
    <ul>
      <li>List Item Five</li>
      <li>List Item Six</li>
      <li>List Item Seven</li>
      <li>List Item Eight</li>
    </ul>
  </div>
</div></code>```

Solution #1: overflow: auto

A solution that works in all modern browsers and in Internet Explorer back to IE8 is to add overflow: auto to the parent element. This also works in IE7, with scrollbars added.

/* Our Modified CSS.
 * This is one way we can solve our problem.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
  overflow: auto;
  /*This is what we added!*/
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}```
</div>
</div>
</p>

<p><strong>Solution #2: Float Parent Container</strong></p>

<p>Another solution that works in all modern browsers and back to IE7 is to float the parent container.</p>

<p>This may not always be practical, because floating your parent div may affect other parts of your page layout.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Modified CSS #2.
 * Floating parent div.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  float: left;
  /*Added*/
  height: auto;
  width: 100%;
  /*Added*/
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}</code>```

Method #3: Add Clearing Div Below Floated Elements

/*
 * CSS to Solution #3.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}

/*Added*/

.clear {
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Solution 3, Add a clearing div to bottom of parent element -->
<div class="containing-div">
  <div class="floating-div">
    <ul>
      <li>List Item One</li>
      <li>List Item Two</li>
      <li>List Item Three</li>
      <li>List Item Four</li>
    </ul>
  </div>
  <div class="floating-div">
    <ul>
      <li>List Item Five</li>
      <li>List Item Six</li>
      <li>List Item Seven</li>
      <li>List Item Eight</li>
    </ul>
  </div>
  <div class="clear"></div>
</div></code>```

Method #4: Add Clearing Div To The Parent Element
This solution is pretty bulletproof for older browsers and newer browsers alike.

/*
 * CSS to Solution #4.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}

/*Added*/

.clearfix {
  clear: both;
}

.clearfix:after {
  clear: both;
  content: "";
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Solution 4, make parent element self-clearing -->
<div class="containing-div clearfix">
  <div class="floating-div">
    <ul>
      <li>List Item One</li>
      <li>List Item Two</li>
      <li>List Item Three</li>
      <li>List Item Four</li>
    </ul>
  </div>
  <div class="floating-div">
    <ul>
      <li>List Item Five</li>
      <li>List Item Six</li>
      <li>List Item Seven</li>
      <li>List Item Eight</li>
    </ul>
  </div>
</div></code>```

from https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/

OwnerDisplayName: Steve Horn

Title: Expanding a parent <div> to the height of its children

Body:
I have a page structure similar to this:

      /*Content*/

      /*Content*/

I would like for the parent div to expand in height when the inner div's height increases.

Edit:

One problem is that if the width of the child content expands past the width of the browser window, my current CSS puts a horizontal scrollbar on the parent div.  I would like the scrollbar to be at the page level. Currently my parent div is set to overflow: auto;

Can you please help me with the CSS for this?

LastEditorDisplayName: Steve Horn

Body:
Where We’re Starting From

Here’s some boilerplate HTML and CSS. In our example, we have a parent element with two floated child elements.

/* The CSS you're starting with may look similar to this.
 * This doesn't solve our problem yet, but we'll get there shortly.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}

<!-- The HTML you're starting with might look similar to this -->
<div class="containing-div">
  <div class="floating-div">
    <ul>
      <li>List Item One</li>
      <li>List Item Two</li>
      <li>List Item Three</li>
      <li>List Item Four</li>
    </ul>
  </div>
  <div class="floating-div">
    <ul>
      <li>List Item Five</li>
      <li>List Item Six</li>
      <li>List Item Seven</li>
      <li>List Item Eight</li>
    </ul>
  </div>
</div>

Solution #1: overflow: auto

A solution that works in all modern browsers and in Internet Explorer back to IE8 is to add overflow: auto to the parent element. This also works in IE7, with scrollbars added.

/* Our Modified CSS.
 * This is one way we can solve our problem.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
  overflow: auto;
  /*This is what we added!*/
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}

Solution #2: Float Parent Container

Another solution that works in all modern browsers and back to IE7 is to float the parent container.

This may not always be practical, because floating your parent div may affect other parts of your page layout.

/* Modified CSS #2.
 * Floating parent div.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  float: left;
  /*Added*/
  height: auto;
  width: 100%;
  /*Added*/
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}

Method #3: Add Clearing Div Below Floated Elements

/*
 * CSS to Solution #3.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}

/*Added*/

.clear {
  clear: both;
}

<!-- Solution 3, Add a clearing div to bottom of parent element -->
<div class="containing-div">
  <div class="floating-div">
    <ul>
      <li>List Item One</li>
      <li>List Item Two</li>
      <li>List Item Three</li>
      <li>List Item Four</li>
    </ul>
  </div>
  <div class="floating-div">
    <ul>
      <li>List Item Five</li>
      <li>List Item Six</li>
      <li>List Item Seven</li>
      <li>List Item Eight</li>
    </ul>
  </div>
  <div class="clear"></div>
</div>

Method #4: Add Clearing Div To The Parent Element
This solution is pretty bulletproof for older browsers and newer browsers alike.

/*
 * CSS to Solution #4.
 */

.containing-div {
  background-color: #d2b48c;
  display: block;
  height: auto;
}

.floating-div {
  float: left;
  width: 50%;
}

.floating-div ul {
  display: inline-block;
  height: auto;
}

/*Added*/

.clearfix {
  clear: both;
}

.clearfix:after {
  clear: both;
  content: "";
  display: table;
}

<!-- Solution 4, make parent element self-clearing -->
<div class="containing-div clearfix">
  <div class="floating-div">
    <ul>
      <li>List Item One</li>
      <li>List Item Two</li>
      <li>List Item Three</li>
      <li>List Item Four</li>
    </ul>
  </div>
  <div class="floating-div">
    <ul>
      <li>List Item Five</li>
      <li>List Item Six</li>
      <li>List Item Seven</li>
      <li>List Item Eight</li>
    </ul>
  </div>
</div>

from https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/


问:
how to compare type of an object's instance to a generic type?
how can i write this code in java?

```<code>public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public <U extends IComponent> U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}
</code>```

but i cant perform instanceof on generic types. how should i do it?
thanks.

答:
As far as I know, you can't. You'll have to take a Class object as a parameter:

```<code>public <U extends IComponent> U getComponent(Class<U> clazz) {
    // ...
    if (component.getClass() == clazz) {
        return (U) component;
    }
}
</code>```

And call it like this:

```<code>getComponent(MyComponentImpl.class);
</code>```

Body:
how can i write this code in java?

public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public  U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}

but i cant perform instanceof on generic types. how should i do it?
thanks.

Body:
As far as I know, you can't. You'll have to take a Class object as a parameter:

public <U extends IComponent> U getComponent(Class<U> clazz) {
    // ...
    if (component.getClass() == clazz) {
        return (U) component;
    }
}

And call it like this:

getComponent(MyComponentImpl.class);


问:
How do I set text cursor height to match with my font in EditText
I am using Digory Doodles Font for my EditText. Font is locally available to my app in assets.

When I set this font to my EditText, the text cursor takes too much space in height. It doesn't match actual text height. This, also, changes height for EditText, which was set to wrap_content.

This is how I set fonts:

```<code>val typeface = Typeface.createFromAsset(
   assetsManager, "fonts/$type/$fileName"
)
editText.typeface = typeface
</code>```

When I set font it looks like image below.

If I move cursor to some other position in text(not last position), it looks like image below:

For any other font, it looks like image below:

How can I solve this issue?

答:
android:textCursorDrawable="@drawable/cursor"

Design custom cursor and use like this

Body:
I am using Digory Doodles Font for my EditText. Font is locally available to my app in assets.

When I set this font to my EditText, the text cursor takes too much space in height. It doesn't match actual text height. This, also, changes height for EditText, which was set to wrap_content.

This is how I set fonts:

val typeface = Typeface.createFromAsset(
   assetsManager, "fonts/$type/$fileName"
)
editText.typeface = typeface

When I set font it looks like image below.

If I move cursor to some other position in text(not last position), it looks like image below:

For any other font, it looks like image below:

How can I solve this issue?


问:
Does spread operator affect performance?
I am considering the below two approaches for building an array of objects:

Approach 1 (list all properties, even if duplicated among objects):

```<code>const employees = [
  {
    company: 'ABC',
    country: 'IN',
    zip: 123,
    employeeId: 123,
    employeeName: 'p'
  },
  {
    company: 'ABC',
    country: 'IN',
    zip: 123,
    employeeId: 456,
    employeeName: 'q'
  },
  {
    company: 'ABC',
    country: 'IN',
    zip: 123,
    employeeId: 789,
    employeeName: 'r'
  }
];
</code>```

Approach 2 (avoid duplication with the spread operator):

```<code>const commonParams = {
  company: 'ABC',
  country: 'IN',
  zip: 123
};

const employees = [
  {
    ...commonParams,
    employeeId: 123,
    employeeName: 'p'
  },
  {
    ...commonParams,
    employeeId: 456,
    employeeName: 'q'
  },
  {
    ...commonParams,
    employeeId: 789,
    employeeName: 'r'
  }
]
</code>```

Approach 2 is more succint, and adding a new property that is common to all array elements would be much easier (and less prone to errors).

However, in case of a large commonParams object, does approach 2 (using the spread operator) affect performance as compared to approach 1?

Would the spread operator loop through each of the properties of the commonParams object for each of the objects in the employees array?

答:
In case someone is stumbling uppon this question while wondering about array spread operations instead of objects:

I benched different methods to accomplish:

```<code>const clone = [...original]
</code>```

var original = [];
var clone = [];

for (var i = 0; i < 10000000; i++) {
    original.push(1);
}
var cycle = 0;

var spreadTime = [];
var mapTime = [];
var forTime = [];
var reduceTime = [];
var sliceTime = [];
var arrayFromTime = [];

while (cycle < 10) {
  var d = Date.now();
  clone = [];
  clone = [...original];
  spreadTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = original.map((entry) => entry);
  mapTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  for (var i = 0; i < original.length; i++) {
      clone[i] = original[i];
  }
  forTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = original.reduce((next, e) => {
      next.push(e);

      return next;
  }, []);
  reduceTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = original.slice();
  sliceTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = Array.from(original);
  arrayFromTime.push(Date.now() - d);

  cycle ++;
  document.getElementById("cycle").innerHTML = cycle;
  document.getElementById("spreadTime").innerHTML = spreadTime.reduce((a,b) => a + b, 0) / spreadTime.length;
  document.getElementById("mapTime").innerHTML = mapTime.reduce((a,b) => a + b, 0) / mapTime.length;
  document.getElementById("forTime").innerHTML = forTime.reduce((a,b) => a + b, 0) / forTime.length;
  document.getElementById("reduceTime").innerHTML = reduceTime.reduce((a,b) => a + b, 0) / reduceTime.length;
  document.getElementById("sliceTime").innerHTML = sliceTime.reduce((a,b) => a + b, 0) / sliceTime.length;
  document.getElementById("arrayFromTime").innerHTML = arrayFromTime.reduce((a,b) => a + b, 0) / arrayFromTime.length;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><View>
  <h1>cycle <span id="cycle"></span></h1>
  spread: <span id="spreadTime"></span> ms
  <br/>
  map: <span id="mapTime"></span> ms
  <br/>
  for: <span id="forTime"></span> ms
  <br/>
  reduce: <span id="reduceTime"></span> ms
  <br/>
  slice: <span id="sliceTime"></span> ms
  <br/>
  arrayFrom: <span id="arrayFromTime"></span> ms
  <br/>
</View></code>```

Body:
I am considering the below two approaches for building an array of objects:

Approach 1 (list all properties, even if duplicated among objects):

const employees = [
  {
    company: 'ABC',
    country: 'IN',
    zip: 123,
    employeeId: 123,
    employeeName: 'p'
  },
  {
    company: 'ABC',
    country: 'IN',
    zip: 123,
    employeeId: 456,
    employeeName: 'q'
  },
  {
    company: 'ABC',
    country: 'IN',
    zip: 123,
    employeeId: 789,
    employeeName: 'r'
  }
];

Approach 2 (avoid duplication with the spread operator):

const commonParams = {
  company: 'ABC',
  country: 'IN',
  zip: 123
};

const employees = [
  {
    ...commonParams,
    employeeId: 123,
    employeeName: 'p'
  },
  {
    ...commonParams,
    employeeId: 456,
    employeeName: 'q'
  },
  {
    ...commonParams,
    employeeId: 789,
    employeeName: 'r'
  }
]

Approach 2 is more succint, and adding a new property that is common to all array elements would be much easier (and less prone to errors).

However, in case of a large commonParams object, does approach 2 (using the spread operator) affect performance as compared to approach 1?

Would the spread operator loop through each of the properties of the commonParams object for each of the objects in the employees array?

Body:
In case someone is stumbling uppon this question while wondering about array spread operations instead of objects:

I benched different methods to accomplish:

const clone = [...original]

var original = [];
var clone = [];

for (var i = 0; i < 10000000; i++) {
    original.push(1);
}
var cycle = 0;

var spreadTime = [];
var mapTime = [];
var forTime = [];
var reduceTime = [];
var sliceTime = [];
var arrayFromTime = [];

while (cycle < 10) {
  var d = Date.now();
  clone = [];
  clone = [...original];
  spreadTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = original.map((entry) => entry);
  mapTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  for (var i = 0; i < original.length; i++) {
      clone[i] = original[i];
  }
  forTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = original.reduce((next, e) => {
      next.push(e);

      return next;
  }, []);
  reduceTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = original.slice();
  sliceTime.push(Date.now() - d);

  d = Date.now();
  clone = [];
  clone = Array.from(original);
  arrayFromTime.push(Date.now() - d);

  cycle ++;
  document.getElementById("cycle").innerHTML = cycle;
  document.getElementById("spreadTime").innerHTML = spreadTime.reduce((a,b) => a + b, 0) / spreadTime.length;
  document.getElementById("mapTime").innerHTML = mapTime.reduce((a,b) => a + b, 0) / mapTime.length;
  document.getElementById("forTime").innerHTML = forTime.reduce((a,b) => a + b, 0) / forTime.length;
  document.getElementById("reduceTime").innerHTML = reduceTime.reduce((a,b) => a + b, 0) / reduceTime.length;
  document.getElementById("sliceTime").innerHTML = sliceTime.reduce((a,b) => a + b, 0) / sliceTime.length;
  document.getElementById("arrayFromTime").innerHTML = arrayFromTime.reduce((a,b) => a + b, 0) / arrayFromTime.length;
}

<View>
  <h1>cycle <span id="cycle"></span></h1>
  spread: <span id="spreadTime"></span> ms
  <br/>
  map: <span id="mapTime"></span> ms
  <br/>
  for: <span id="forTime"></span> ms
  <br/>
  reduce: <span id="reduceTime"></span> ms
  <br/>
  slice: <span id="sliceTime"></span> ms
  <br/>
  arrayFrom: <span id="arrayFromTime"></span> ms
  <br/>
</View>


问:
Filtering the camera preview
I am trying to display a filtered version of the camera preview.
The code runs without errors but the device is showing the preview instead of the generated bitmap.

This is the code for my (very small) Activity: http://code.google.com/p/ruellia/source/browse/ruellia/src/br/com/ximp/ruellia/RuelliaActivity.java

I suspect the view layering and the surface holder type, but so far no luck... anyone?

答:
There is small android demo in our java ocr project, which does exactly this:

http://sourceforge.net/projects/javaocr/

Compiled version:
https://market.android.com/details?id=de.pribluda.android.ocrcall&feature=search_result

ContentLicense: CC BY-SA 2.5

Title: Filtering the camera preview


问:
Why can't IntelliJ IDEA import local packages in Go project?
I'm using Idea plugin for Go to work with my project.
The structure of my project is the following:

controller, entity, model, repository etc - are local packages (where one can use another).

Unfortunately, Idea can't import one local package from another:

With remote packages everything is just fine.

My project settings:

What am I doing wrong?

答:
Indexing the Preferences -> Go -> GOPATH worked for me.

<img src="https://i.stack.imgur.com/ySArC.png" alt="Indexing the Preferences -> Go -> GOPATH worked for me.">


问:
The Angular Compiler requires TypeScript >=3.4.0 and <3.5.0 but 3.5.3 was found instead
I'm getting the following error when I do npm run build:

The Angular Compiler requires TypeScript >=3.4.0 and <3.5.0 but 3.5.3
  was found instead.

I've tried following things separately:

npm install typescript@">=3.4.0 <3.5.0". Then deleted node_modules and package.json. Run npm install

npm update --force.
  Then deleted node_modules and package.json. Run npm install

I'm still getting the error:

My package.json contains following dependencies:

```<code>  "dependencies": {
    "@angular/animations": "8.1.0",
    "@angular/cdk": "^8.0.2",
    "@angular/cli": "^8.1.0",
    "@angular/common": "8.1.0",
    "@angular/compiler": "8.1.0",
    "@angular/core": "8.1.0",
    "@angular/forms": "8.1.0",
    "@angular/http": "7.2.15",
    "@angular/material": "^8.0.2",
    "@angular/platform-browser": "8.1.0",
    "@angular/platform-browser-dynamic": "8.1.0",
    "@angular/router": "8.1.0",
    "@ngx-translate/core": "^11.0.1",
    "@ngx-translate/http-loader": "^4.0.0",
    "angular-user-idle": "^2.1.2",
    "angular2-cookie": "^1.2.6",
    "core-js": "^2.6.7",
    "rxjs": "6.5.2",
    "rxjs-tslint": "^0.1.5",
    "stream": "0.0.2",
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.801.0",
    "@angular/compiler-cli": "8.1.0",
    "@angular/language-service": "8.1.0",
    "@types/jasmine": "~3.3.13",
    "@types/jasminewd2": "~2.0.6",
    "@types/node": "~12.6.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "protractor": "~5.4.2",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "^3.4.5"
  }
</code>```

ng --version gives following output:

```<code>Angular CLI: 8.1.2
Node: 10.16.0
OS: win32 x64
Angular: 8.1.0
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.801.2
@angular-devkit/build-angular     0.801.2
@angular-devkit/build-optimizer   0.801.2
@angular-devkit/build-webpack     0.801.2
@angular-devkit/core              8.1.2
@angular-devkit/schematics        8.1.2
@angular/cdk                      8.1.1
@angular/cli                      8.1.2
@angular/http                     7.2.15
@angular/material                 8.1.1
@ngtools/webpack                  8.1.2
@schematics/angular               8.1.2
@schematics/update                0.801.2
rxjs                              6.5.2
typescript                        3.5.3
webpack                           4.35.2
</code>```

What could be going wrong here?

答:
You don't need to uninstall and again install the typescript so you can install the specific version of typescript as recommended in the error.

```<code>npm install typescript@ version
</code>```

or you can run

```<code>npm install typescript@ version --save-dev
</code>```

to save it in the package json

Body:
I'm getting the following error when I do npm run build:

The Angular Compiler requires TypeScript >=3.4.0 and <3.5.0 but 3.5.3
  was found instead.

I've tried following things separately:

npm install typescript@">=3.4.0 <3.5.0". Then deleted node_modules and package.json. Run npm install

npm update --force.
  Then deleted node_modules and package.json. Run npm install

I'm still getting the error:

My package.json contains following dependencies:

  "dependencies": {
    "@angular/animations": "8.1.0",
    "@angular/cdk": "^8.0.2",
    "@angular/cli": "^8.1.0",
    "@angular/common": "8.1.0",
    "@angular/compiler": "8.1.0",
    "@angular/core": "8.1.0",
    "@angular/forms": "8.1.0",
    "@angular/http": "7.2.15",
    "@angular/material": "^8.0.2",
    "@angular/platform-browser": "8.1.0",
    "@angular/platform-browser-dynamic": "8.1.0",
    "@angular/router": "8.1.0",
    "@ngx-translate/core": "^11.0.1",
    "@ngx-translate/http-loader": "^4.0.0",
    "angular-user-idle": "^2.1.2",
    "angular2-cookie": "^1.2.6",
    "core-js": "^2.6.7",
    "rxjs": "6.5.2",
    "rxjs-tslint": "^0.1.5",
    "stream": "0.0.2",
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.801.0",
    "@angular/compiler-cli": "8.1.0",
    "@angular/language-service": "8.1.0",
    "@types/jasmine": "~3.3.13",
    "@types/jasminewd2": "~2.0.6",
    "@types/node": "~12.6.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "protractor": "~5.4.2",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "^3.4.5"
  }

ng --version gives following output:

Angular CLI: 8.1.2
Node: 10.16.0
OS: win32 x64
Angular: 8.1.0
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.801.2
@angular-devkit/build-angular     0.801.2
@angular-devkit/build-optimizer   0.801.2
@angular-devkit/build-webpack     0.801.2
@angular-devkit/core              8.1.2
@angular-devkit/schematics        8.1.2
@angular/cdk                      8.1.1
@angular/cli                      8.1.2
@angular/http                     7.2.15
@angular/material                 8.1.1
@ngtools/webpack                  8.1.2
@schematics/angular               8.1.2
@schematics/update                0.801.2
rxjs                              6.5.2
typescript                        3.5.3
webpack                           4.35.2

What could be going wrong here?

Body:
You don't need to uninstall and again install the typescript so you can install the specific version of typescript as recommended in the error.

npm install typescript@ version

or you can run

npm install typescript@ version --save-dev

to save it in the package json


问:
Open popup when click on marker
I have this code :

```<code>popupIsOpen = false;
const marker: Marker = this.map.addMarkerSync(markerData);
marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(this.markerClick);

markerClick(params: any) {
        this.popupIsOpen = !this.popupIsOpen;
        const marker: Marker = params[1] as Marker;
}
</code>```

The template :

```<code><ion-content>
    <div id="map_canvas"></div>
</ion-content>
<div [ngClass]="{'overlay': popupIsOpen, 'hidden': !popupIsOpen}">
    <ion-card>
        <ion-card-content>
            <ion-button (click)="popupIsOpen=!popupIsOpen">close</ion-button>
             Content
        </ion-card-content>
    </ion-card>
</div>
</code>```

The popup is not displayed when I click on marker. What I’m doing wrong ? Thx in advance.

答:
The google map API events are not monkey patched by zone.js and therefore are not running in the ngZone. You should manually re-enter the zone using ngZone.run():

```<code>constructor(private ngZone: NgZone) {}

markerClick(params: Marker[]) {
  this.ngZone.run(() => {
    this.popupIsOpen = !this.popupIsOpen;
    const marker: Marker = params[1] as Marker;
  });
}
</code>```

There is also a possibility you are losing the this context, because you are not binding the events properly. There are several options, one is to use the anonymous arrow function notation when binding:

```<code>marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe((params) => this.markerClick(params));
</code>```

Title: Open popup when click on marker

Body:
I have this code :

popupIsOpen = false;
const marker: Marker = this.map.addMarkerSync(markerData);
marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(this.markerClick);

markerClick(params: any) {
        this.popupIsOpen = !this.popupIsOpen;
        const marker: Marker = params[1] as Marker;
}

The template :

<ion-content>

</ion-content>

    <ion-card>
        <ion-card-content>
            <ion-button (click)="popupIsOpen=!popupIsOpen">close</ion-button>
             Content
        </ion-card-content>
    </ion-card>

The popup is not displayed when I click on marker. What I’m doing wrong ? Thx in advance.

Body:
The google map API events are not monkey patched by zone.js and therefore are not running in the ngZone. You should manually re-enter the zone using ngZone.run():

constructor(private ngZone: NgZone) {}

markerClick(params: Marker[]) {
  this.ngZone.run(() => {
    this.popupIsOpen = !this.popupIsOpen;
    const marker: Marker = params[1] as Marker;
  });
}

There is also a possibility you are losing the this context, because you are not binding the events properly. There are several options, one is to use the anonymous arrow function notation when binding:

marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe((params) => this.markerClick(params));


问:
Styled-components using a prop inside of a keyframe animation
What's the proper way of using props inside of animation: ${styledKeyFrame} ${props.myProps}?

The issue:

```<code>import styled from 'styled-components';
const KeyFrameTest = styled.keyframes`
    from { opacity: 0; }
    to { opacity: 1; }
`;

const StyledComponent = styled.div`
 animation: ${KeyFrameTest} 2s 4s ease-in; /* works */
 animation: ${props => `${KeyFrameTest} 2s ${props.delay} ease-in`}; /* ERROR */
 animation: ${props => `${styled.css`{KeyFrameTest}}` 2s ${props.delay} ease-in`}; /* ERROR */
`;

const PureComponent = () => <StyledComponent delay="3s" />;
export default PureComponent;
</code>```

答:
I think the error is happening when you try to use KeyFrames inside the ${props => } syntax.

I don't know which version of styled-components you are using but I think this should work;

animation: ${KeyFrameTest} 2s ${props => props.delay} ease-in

Body:
What's the proper way of using props inside of animation: ${styledKeyFrame} ${props.myProps}?

The issue:

import styled from 'styled-components';
const KeyFrameTest = styled.keyframes`
    from { opacity: 0; }
    to { opacity: 1; }
`;

const StyledComponent = styled.div`
 animation: ${KeyFrameTest} 2s 4s ease-in; /* works */
 animation: ${props => `${KeyFrameTest} 2s ${props.delay} ease-in`}; /* ERROR */
 animation: ${props => `${styled.css`{KeyFrameTest}}` 2s ${props.delay} ease-in`}; /* ERROR */
`;

const PureComponent = () =>


问:
Load and merge two images in WPF
I try to write an application that create a watermarked image from the loaded jpeg in WPF.
I want to load in WPF an jpeg image and draw it with a predifined png with a transparence region  over.
I've tried to create two images as the RenderTargetBitmap and then create a new RenderTargetBitmap like

```<code>Image LoadSource(string file) {
  var image = new Image();
  var src = new BitmapImage();
  src.BeginInit();
  src.UriSource = new Uri(file, UriKind.Absolute);
  src.CacheOption = BitmapCacheOption.OnLoad;
  src.EndInit();
  image.Source = src;
  image.Stretch = Stretch.Uniform;
  image.Width = 1024;
  image.Height = 768;
  return image;
}

private void Window_Loaded(object sender, RoutedEventArgs e) {
  var imgA = LoadSource(@"D:\test\1.jpg");
  var imgB = LoadSource(@"D:\test\2.png");
  var bmp = new RenderTargetBitmap(1024, 768, 120, 96, PixelFormats.Pbgra32);
  bmp.Render(imgA);
  bmp.Render(imgB);
  ResultImage.Source = bmp;
}
</code>```

but it doen't work.

Can anyone point me at the solution?

答:
I have an easier solution:

XAML:

```<code><DockPanel>
    <Button DockPanel.Dock="Bottom" HorizontalAlignment="Right"
            Margin="12" Click="ButtonSave_OnClick" Content="_Save" />
    <Grid Name="MergedImage" Width="1024" Height="768"
            HorizontalAlignment="Center" VerticalAlignment="Center"
            AllowDrop="True" DragOver="MergedImage_DragEnter"
            Drop="MergedImage_Drop">
        <Image Name="SourcePicture"/>
        <Image Source="Watermark.png"/>
    </Grid>
</DockPanel>
</code>```

Code behind:

```<code>void ButtonSave_OnClick(object sender, RoutedEventArgs e)
{
    var dialog = new Microsoft.Win32.SaveFileDialog
    {
        DefaultExt = ".jpg",
        Filter = "Image (.jpg)|*.jpg"
    };

    if (dialog.ShowDialog() == true)
    {
        // Save my merged image as jpeg.
        // SaveAsJpeg(MergedImage, dialog.FileName);
    }
}

private void MergedImage_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, true);
        if (fileNames.Length == 1)
        {
            var file = new FileInfo(fileNames[0]);
            if (file.Extension.ToLower() == ".png" ||
                file.Extension.ToLower() == ".bmp" ||
                file.Extension.ToLower() == ".jpg" ||
                file.Extension.ToLower() == ".jpeg" ||
                file.Extension.ToLower() == ".gif")
            {
                e.Effects = DragDropEffects.Copy;
                e.Handled = true;
                return;
            }
        }
    }
    e.Effects = DragDropEffects.None;
    e.Handled = true;
}

private void MergedImage_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, true);
        SourcePicture.Source = new BitmapImage(new Uri(fileNames[0],
            UriKind.Absolute));
        Application.Current.MainWindow.Activate();
    }
}
</code>```

Title: Load and merge two images in WPF

Body:
I try to write an application that create a watermarked image from the loaded jpeg in WPF.
I want to load in WPF an jpeg image and draw it with a predifined png with a transparence region  over.
I've tried to create two images as the RenderTargetBitmap and then create a new RenderTargetBitmap like

Image LoadSource(string file) {
  var image = new Image();
  var src = new BitmapImage();
  src.BeginInit();
  src.UriSource = new Uri(file, UriKind.Absolute);
  src.CacheOption = BitmapCacheOption.OnLoad;
  src.EndInit();
  image.Source = src;
  image.Stretch = Stretch.Uniform;
  image.Width = 1024;
  image.Height = 768;
  return image;
}

private void Window_Loaded(object sender, RoutedEventArgs e) {
  var imgA = LoadSource(@"D:\test\1.jpg");
  var imgB = LoadSource(@"D:\test\2.png");
  var bmp = new RenderTargetBitmap(1024, 768, 120, 96, PixelFormats.Pbgra32);
  bmp.Render(imgA);
  bmp.Render(imgB);
  ResultImage.Source = bmp;
}

but it doen't work.

Can anyone point me at the solution?

Body:
I have an easier solution:

XAML:

<DockPanel>
    <Button DockPanel.Dock="Bottom" HorizontalAlignment="Right"
            Margin="12" Click="ButtonSave_OnClick" Content="_Save" />
    <Grid Name="MergedImage" Width="1024" Height="768"
            HorizontalAlignment="Center" VerticalAlignment="Center"
            AllowDrop="True" DragOver="MergedImage_DragEnter"
            Drop="MergedImage_Drop">
        <Image Name="SourcePicture"/>
        <Image Source="Watermark.png"/>
    </Grid>
</DockPanel>

Code behind:

void ButtonSave_OnClick(object sender, RoutedEventArgs e)
{
    var dialog = new Microsoft.Win32.SaveFileDialog
    {
        DefaultExt = ".jpg",
        Filter = "Image (.jpg)|*.jpg"
    };

    if (dialog.ShowDialog() == true)
    {
        // Save my merged image as jpeg.
        // SaveAsJpeg(MergedImage, dialog.FileName);
    }
}

private void MergedImage_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, true);
        if (fileNames.Length == 1)
        {
            var file = new FileInfo(fileNames[0]);
            if (file.Extension.ToLower() == ".png" ||
                file.Extension.ToLower() == ".bmp" ||
                file.Extension.ToLower() == ".jpg" ||
                file.Extension.ToLower() == ".jpeg" ||
                file.Extension.ToLower() == ".gif")
            {
                e.Effects = DragDropEffects.Copy;
                e.Handled = true;
                return;
            }
        }
    }
    e.Effects = DragDropEffects.None;
    e.Handled = true;
}

private void MergedImage_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, true);
        SourcePicture.Source = new BitmapImage(new Uri(fileNames[0],
            UriKind.Absolute));
        Application.Current.MainWindow.Activate();
    }
}