问:
Fragment content overlapping toolbar
Implementing a BottomNavigationView with viewpager and tablayout.Each navigation view is a fragment in first fragment ("NewsFeedFragment") i want to use tablayout attached with a viewpager. Result come correct but the content of the fragment overlaps the parent toolbar.

Here is how i am trying to use it.

Home.xml

```<code><android.support.design.widget.CoordinatorLayout 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:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.M1Activity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="6dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation" />
</code>```

NewsFragment.xml

```<code><LinearLayout 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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.HomeActivity">

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:tabGravity="fill"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorAccent"
    app:tabTextColor="#FFF" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

Here is result i get.

And what i basically trying exactly to implement is.

答:
```<code><android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:titleEnabled="false">

Map view is just a view that you want to collapse on scroll replace with your widget

     <com.google.android.gms.maps.MapView
            android:id="@+id/mapView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            app:layout_collapseMode="parallax" />

Widget that you want to display after collapse

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
     app:layout_collapseMode="pin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/colorAccent"
        app:tabTextColor="#FFF" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

     <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

        All your component to display should be here

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout >
</code>```

Title: Fragment content overlapping toolbar

Body:
Implementing a BottomNavigationView with viewpager and tablayout.Each navigation view is a fragment in first fragment ("NewsFeedFragment") i want to use tablayout attached with a viewpager. Result come correct but the content of the fragment overlaps the parent toolbar.

Here is how i am trying to use it.

Home.xml

<android.support.design.widget.CoordinatorLayout 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:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.M1Activity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="6dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation" />

NewsFragment.xml

<LinearLayout 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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.HomeActivity">

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:tabGravity="fill"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorAccent"
    app:tabTextColor="#FFF" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Here is result i get.

And what i basically trying exactly to implement is.


来源: stackexchange

问:
Bootstrap InputFile Initial Preview Shows image as original size
I'm using Krajee Bootstrap FileInput. I'm using initialPreview tag and have below issues:

Initial image is shown in original image size not the thumbnail size

Cannot delete the initial image.

I have use overwriteInitial and autoReplace, but when I add a new image, the initial is still there. I expect it overwrite the initial image but it doesn't

This is my script:

```<code><script>
    $("#file-1").fileinput({
        initialPreview: [
            "<img src='/img/Tulips.jpg' class='file-preview-image' title='Desert'>"
        ],
        uploadUrl: "@Url.Action("upload","Home")",
        uploadAsync: true,
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        maxFilesNum: 1,
        allowedFileTypes: ['image'],
        overwriteInitial: true,
        autoReplace: true,
        showUpload: true,
        showCaption: true,
        showUploadedThumbs: true,
    });
</script>
</code>```

答:
maybe set size in width in img tag?

```<code><script>
$("#file-1").fileinput({
    initialPreview: [
        "<img src='/img/Tulips.jpg' class='file-preview-image' title='Desert' width='120' >"
    ],
    uploadUrl: "@Url.Action("upload","Home")",
    uploadAsync: true,
    allowedFileExtensions: ['jpg', 'png', 'gif'],
    maxFilesNum: 1,
    allowedFileTypes: ['image'],
    overwriteInitial: true,
    autoReplace: true,
    showUpload: true,
    showCaption: true,
    showUploadedThumbs: true,
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
maybe set size in width in img tag?

<script>
$("#file-1").fileinput({
    initialPreview: [
        "<img src='/img/Tulips.jpg' class='file-preview-image' title='Desert' width='120' >"
    ],
    uploadUrl: "@Url.Action("upload","Home")",
    uploadAsync: true,
    allowedFileExtensions: ['jpg', 'png', 'gif'],
    maxFilesNum: 1,
    allowedFileTypes: ['image'],
    overwriteInitial: true,
    autoReplace: true,
    showUpload: true,
    showCaption: true,
    showUploadedThumbs: true,
});


问:
How to use count and group by at the same select statement
I have an SQL SELECT query that also uses a GROUP BY,
I want to count all the records after the GROUP BY clause filtered the resultset.

Is there any way to do this directly with SQL? For example, if I have the table users and want to select the different towns and the total number of users:

SELECT `town`, COUNT(*)
FROM `user`
GROUP BY  `town`;
```

I want to have a column with all the towns and another with the number of users in all rows.

An example of the result for having 3 towns and 58 users in total is:

Town
Count

Copenhagen
58

New York
58

Athens
58

答:
if You Want to use Select All Query With Count Option, try this...</p>

```<code> select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name  as a where where Condition
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an SQL SELECT query that also uses a GROUP BY,
I want to count all the records after the GROUP BY clause filtered the resultset.

Is there any way to do this directly with SQL? For example, if I have the table users and want to select the different towns and the total number of users:

SELECT `town`, COUNT(*)
FROM `user`
GROUP BY  `town`;

I want to have a column with all the towns and another with the number of users in all rows.

An example of the result for having 3 towns and 58 users in total is:

Town
Count

Copenhagen
58

New York
58

Athens
58

Body:
if You Want to use Select All Query With Count Option, try this...

 select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name  as a where where Condition


问:
express js api end point does not work on azure web app
I just tried creating a test api app using Express js. i embraced many ways available on internet to deploy and run node js api app. But nothing is working in my case. Please help me.

Other wise i will have to leave either azure or node js.

I am attaching all the files below:
1.index.js

var express = require('express');
var app = express();

router.get('/things', function(req, res) {
    res.json('GET route on things.');
});
router.post('/things', function(req, res) {
    res.json('POST route on things.');
});

app.get('/hello', function(req, res) {
    res.json("Hello World!");
});

app.post('/hello', function(req, res) {
    res.json("You just called the post method at '/hello'!\n");
});

const port = process.env.PORT || 1337;
app.listen(port);```
</div>
</div>

2.package-lock.json</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-js lang-js prettyprint-override"><code>{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}</code>```

3.package.json

{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}```
</div>
</div>
</p>

<p>4.web.config</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-js lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
        </handlers>
        <rewrite>
      <rules>
        <rule name="myapp">
          <match url="/*" />
          <action type="Rewrite" url="index.js" />
        </rule>
      </rules>
    </rewrite>
    </system.webServer>
</configuration></code>```

答:
var express = require('express');
var app = express();
var router = express.Router();

router.get('/things', function(req, res) {
    res.json('GET route on things.');
});
router.post('/things', function(req, res) {
    res.json('POST route on things.');
});

app.get('/hello', function(req, res) {
    res.json("Hello World!");
});

app.post('/hello', function(req, res) {
    res.json("You just called the post method at '/hello'!\n");
});

const port = process.env.PORT || 1337;
app.listen(port);```

Body:
I just tried creating a test api app using Express js. i embraced many ways available on internet to deploy and run node js api app. But nothing is working in my case. Please help me.

Other wise i will have to leave either azure or node js.

I am attaching all the files below:
1.index.js

var express = require('express');
var app = express();

router.get('/things', function(req, res) {
    res.json('GET route on things.');
});
router.post('/things', function(req, res) {
    res.json('POST route on things.');
});

app.get('/hello', function(req, res) {
    res.json("Hello World!");
});

app.post('/hello', function(req, res) {
    res.json("You just called the post method at '/hello'!\n");
});

const port = process.env.PORT || 1337;
app.listen(port);

2.package-lock.json

{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}

3.package.json

{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}

4.web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
        </handlers>
        <rewrite>
      <rules>
        <rule name="myapp">
          <match url="/*" />
          <action type="Rewrite" url="index.js" />
        </rule>
      </rules>
    </rewrite>
    </system.webServer>
</configuration>


问:
Validate JSON object against a flexible set of rules?
I am use metosin/scjsv to validate the json body of a POST request.

I would like to validate against the following rules:

Any value should be allowed for the element key within the mapping object so long as it conforms to this regex: ^[a-z_][a-z\\d_]*$

Only the object: {:attribute : {:type "string"}} should be allowed as the value of an element within the mapping object.

This is an example of a valid json object:

```<code>{
   "mapping" : {
              "attr_a" : {
                          "attribute" : "a"
                         },
              "attr_b" : {
                          "attribute" : "b"
                         }
             }
 }
</code>```

Here is the schema I have defined so far, it fails to valid how I would like it to:

```<code>(def schema {:type       "object"
         :properties {:mapping {:type    "object"
                                :pattern "^[a-z_][a-z\\d_]*$"
                                {:$attr {:type       "object"
                                         :properties {:attribute {:type "string"}}
                                         :required   [:attribute]}}}}})
</code>```

答:
I should have used patternProperties and additionalProperties.

```<code>(def schema {:type       "object"
     :properties {:mapping {:type    "object"
                            :patternProperties {"^[a-z_][a-z\\d_]*$" {:type       "object"
                                     :properties {:attribute {:type "string"}}
                                     :required   [:attribute]}}}}})
</code>```

Body:
I am use metosin/scjsv to validate the json body of a POST request.

I would like to validate against the following rules:

Any value should be allowed for the element key within the mapping object so long as it conforms to this regex: ^[a-z_][a-z\\d_]*$

Only the object: {:attribute : {:type "string"}} should be allowed as the value of an element within the mapping object.

This is an example of a valid json object:

{
   "mapping" : {
              "attr_a" : {
                          "attribute" : "a"
                         },
              "attr_b" : {
                          "attribute" : "b"
                         }
             }
 }

Here is the schema I have defined so far, it fails to valid how I would like it to:

(def schema {:type       "object"
         :properties {:mapping {:type    "object"
                                :pattern "^[a-z_][a-z\\d_]*$"
                                {:$attr {:type       "object"
                                         :properties {:attribute {:type "string"}}
                                         :required   [:attribute]}}}}})

Body:
I should have used patternProperties and additionalProperties.

(def schema {:type       "object"
     :properties {:mapping {:type    "object"
                            :patternProperties {"^[a-z_][a-z\\d_]*$" {:type       "object"
                                     :properties {:attribute {:type "string"}}
                                     :required   [:attribute]}}}}})


问:
How can objective C classes be encrypted
I would like to encrypt a few of my obj c classes in my iphone game which handle openfeint data and classes which handle scores.

I have heard there is a way to encrypt this data to act as another level of security, at least enough to discourage some from cracking it and forging scores on a jailbroken iphone and then spam the leaderboards.

How is this done, what are good techniques to secure this data and discourage some from attempting to spoof data?

Thanks

答:
Encrypting classes suffers the "shipping the lock with the key" problem that any DRM or similar security system has.

What you are looking for is self modifying code, where the code is either loaded and decrypted later by the application, or is present as machine code in the binary and modified at runtime by a key the application has.

Note that you'll likely create some very subtle and interesting bugs, and your method will be bypassed (it will take someone maybe an extra day).

ContentLicense: CC BY-SA 2.5


问:
Laravel query not returns all values
I'm trying to make simple forum on laravel. I have two tables:
categories:

forums:

I run query:

```<code>$categories = DB::table('forums')
        ->join('categories', 'forums.fid', '=', 'categories.cid')
        ->select('categories.*', 'forums.*')
        ->get();
</code>```

I receive only two results:

```<code>[{"cid" :1,
  "name": "First forum",
  "fid": 1,
  "seo_name": "first-forum",
  "category_id": 1
 },
 {"cid": 2,
  "name": "Another forum",
  "fid": 2,
  "seo_name": "another-forum",
  "category_id": 2
 }]
</code>```

Why only 1 result for category_id 1? I have two forums in that category. Thanks in advance and sorry for my bad English.

答:
Update query to:</p>

```<code>$categories = DB::table('forums')
        ->join('categories', 'forums.category_id', '=', 'categories.cid')
        ->select('categories.*', 'forums.*')
        ->get();
</code>```

Title: Laravel query not returns all values

Body:
I'm trying to make simple forum on laravel. I have two tables:
categories:

forums:

I run query:

$categories = DB::table('forums')
        ->join('categories', 'forums.fid', '=', 'categories.cid')
        ->select('categories.*', 'forums.*')
        ->get();

I receive only two results:

[{"cid" :1,
  "name": "First forum",
  "fid": 1,
  "seo_name": "first-forum",
  "category_id": 1
 },
 {"cid": 2,
  "name": "Another forum",
  "fid": 2,
  "seo_name": "another-forum",
  "category_id": 2
 }]

Why only 1 result for category_id 1? I have two forums in that category. Thanks in advance and sorry for my bad English.

Body:
Update query to:

$categories = DB::table('forums')
        ->join('categories', 'forums.category_id', '=', 'categories.cid')
        ->select('categories.*', 'forums.*')
        ->get();


问:
How to calculate an angle from points?
I want to get a simple solution to calculate the angle of a line (like a pointer of a clock).

I have 2 points:

```<code>cX, cY - the center of the line.
eX, eY - the end of the line.

The result is angle (0 <= a < 360).
</code>```

Which function is able to provide this value?

答:
If you're using canvas, you'll notice (if you haven't already) that canvas uses clockwise rotation(MDN) and y axis is flipped. To get consistent results, you need to tweak your angle function.

From time to time, I need to write this function and each time I need to look it up, because I never get to the bottom of the calculation.

While the suggested solutions work, they don't take the canvas coordinate system into consideration. Examine the following demo:

Calculate angle from points - JSFiddle

```<code>function angle(originX, originY, targetX, targetY) {
    var dx = originX - targetX;
    var dy = originY - targetY;

    // var theta = Math.atan2(dy, dx);  // [0, Ⲡ] then [-Ⲡ, 0]; clockwise; 0° = west
    // theta *= 180 / Math.PI;          // [0, 180] then [-180, 0]; clockwise; 0° = west
    // if (theta < 0) theta += 360;     // [0, 360]; clockwise; 0° = west

    // var theta = Math.atan2(-dy, dx); // [0, Ⲡ] then [-Ⲡ, 0]; anticlockwise; 0° = west
    // theta *= 180 / Math.PI;          // [0, 180] then [-180, 0]; anticlockwise; 0° = west
    // if (theta < 0) theta += 360;     // [0, 360]; anticlockwise; 0° = west

    // var theta = Math.atan2(dy, -dx); // [0, Ⲡ] then [-Ⲡ, 0]; anticlockwise; 0° = east
    // theta *= 180 / Math.PI;          // [0, 180] then [-180, 0]; anticlockwise; 0° = east
    // if (theta < 0) theta += 360;     // [0, 360]; anticlockwise; 0° = east

    var theta = Math.atan2(-dy, -dx); // [0, Ⲡ] then [-Ⲡ, 0]; clockwise; 0° = east
    theta *= 180 / Math.PI;           // [0, 180] then [-180, 0]; clockwise; 0° = east
    if (theta < 0) theta += 360;      // [0, 360]; clockwise; 0° = east

    return theta;
}
</code>```

Title: How to calculate an angle from points?

Body:
I want to get a simple solution to calculate the angle of a line (like a pointer of a clock).

I have 2 points:

cX, cY - the center of the line.
eX, eY - the end of the line.

The result is angle (0 <= a < 360).

Which function is able to provide this value?

Body:
If you're using canvas, you'll notice (if you haven't already) that canvas uses clockwise rotation(MDN) and y axis is flipped. To get consistent results, you need to tweak your angle function.

From time to time, I need to write this function and each time I need to look it up, because I never get to the bottom of the calculation.

While the suggested solutions work, they don't take the canvas coordinate system into consideration. Examine the following demo:

Calculate angle from points - JSFiddle

function angle(originX, originY, targetX, targetY) {
    var dx = originX - targetX;
    var dy = originY - targetY;

    // var theta = Math.atan2(dy, dx);  // [0, Ⲡ] then [-Ⲡ, 0]; clockwise; 0° = west
    // theta *= 180 / Math.PI;          // [0, 180] then [-180, 0]; clockwise; 0° = west
    // if (theta < 0) theta += 360;     // [0, 360]; clockwise; 0° = west

    // var theta = Math.atan2(-dy, dx); // [0, Ⲡ] then [-Ⲡ, 0]; anticlockwise; 0° = west
    // theta *= 180 / Math.PI;          // [0, 180] then [-180, 0]; anticlockwise; 0° = west
    // if (theta < 0) theta += 360;     // [0, 360]; anticlockwise; 0° = west

    // var theta = Math.atan2(dy, -dx); // [0, Ⲡ] then [-Ⲡ, 0]; anticlockwise; 0° = east
    // theta *= 180 / Math.PI;          // [0, 180] then [-180, 0]; anticlockwise; 0° = east
    // if (theta < 0) theta += 360;     // [0, 360]; anticlockwise; 0° = east

    var theta = Math.atan2(-dy, -dx); // [0, Ⲡ] then [-Ⲡ, 0]; clockwise; 0° = east
    theta *= 180 / Math.PI;           // [0, 180] then [-180, 0]; clockwise; 0° = east
    if (theta < 0) theta += 360;      // [0, 360]; clockwise; 0° = east

    return theta;
}


问:
Alamofire post body format is not correct
I use Alamofire to call api methods. I use it like this

```<code>Alamofire.request("some api",
        method:method,
        parameters:body,
        encoding:URLEncoding.default,
        headers: finalHeaders)
        .responseJSON { (apiResponse) in
        ...
</code>```

body is a Dictionary of Strings and Any. When I send a post request server gets something like this as body:

```<code>key1=StringValue&key2=intValue
</code>```

While I need my body format be like this:

```<code>"key1":"StringValue","key2":intValue
</code>```

What parameter is not set or is set wrongly?

答:
Set content type as JSON.

```<code>_ = ["Content-Type": "application/json"]
</code>```

Check this answer
Alamofire Accept and Content-Type JSON

Body:
I use Alamofire to call api methods. I use it like this

Alamofire.request("some api",
        method:method,
        parameters:body,
        encoding:URLEncoding.default,
        headers: finalHeaders)
        .responseJSON { (apiResponse) in
        ...

body is a Dictionary of Strings and Any. When I send a post request server gets something like this as body:

key1=StringValue&key2=intValue

While I need my body format be like this:

"key1":"StringValue","key2":intValue

What parameter is not set or is set wrongly?

Body:
Set content type as JSON.

_ = ["Content-Type": "application/json"]

Check this answer
Alamofire Accept and Content-Type JSON


问:
Angular2. Method in component is being called multiple times and returns the wrong data
I have a method inside a module that is being called 3 times when the page load and it returns the wrong data. When debugging / checking the console it appears as the right data is being returned but on the screen the data is wrong

in component.html i have

```<code><p ng-if="posting">
 {{ getPlaceholderText('headline') }}
</p>
</code>```

This is the method:

```<code>getPlaceholderText(placeholderName: string): string {

console.log('Looking for placeholder with name "' + placeholderName + '"');

if (this.posting.placeholders != null) {

  this.posting.placeholders.forEach(placeholder => {
    if (placeholder.name === placeholderName) {
      console.log('found placeholder with name "' + placeholderName + '"');
      console.log('Returning value: "' + placeholder.text + '"');
      console.log('');
      return placeholder.text;
    }
  });
} else {
  return 'posting.placeholder is null';
}

console.log('');
console.log('placeholder with name "' + placeholderName + '" not found');
return 'placeholder with name "' + placeholderName + '" not found';
}
</code>```

When the pages is rendered this is output:

```<code>placeholder with name "headline" not found
</code>```

It should have been the value of placeholder.text property. In the console I have this:

```<code>Looking for placeholder with name "headline"
found placeholder with name "headline"
Returning value: "Standard Post 1 headline"

placeholder with name "headline" not found

Looking for placeholder with name "headline"
found placeholder with name "headline"
Returning value: "Standard Post 1 headline"

placeholder with name "headline" not found
</code>```

Anyone can put some light on what is going on here?

Here is the complete code for my component:

```<code>import { Component, OnInit } from '@angular/core';
import { environment } from '../../environments/environment';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { Posting } from '../models/Posting';
import { SiteService } from '../shared/siteService/siteService.service';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.scss']
})
export class PostComponent implements OnInit {

  version: string = environment.version;
  postingId: number;
  sub: any;
  isLoading: boolean;
  posting: Posting;
  postingTitle: string;

  constructor(
    private route: ActivatedRoute,
    private titleService: Title,
    private siteService: SiteService) { }

  ngOnInit() {

    this.isLoading = true;
    this.posting = new Posting();

    this.sub = this.route.params.subscribe(params => {
      this.postingId = +params['id'];
      this.postingTitle = params['title'];

      this.titleService.setTitle(this.postingTitle);

      this.siteService.getPost({ id: this.postingId })
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(posting => this.posting = posting);
    });
  }

  getPlaceholderText(placeholderName: string): string {

    console.log('Looking for placeholder with name "' + placeholderName + '"');

    if (this.posting.placeholders != null) {

      this.posting.placeholders.forEach(placeholder => {
        if (placeholder.name === placeholderName) {
          console.log('found placeholder with name "' + placeholderName + '"');
          console.log('Returning value: "' + placeholder.text + '"');
          console.log('');
          return placeholder.text;
        }
      });
    } else {
      return 'posting.placeholder is null';
    }

    console.log('placeholder with name "' + placeholderName + '" not found');
    return 'placeholder with name "' + placeholderName + '" not found';
  }
}
</code>```

答:
ahhh "forEach" is not TypeScript. It is javascript, so

```<code>this.posting.placeholders.forEach(placeholder => {
</code>```

should be

```<code>for (const placeholder of this.posting.placeholders) {
</code>```

and then it works

Body:
I have a method inside a module that is being called 3 times when the page load and it returns the wrong data. When debugging / checking the console it appears as the right data is being returned but on the screen the data is wrong

in component.html i have

 {{ getPlaceholderText('headline') }}

This is the method:

getPlaceholderText(placeholderName: string): string {

console.log('Looking for placeholder with name "' + placeholderName + '"');

if (this.posting.placeholders != null) {

  this.posting.placeholders.forEach(placeholder => {
    if (placeholder.name === placeholderName) {
      console.log('found placeholder with name "' + placeholderName + '"');
      console.log('Returning value: "' + placeholder.text + '"');
      console.log('');
      return placeholder.text;
    }
  });
} else {
  return 'posting.placeholder is null';
}

console.log('');
console.log('placeholder with name "' + placeholderName + '" not found');
return 'placeholder with name "' + placeholderName + '" not found';
}

When the pages is rendered this is output:

placeholder with name "headline" not found

It should have been the value of placeholder.text property. In the console I have this:

Looking for placeholder with name "headline"
found placeholder with name "headline"
Returning value: "Standard Post 1 headline"

placeholder with name "headline" not found

Looking for placeholder with name "headline"
found placeholder with name "headline"
Returning value: "Standard Post 1 headline"

placeholder with name "headline" not found

Anyone can put some light on what is going on here?

Here is the complete code for my component:

import { Component, OnInit } from '@angular/core';
import { environment } from '../../environments/environment';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { Posting } from '../models/Posting';
import { SiteService } from '../shared/siteService/siteService.service';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.scss']
})
export class PostComponent implements OnInit {

  version: string = environment.version;
  postingId: number;
  sub: any;
  isLoading: boolean;
  posting: Posting;
  postingTitle: string;

  constructor(
    private route: ActivatedRoute,
    private titleService: Title,
    private siteService: SiteService) { }

  ngOnInit() {

    this.isLoading = true;
    this.posting = new Posting();

    this.sub = this.route.params.subscribe(params => {
      this.postingId = +params['id'];
      this.postingTitle = params['title'];

      this.titleService.setTitle(this.postingTitle);

      this.siteService.getPost({ id: this.postingId })
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(posting => this.posting = posting);
    });
  }

  getPlaceholderText(placeholderName: string): string {

    console.log('Looking for placeholder with name "' + placeholderName + '"');

    if (this.posting.placeholders != null) {

      this.posting.placeholders.forEach(placeholder => {
        if (placeholder.name === placeholderName) {
          console.log('found placeholder with name "' + placeholderName + '"');
          console.log('Returning value: "' + placeholder.text + '"');
          console.log('');
          return placeholder.text;
        }
      });
    } else {
      return 'posting.placeholder is null';
    }

    console.log('placeholder with name "' + placeholderName + '" not found');
    return 'placeholder with name "' + placeholderName + '" not found';
  }
}

Body:
ahhh "forEach" is not TypeScript. It is javascript, so

this.posting.placeholders.forEach(placeholder => {

should be

for (const placeholder of this.posting.placeholders) {

and then it works


问:
Decoding unknown Encodable enum values to a default
I have to deserialize a JSON string like this:

```<code>{ "name" : "John Smith", "value" : "someValue" }
</code>```

in Swift 4, where "value" should be a enum and the whole object is a struct like:

```<code>struct MyType {
    name: String?
    value: Value?
}
</code>```

At some point in the future, there might be new enum values added in the backend so I thought it would be smart to have some fallback.

I thought I could create a enum like

```<code>enum Value {
    case someValue
    case someOtherValue
    case unknown(value: String)
}
</code>```

but I just can't wrap my head around how to deserialize that enum and make it work. Previously I simply used a String enum, but deserializing unknown values throws errors.

Is there a simple way to make that work or should I deserialize the value as a String and create a custom getter in the struct with a switch statement to return one of the cases (probably not even in the struct itself but in my view model)?

答:
You can implement init(from decoder: Decoder) and encode(to encoder: Encoder) and handle every case explicitly, i.e.

```<code>struct MyType: Codable {
    var name: String?
    var value: Value?

    enum CodingKeys: String, CodingKey {
        case name
        case value
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        let strValue = try values.decode(String.self, forKey: .value)
        //You need to handle every case explicitly
        switch strValue {
        case "someValue":
            value = Value.someValue
        case "someOtherValue":
            value = Value.someOtherValue
        default:
            value = Value.unknown(value: strValue)
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        if let val = value {
            //You need to handle every case explicitly
            switch val {
            case .someValue, .someOtherValue:
                try container.encode(String(describing: val), forKey: .value)
            case .unknown(let strValue):
                try container.encode(strValue, forKey: .value)
            }
        }
    }
}

enum Value {
    case someValue
    case someOtherValue
    case unknown(value: String)
}
</code>```

Body:
I have to deserialize a JSON string like this:

{ "name" : "John Smith", "value" : "someValue" }

in Swift 4, where "value" should be a enum and the whole object is a struct like:

struct MyType {
    name: String?
    value: Value?
}

At some point in the future, there might be new enum values added in the backend so I thought it would be smart to have some fallback.

I thought I could create a enum like

enum Value {
    case someValue
    case someOtherValue
    case unknown(value: String)
}

but I just can't wrap my head around how to deserialize that enum and make it work. Previously I simply used a String enum, but deserializing unknown values throws errors.

Is there a simple way to make that work or should I deserialize the value as a String and create a custom getter in the struct with a switch statement to return one of the cases (probably not even in the struct itself but in my view model)?

Body:
You can implement init(from decoder: Decoder) and encode(to encoder: Encoder) and handle every case explicitly, i.e.

struct MyType: Codable {
    var name: String?
    var value: Value?

    enum CodingKeys: String, CodingKey {
        case name
        case value
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        let strValue = try values.decode(String.self, forKey: .value)
        //You need to handle every case explicitly
        switch strValue {
        case "someValue":
            value = Value.someValue
        case "someOtherValue":
            value = Value.someOtherValue
        default:
            value = Value.unknown(value: strValue)
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        if let val = value {
            //You need to handle every case explicitly
            switch val {
            case .someValue, .someOtherValue:
                try container.encode(String(describing: val), forKey: .value)
            case .unknown(let strValue):
                try container.encode(strValue, forKey: .value)
            }
        }
    }
}

enum Value {
    case someValue
    case someOtherValue
    case unknown(value: String)
}


问:
Rails 2.3.x - how does this ActiveRecord scope work?
There's a named_scope in a project I'm working on that looks like the following:

```<code> # default product scope only lists available and non-deleted products
  ::Product.named_scope :active,      lambda { |*args|
    Product.not_deleted.available(args.first).scope(:find)
  }
</code>```

The initial named_scope makes sense. The confusing part here is how .scope(:find) works. This is clearly calling another named scope (not_deleted), and applying .scope(:find) afterwards. What/how does .scope(:find) work here?

答:
A quick answer

```<code>Product.not_deleted.available(args.first)
</code>```

is a named-scope itself, formed by combining both named scopes.

scope(:find) gets the conditions for a named-scope (or combination of scopes), which you can in turn use to create a new named-scope.

So by example:

```<code>named_scope :active,      :conditions => 'active  = true'
named_scope :not_deleted, :conditions => 'deleted = false'
</code>```

then you write

```<code>named_scope :active_and_not_deleted, :conditions => 'active = true and deleted = false'
</code>```

or, you could write

```<code>named_scope :active_and_not_deleted, lambda { self.active.not_deleted.scope(:find) }
</code>```

which is identical. I hope that makes it clear.

Note that this has become simpler (cleaner) in rails 3, you would just write

```<code>scope :active_and_not_deleted, active.not_deleted
</code>```

Body:
There's a named_scope in a project I'm working on that looks like the following:

 # default product scope only lists available and non-deleted products
  ::Product.named_scope :active,      lambda { |*args|
    Product.not_deleted.available(args.first).scope(:find)
  }

The initial named_scope makes sense. The confusing part here is how .scope(:find) works. This is clearly calling another named scope (not_deleted), and applying .scope(:find) afterwards. What/how does .scope(:find) work here?

Body:
A quick answer

Product.not_deleted.available(args.first)

is a named-scope itself, formed by combining both named scopes.

scope(:find) gets the conditions for a named-scope (or combination of scopes), which you can in turn use to create a new named-scope.

So by example:

named_scope :active,      :conditions => 'active  = true'
named_scope :not_deleted, :conditions => 'deleted = false'

then you write

named_scope :active_and_not_deleted, :conditions => 'active = true and deleted = false'

or, you could write

named_scope :active_and_not_deleted, lambda { self.active.not_deleted.scope(:find) }

which is identical. I hope that makes it clear.

Note that this has become simpler (cleaner) in rails 3, you would just write

scope :active_and_not_deleted, active.not_deleted


问:
Background version of uploaded video creation in Elixir with Arc and FFmpeg
I tried to make video uploading on Elixir phoenix project using Arc. I need to have different size versions of video. So I used FFmpeg to do this:

```<code>def transform(:large, {file, scope}) do
  {:ffmpeg, fn(input, output) -> "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end, :mp4}
end
</code>```

However, it takes a lot of time to create this versions even to small videos. So, I decided to make version creation on background. I want Arc to upload video, then I give the response with uploaded original while other versions are creating.

I was hoping to find such option at https://github.com/stavro/arc but I didn't succed. I only found "To disable asynchronous processing, add @async false to your upload definition" but I don't want to disable it, right?

I tried to use Exq https://github.com/akira/exq for background processing but I didn't menage to use it in uploader.

Could anybody tell me how it should be made in a proper way or give me some dirty hack advice to make it work. Thanks.

I tried Task as was advised in comments, but I am not sure how to use them in this case. When I try

```<code>{:ffmpeg, fn(input, output) -> Task.async(fn -> "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end) end, :mp4}
</code>```

or

```<code>{:ffmpeg, Task.async(fn -> fn(input, output) ->  "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end end), :mp4}
</code>```

I got "protocol String.Chars not implemented for %Task".

When I try

```<code>{:ffmpeg, Task.async(fn(input, output) ->  "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end), :mp4}
</code>```

I got "#Function<20.83953603/2 in MyWebSite.Content.transform/2> with arity 2 called with no arguments". I tried to pass function as an argument with "&" but it fails as well.

My uploader:

```<code>defmodule MyWebSite.Content do
use Arc.Definition
use Arc.Ecto.Definition

@acl :public_read

@versions [:original,  :huge]

def transform(:huge, {file, scope}) do
  {:ffmpeg, Task.async(fn(input, output) ->  "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end), :mp4}
end

def s3_object_headers(version, {file, scope}) do
  [timeout: 3_000_00, content_type: Plug.MIME.path(file.file_name)]
end
end
</code>```

答:
From the Arc’s README (section Complex Transformations):

However, the transformation may be done completely outside of Arc. For fine-grained transformations, you should create an executable wrapper in your $PATH (eg. bash script) which takes these proper arguments, runs your transformation, and then moves the file into the correct location**.

That said, if you want the transformation to be run completely asynchronously, just create a bash script somewhere and call it like (assuming it’s name is myffmpeg):

```<code>def transform(:huge, {file, scope}) do
  {:myffmpeg,
     fn ->
       "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}"
     end,
   :mp4}
end
</code>```

The script should spawn ffmpeg passing the arguments and move the result to the folder Arc wants.

Body:
I tried to make video uploading on Elixir phoenix project using Arc. I need to have different size versions of video. So I used FFmpeg to do this:

def transform(:large, {file, scope}) do
  {:ffmpeg, fn(input, output) -> "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end, :mp4}
end

However, it takes a lot of time to create this versions even to small videos. So, I decided to make version creation on background. I want Arc to upload video, then I give the response with uploaded original while other versions are creating.

I was hoping to find such option at https://github.com/stavro/arc but I didn't succed. I only found "To disable asynchronous processing, add @async false to your upload definition" but I don't want to disable it, right?

I tried to use Exq https://github.com/akira/exq for background processing but I didn't menage to use it in uploader.

Could anybody tell me how it should be made in a proper way or give me some dirty hack advice to make it work. Thanks.

I tried Task as was advised in comments, but I am not sure how to use them in this case. When I try

{:ffmpeg, fn(input, output) -> Task.async(fn -> "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end) end, :mp4}

or

{:ffmpeg, Task.async(fn -> fn(input, output) ->  "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end end), :mp4}

I got "protocol String.Chars not implemented for %Task".

When I try

{:ffmpeg, Task.async(fn(input, output) ->  "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end), :mp4}

I got "#Function<20.83953603/2 in MyWebSite.Content.transform/2> with arity 2 called with no arguments". I tried to pass function as an argument with "&" but it fails as well.

My uploader:

defmodule MyWebSite.Content do
use Arc.Definition
use Arc.Ecto.Definition

@acl :public_read

@versions [:original,  :huge]

def transform(:huge, {file, scope}) do
  {:ffmpeg, Task.async(fn(input, output) ->  "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}" end), :mp4}
end

def s3_object_headers(version, {file, scope}) do
  [timeout: 3_000_00, content_type: Plug.MIME.path(file.file_name)]
end
end

Body:
From the Arc’s README (section Complex Transformations):

However, the transformation may be done completely outside of Arc. For fine-grained transformations, you should create an executable wrapper in your $PATH (eg. bash script) which takes these proper arguments, runs your transformation, and then moves the file into the correct location**.

That said, if you want the transformation to be run completely asynchronously, just create a bash script somewhere and call it like (assuming it’s name is myffmpeg):

def transform(:huge, {file, scope}) do
  {:myffmpeg,
     fn ->
       "-i #{input} -c:a copy -s 1920x1080 -f mp4 #{output}"
     end,
   :mp4}
end

The script should spawn ffmpeg passing the arguments and move the result to the folder Arc wants.


问:
How to iterate through bytes in python
I'm trying to iterate through bytes in python.
I have:

```<code>new[0]=b'\x00'
</code>```

but I want to iterate from '\x00' to '\xFF' in this new[0] element in a for loop. I mean:

```<code>new[0]=b'\x01'
new[0]=b'\x02'
</code>```

My target is not to view bytearray, but to change the first byte in this statement:

```<code>XX:32:38:B3:89:E9:D2:E6:88:1F:FF:A9:96:AF:26:CB:C6:06:2F:E0:08:21:7C:12:4D:31
</code>```

I want to change XX by iterating through bytes.

How can I do that?

答:
```<code>>>> arr = bytearray()
>>> arr.append(1)
>>> arr
bytearray(b'\x01')
>>> arr.append(2)
>>> arr
bytearray(b'\x01\x02')
>>> arr[0]
1
>>> arr[1]
2
>>> arr[1] = 3
>>> arr
bytearray(b'\x01\x03')

>>> arr = bytearray()
>>> _=list(map(arr.append, range(0,256)))
>>> print(arr)
bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff')
</code>```

Title: How to iterate through bytes in python

Body:
I'm trying to iterate through bytes in python.
I have:

new[0]=b'\x00'

but I want to iterate from '\x00' to '\xFF' in this new[0] element in a for loop. I mean:

new[0]=b'\x01'
new[0]=b'\x02'

My target is not to view bytearray, but to change the first byte in this statement:

XX:32:38:B3:89:E9:D2:E6:88:1F:FF:A9:96:AF:26:CB:C6:06:2F:E0:08:21:7C:12:4D:31

I want to change XX by iterating through bytes.

How can I do that?


问:
Apply character vector in double quotes to a variable as individual characters in double quotes separated by commas in R
I have the following in a data frame:

```<code>df <- "s1, s2, s3"
</code>```

I would like to assign it to a variable like this:

```<code>scafhold <- df
</code>```

But the output has to be:

```<code>scafhold

"s1", "s2", "s3"
</code>```

I have seen tips on using shQuote, but it only works for output and not assigning to a variable.

Any help would be appreciated.

EDIT!!

Just to sum up. I want this:

```<code>df <- "s1, s2, s3"
</code>```

To be applied like this:

```<code>df <- c("s1", "s2", "s3")
</code>```

答:
Check out the strsplit function:

```<code>strsplit(df, ",")[[1]]
</code>```

should do what you want

Body:
I have the following in a data frame:

df <- "s1, s2, s3"

I would like to assign it to a variable like this:

scafhold <- df

But the output has to be:

scafhold

"s1", "s2", "s3"

I have seen tips on using shQuote, but it only works for output and not assigning to a variable.

Any help would be appreciated.

EDIT!!

Just to sum up. I want this:

df <- "s1, s2, s3"

To be applied like this:

df <- c("s1", "s2", "s3")

Body:
Check out the strsplit function:

strsplit(df, ",")[[1]]

should do what you want


问:
Function declaration must have a name
I have strings of codes in my Main.Activity.kt of Android studio but I keep getting the error message "Function declaration must have a name: Unresolved reference"

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(2);
    displayPrice(2*5);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + number);
}
}
</code>```

答: You don't have displayPrice(2*5); function so replace displayPrice(2*5); to display(2*5); otherwise create function with name displayPrice(int number);

Title: Function declaration must have a name

Body:
I have strings of codes in my Main.Activity.kt of Android studio but I keep getting the error message "Function declaration must have a name: Unresolved reference"

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

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(2);
    displayPrice(2*5);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + number);
}
}


问:
VBA to test the speed of another program
I have 2 competing programs for a project I am working on. It is a change management tracking tool. It uses the application.undo function.

I'm trying to write a 3rd program to do changes so I can get data on which program runs faster, however, the application.undo does not work with the programs.

Any idea on how to bypass this or a work around?

```<code>Sub Counter()
     Dim i As Integer
     Worksheets("F&E List").Cells(6, 6).Value = 0
     For i = 1 To 5
         Worksheets("F&E List").Cells(6, 6).Value = i
         Application.Undo
     Next i
End Sub
</code>```

This gives me run time 1004 "Method Undo of object'_Application failed"

Which is the same error I get from the general program

答:
Ultimately I adjusted the code to simulate the undo in both programs to test the rest of the code without actually initiating the application.undo command. I figured that undo time would be the same in both programs so it wouldn't be a factor in the speed of the code (at lease one I could control) but this way I could still compare the code.

This sub updates the spreadsheets and records how much time each iteration took, then exports to another sheet so I can look at it in minitab

```<code> Sub Counter()
     Dim i As Integer
     Dim j As Integer
     Dim Time_Arr As Variant
     Worksheets("F&E List").Cells(4, 6).Value = 0
     ReDim Time_Arr(0) As Variant

     For i = 1 To 1000
         Worksheets("F&E List").Cells(4, 6).Value = i
         ReDim Preserve Time_Arr(i) As Variant
         Time_Arr(i) = Timer()
     Next i

     For i = 2 To UBound(Time_Arr)
         Worksheets("Time_Stamp").Cells(i, 1).Value = i
         Worksheets("Time_Stamp").Cells(i, 2).Value = Time_Arr(i) - Time_Arr(i - 1)
     Next i
 End Sub
</code>```

This is the main body of the code, I have not included the sub-procedures, i can if anyone would like to look at them. Note how i bypassed the application.undo and created a fake old value. My goal now is to look into times at each step and how i can further reduce the processing time to reduce lag as this is needed on daily use of the table.

```<code> Sub New_Process(Target As Range)

     Dim vStartTime As Variant
     Dim rng As Range
     Dim new_arr As Variant, old_arr As Variant, add_arr As Variant
     Dim add_val As String, r As Range
     Dim i As Integer, j As Integer

     On Error GoTo ErrHandler:

     Set rng = Intersect(Target, Range("FETable"))

     If rng Is Nothing Then
         Exit Sub
     End If

     Call Optimize_VBA

     new_arr = rng.Value
     add_val = rng.Address

     **'Application.Undo 'changed to a comment for testing purposes**

     **'old_arr = Range(add_val).Value**
     old_arr = -1

     Call Get_Add(add_arr, rng)

     Range(add_val).Value = new_arr

     If rng.Count = 1 Then

         If old_arr <> new_arr Then
             Call Check_Change(old_arr, new_arr, add_val)
         End If
     Else
    For i = LBound(add_arr, 1) To UBound(add_arr, 1)
        For j = LBound(add_arr, 2) To UBound(add_arr, 2)
            If old_arr(i, j) <> new_arr(i, j) Then
                'Debug.Print i, j, add_arr(i, j), old_arr(i, j), new_arr(i, j)
                Call Check_Change(old_arr(i, j), new_arr(i, j), add_arr(i, j))
                 End If
             Next j
         Next i
     End If

     Call Return_Func

 ErrHandler:

     If Err.Number = 13 Then
         Call Return_Func
         Exit Sub
     End If
 End Sub
</code>```

Body:
I have 2 competing programs for a project I am working on. It is a change management tracking tool. It uses the application.undo function.

I'm trying to write a 3rd program to do changes so I can get data on which program runs faster, however, the application.undo does not work with the programs.

Any idea on how to bypass this or a work around?

Sub Counter()
     Dim i As Integer
     Worksheets("F&E List").Cells(6, 6).Value = 0
     For i = 1 To 5
         Worksheets("F&E List").Cells(6, 6).Value = i
         Application.Undo
     Next i
End Sub

This gives me run time 1004 "Method Undo of object'_Application failed"

Which is the same error I get from the general program

Body:
Ultimately I adjusted the code to simulate the undo in both programs to test the rest of the code without actually initiating the application.undo command. I figured that undo time would be the same in both programs so it wouldn't be a factor in the speed of the code (at lease one I could control) but this way I could still compare the code.

This sub updates the spreadsheets and records how much time each iteration took, then exports to another sheet so I can look at it in minitab

 Sub Counter()
     Dim i As Integer
     Dim j As Integer
     Dim Time_Arr As Variant
     Worksheets("F&E List").Cells(4, 6).Value = 0
     ReDim Time_Arr(0) As Variant

     For i = 1 To 1000
         Worksheets("F&E List").Cells(4, 6).Value = i
         ReDim Preserve Time_Arr(i) As Variant
         Time_Arr(i) = Timer()
     Next i

     For i = 2 To UBound(Time_Arr)
         Worksheets("Time_Stamp").Cells(i, 1).Value = i
         Worksheets("Time_Stamp").Cells(i, 2).Value = Time_Arr(i) - Time_Arr(i - 1)
     Next i
 End Sub

This is the main body of the code, I have not included the sub-procedures, i can if anyone would like to look at them. Note how i bypassed the application.undo and created a fake old value. My goal now is to look into times at each step and how i can further reduce the processing time to reduce lag as this is needed on daily use of the table.

 Sub New_Process(Target As Range)

     Dim vStartTime As Variant
     Dim rng As Range
     Dim new_arr As Variant, old_arr As Variant, add_arr As Variant
     Dim add_val As String, r As Range
     Dim i As Integer, j As Integer

     On Error GoTo ErrHandler:

     Set rng = Intersect(Target, Range("FETable"))

     If rng Is Nothing Then
         Exit Sub
     End If

     Call Optimize_VBA

     new_arr = rng.Value
     add_val = rng.Address

     **'Application.Undo 'changed to a comment for testing purposes**

     **'old_arr = Range(add_val).Value**
     old_arr = -1

     Call Get_Add(add_arr, rng)

     Range(add_val).Value = new_arr

     If rng.Count = 1 Then

         If old_arr <> new_arr Then
             Call Check_Change(old_arr, new_arr, add_val)
         End If
     Else
    For i = LBound(add_arr, 1) To UBound(add_arr, 1)
        For j = LBound(add_arr, 2) To UBound(add_arr, 2)
            If old_arr(i, j) <> new_arr(i, j) Then
                'Debug.Print i, j, add_arr(i, j), old_arr(i, j), new_arr(i, j)
                Call Check_Change(old_arr(i, j), new_arr(i, j), add_arr(i, j))
                 End If
             Next j
         Next i
     End If

     Call Return_Func

 ErrHandler:

     If Err.Number = 13 Then
         Call Return_Func
         Exit Sub
     End If
 End Sub


问:
Obtain column names via Perl DBI
In SQL Server Management Studio 2008, I can run

```<code>sp_columns MY_TABLE
</code>```

to get all the column names (under COLUMN_NAME). However, how can I obtain the same information using Perl DBI?

In particular, I tried

```<code>my $result = $dbh->selectall_hashref("sp_columns MY_TABLE", 'COLUMN_NAME');
</code>```

hoping that the column names would be the keys of the returned hash.

In fact, even if that's successful, that's not what I want as I need to preserve the order of columns in that table. So I tried

```<code>my $sth = $dbh->prepare("sp_columns $table");
$sth->execute();
while (my @row = $sth->fetchrow_array) {
    # process @row;
}
</code>```

But neither works. I got the error message of

```<code>DBD::Sybase::db selectall_hashref failed: Server message number=102 severity=15 state=1 line=1 server=XXXX text=Incorrect syntax near '.'
</code>```

I also referenced this post. Apparently the following query does NOT work in my Management Studio:

```<code>select * from information_schema.columns where table_name = MY_TABLE
</code>```

with the error message of

```<code>Msg 208, Level 16, State 1, Line 2
Invalid object name 'information_schema.columns'.
</code>```

Please help? Thx!

答:
The returned column names are an attribute of a prepared statement, so you can use:

```<code>my $dbh = DBI->connect('dbi:DBMS:...','','');
my $sth = $dbh->prepare("SELECT * FROM SomeTable");
</code>```

and now $sth->{NAME} (an array reference) contains the names of the columns (as aliased, etc).

Title: Obtain column names via Perl DBI

Body:
In SQL Server Management Studio 2008, I can run

sp_columns MY_TABLE

to get all the column names (under COLUMN_NAME). However, how can I obtain the same information using Perl DBI?

In particular, I tried

my $result = $dbh->selectall_hashref("sp_columns MY_TABLE", 'COLUMN_NAME');

hoping that the column names would be the keys of the returned hash.

In fact, even if that's successful, that's not what I want as I need to preserve the order of columns in that table. So I tried

my $sth = $dbh->prepare("sp_columns $table");
$sth->execute();
while (my @row = $sth->fetchrow_array) {
    # process @row;
}

But neither works. I got the error message of

DBD::Sybase::db selectall_hashref failed: Server message number=102 severity=15 state=1 line=1 server=XXXX text=Incorrect syntax near '.'

I also referenced this post. Apparently the following query does NOT work in my Management Studio:

select * from information_schema.columns where table_name = MY_TABLE

with the error message of

Msg 208, Level 16, State 1, Line 2
Invalid object name 'information_schema.columns'.

Please help? Thx!

Body:
The returned column names are an attribute of a prepared statement, so you can use:

my $dbh = DBI->connect('dbi:DBMS:...','','');
my $sth = $dbh->prepare("SELECT * FROM SomeTable");

and now $sth->{NAME} (an array reference) contains the names of the columns (as aliased, etc).


问:
Selenium ruby check whether webelement is clickable or not?
```<code>def click(tag,prop)
  # wait_for_ajax
  element = wait.until{
  tmp_element = driver.find_element(tag, prop)
  tmp_element if tmp_element.displayed?
  }
 element.click
end
</code>```

This is function to check visibility of element . But I want check click ability of web element.

答:
Try this</p>

```<code>def click(tag,prop)
  # wait_for_ajax
  element = wait.until{
    tmp_element = driver.find_element(tag, prop)
    tmp_element if tmp_element.enabled? && tmp_element.displayed?
  }
  element.click
end
</code>```

Body:
def click(tag,prop)
  # wait_for_ajax
  element = wait.until{
  tmp_element = driver.find_element(tag, prop)
  tmp_element if tmp_element.displayed?
  }
 element.click
end

This is function to check visibility of element . But I want check click ability of web element.

Body:
Try this

def click(tag,prop)
  # wait_for_ajax
  element = wait.until{
    tmp_element = driver.find_element(tag, prop)
    tmp_element if tmp_element.enabled? && tmp_element.displayed?
  }
  element.click
end


问:
java.io.IOException: Incomplete parts with embedded Jetty Server
I`m programming a little file server which gets documents via HTTP-POST requests from another software.

The requests are always "multipart/form-data" types, so I`d like to split it via .getParts();

Unfortunately I always get a "java.io.IOException: Incomplete parts" or it does not find the part.

Is there something wrong with my code or is there a problem with the request?

I`m using a embedded Jetty server with Eclipse

```<code>    public void create_document() {
    String lv_path = gr_request.getParameter("contRep") + File.separator + gr_request.getParameter("docId");
    Part lr_part = null;
    try {
        System.out.println(gr_request.getContentType());
        //for testing
        Part lr_test = gr_request.getPart("data");
        System.out.println("1");
        System.out.println(lr_test);

        //the actual part
        Collection<Part> lr_parts = gr_request.getParts();
        for (Iterator<Part> i = lr_parts.iterator(); i.hasNext();) {
            lr_part = ((Iterator<Part>) lr_parts).next();

            //again for testing
            System.out.println("content Type" + lr_part.getContentType());
            System.out.println("name" + lr_part.getName());
            System.out.println("content Type" + lr_part.getContentType());
            String test = lv_path + ".jpg";
            lr_part.write(test);
</code>```

the log is

```<code>2017-11-28 11:07:47.941:INFO:oejs.Server:main: jetty-9.0.4.v20130625
2017-11-28 11:07:48.222:INFO:oejs.ServerConnector:main: StartedServerConnector@7165cbeb{HTTP/1.1}{0.0.0.0:1090}
Erkannte Aktion: CREATE_DOCUMENT
2017-11-2811:07:54.469:WARN:oejs.Request:qtp424058530-15:java.io.IOException:Incomplete parts
multipart/form-data; boundary=KoZIhvcNAQcB
1
null
</code>```

The MultiPartConfig was done by

```<code>MultipartConfigElement multipartConfigElement = newMultipartConfigElement((String)null);
ir_request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, multipartConfigElement);
</code>```

Beginning of the body of a transmitted PDF file:

```<code>--KoZIhvcNAQcB
Content-Disposition: form-data; filename="data"
X-compId: data
Content-Type: application/pdf
Content-Length: 182370

%PDF-1.7
%µµµµ
1 0 obj
...and so on...
182188
%%EOF
--KoZIhvcNAQcB--
</code>```

答:
It seems that there is a problem with the request.
I changed the "filename" tag to "name" while receiving the request.
Now it's running</p>

Body:
I`m programming a little file server which gets documents via HTTP-POST requests from another software.

The requests are always "multipart/form-data" types, so I`d like to split it via .getParts();

Unfortunately I always get a "java.io.IOException: Incomplete parts" or it does not find the part.

Is there something wrong with my code or is there a problem with the request?

I`m using a embedded Jetty server with Eclipse

    public void create_document() {
    String lv_path = gr_request.getParameter("contRep") + File.separator + gr_request.getParameter("docId");
    Part lr_part = null;
    try {
        System.out.println(gr_request.getContentType());
        //for testing
        Part lr_test = gr_request.getPart("data");
        System.out.println("1");
        System.out.println(lr_test);

        //the actual part
        Collection<Part> lr_parts = gr_request.getParts();
        for (Iterator<Part> i = lr_parts.iterator(); i.hasNext();) {
            lr_part = ((Iterator<Part>) lr_parts).next();

            //again for testing
            System.out.println("content Type" + lr_part.getContentType());
            System.out.println("name" + lr_part.getName());
            System.out.println("content Type" + lr_part.getContentType());
            String test = lv_path + ".jpg";
            lr_part.write(test);

the log is

2017-11-28 11:07:47.941:INFO:oejs.Server:main: jetty-9.0.4.v20130625
2017-11-28 11:07:48.222:INFO:oejs.ServerConnector:main: StartedServerConnector@7165cbeb{HTTP/1.1}{0.0.0.0:1090}
Erkannte Aktion: CREATE_DOCUMENT
2017-11-2811:07:54.469:WARN:oejs.Request:qtp424058530-15:java.io.IOException:Incomplete parts
multipart/form-data; boundary=KoZIhvcNAQcB
1
null

The MultiPartConfig was done by

MultipartConfigElement multipartConfigElement = newMultipartConfigElement((String)null);
ir_request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, multipartConfigElement);

Beginning of the body of a transmitted PDF file:

--KoZIhvcNAQcB
Content-Disposition: form-data; filename="data"
X-compId: data
Content-Type: application/pdf
Content-Length: 182370

%PDF-1.7
%µµµµ
1 0 obj
...and so on...
182188
%%EOF
--KoZIhvcNAQcB--


问:
Accessing Properties of the code-behind from aspx page in web application project
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<div>
<%= x2 %>
<%# x2 %>
</div>
</form>
</body>
</html>
</code>```

Codebehind file :

```<code>using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}
</code>```

It is working fine when I use the same technique in my website project
Kindly help
Thanks

答:
Check if there are any other errors in your code behind WebForm1.aspx.cs.
like missing reference or any other compile error.

Body:
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

<%= x2 %>
<%# x2 %>

</form>

Codebehind file :

using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}

It is working fine when I use the same technique in my website project
Kindly help
Thanks


问:
Nokia here maps-api map overlay
So I'm working on a scenario were I need to have a floorplan as an overlay on top of a Nokia map, and I have succeeded in getting the image on top of the map, the problem is that I don't seem to be able to move it as I need to fit perfectly on a specific building. What am I doing wrong/missing? Is there any why to make it even more precise?</p>

```<code>$(function(){
    var behavior = new H.mapevents.Behavior(mapEvents);
    $('#knapp').click(function(){
    overlayFloorplan(map);
});

function overlayFloorplan(map) {

  var tileProvider = new H.map.provider.ImageTileProvider({

    min: 14,
    max: 17,

    getURL: function (column, row, zoom) {
      if (((zoom == 14) && (row < 4742 || column < 8880 || row > 4746 || column > 8884)) ||
        ((zoom == 15) &&  (row < 9484 || column < 17760 || row > 9492 || column > 17768)) ||
        ((zoom == 16) && (row < 18968 || column < 35520 || row > 18984 || column > 35536)) ||
        ((zoom  == 17) && (row < 37936 || column < 71040 || row > 37968 || column > 71072))) {
        console.log('BLANK');
        return //picture location
      } else {
        return //picture location
      }
    }
  });

  var overlayLayer = new H.map.layer.TileLayer(tileProvider, {
    opacity: 0.5,
  });

  map.addLayer(overlayLayer);
  }
});
</code>```

答:
Providing an image for the floor plan of a building on click can be handled by creating a marker at the building specific location that is invisible and handling the click event.  When click the event occurs the image can be displayed as a infobubble.  The location of the marker will be specific to the latitude and longitude of the location and the marker can be adjusted if necessary using the anchor offset.

Using SVG markers with images

Title: Nokia here maps-api map overlay

Body:
So I'm working on a scenario were I need to have a floorplan as an overlay on top of a Nokia map, and I have succeeded in getting the image on top of the map, the problem is that I don't seem to be able to move it as I need to fit perfectly on a specific building. What am I doing wrong/missing? Is there any why to make it even more precise?

$(function(){
    var behavior = new H.mapevents.Behavior(mapEvents);
    $('#knapp').click(function(){
    overlayFloorplan(map);
});

function overlayFloorplan(map) {

  var tileProvider = new H.map.provider.ImageTileProvider({

    min: 14,
    max: 17,

    getURL: function (column, row, zoom) {
      if (((zoom == 14) && (row < 4742 || column < 8880 || row > 4746 || column > 8884)) ||
        ((zoom == 15) &&  (row < 9484 || column < 17760 || row > 9492 || column > 17768)) ||
        ((zoom == 16) && (row < 18968 || column < 35520 || row > 18984 || column > 35536)) ||
        ((zoom  == 17) && (row < 37936 || column < 71040 || row > 37968 || column > 71072))) {
        console.log('BLANK');
        return //picture location
      } else {
        return //picture location
      }
    }
  });

  var overlayLayer = new H.map.layer.TileLayer(tileProvider, {
    opacity: 0.5,
  });

  map.addLayer(overlayLayer);
  }
});


问:
org.openqa.selenium.SessionNotCreatedException
```<code>public class Admin
{

    public static void main(String args[]) throws MalformedURLException
    {
        DesiredCapabilities cap=new DesiredCapabilities();
        cap.setCapability("automationName", "android");
        cap.setCapability("platformName", "Appium");
        cap.setCapability("Version", "7.1.1");
        cap.setCapability("devicename", "HT4AXJT00193");
        cap.setCapability("appActivity", "com.bcqms.cgs.MainActivity");
        cap.setCapability("appPackage", "com.bcqms.cgs");

        AppiumDriver<WebElement> driver=new AndroidDriver<WebElement>(newURL("http://0.0.0.0:4723/wd/hub"),cap);
        driver.findElementById("inputEmail3").sendKeys("admin");
        driver.findElementById("inputPassword3").sendKeys("jsmith");
    }
}
</code>```

While I am writing the above code for authentication of the app I am getting the following error.

Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: A new session could not be created. Details: The desiredCapabilities object was not valid for the following reason(s): deviceName can't be blank, automationName android not part of Appium,Selendroid,UiAutomator2,XCUITest,YouiEngine, (WARNING: The server did not provide any stacktrace information)

答:
Just update device capability name. you have written devicename instead of deviceName.

I had the same issue, resolved with above changes.

Hope it will work for you.

Body:
public class Admin
{

    public static void main(String args[]) throws MalformedURLException
    {
        DesiredCapabilities cap=new DesiredCapabilities();
        cap.setCapability("automationName", "android");
        cap.setCapability("platformName", "Appium");
        cap.setCapability("Version", "7.1.1");
        cap.setCapability("devicename", "HT4AXJT00193");
        cap.setCapability("appActivity", "com.bcqms.cgs.MainActivity");
        cap.setCapability("appPackage", "com.bcqms.cgs");

        AppiumDriver<WebElement> driver=new AndroidDriver<WebElement>(newURL("http://0.0.0.0:4723/wd/hub"),cap);
        driver.findElementById("inputEmail3").sendKeys("admin");
        driver.findElementById("inputPassword3").sendKeys("jsmith");
    }
}

While I am writing the above code for authentication of the app I am getting the following error.

Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: A new session could not be created. Details: The desiredCapabilities object was not valid for the following reason(s): deviceName can't be blank, automationName android not part of Appium,Selendroid,UiAutomator2,XCUITest,YouiEngine, (WARNING: The server did not provide any stacktrace information)


问:
Cannot get property 'compileSdkVersion' on extra properties extension as it does not exist Open File
I imported a project downloaded from GitHub into my Android Studio project as module.
The "Import module..." wizard worked fine, but when the Adroid Studio tried to rebuild the project, it returned me this error:

```<code>Cannot get property 'compileSdkVersion' on extra properties extension as it does not exist Open File
</code>```

The error is related to this line in the "build.gradle" file of the imported module:

```<code>compileSdkVersion rootProject.compileSdkVersion
</code>```

I tried to add "ext" section in the project "build.gradle" like this:

```<code>ext {
    compileSdkVersion 26
}
</code>```

But in this way I receive a new error:

```<code>Gradle DSL method not found: 'compileSdkVersion()' Possible causes: ...
</code>```

答:
In build.gradle you need to write compilesdkversion under android tag as in this example:

android {
..
  compileSdkVersion 26 // 26 is an example
..}

By the way. You can build that module as library then import it into your project as .aar file.

Body:
I imported a project downloaded from GitHub into my Android Studio project as module.
The "Import module..." wizard worked fine, but when the Adroid Studio tried to rebuild the project, it returned me this error:

Cannot get property 'compileSdkVersion' on extra properties extension as it does not exist Open File

The error is related to this line in the "build.gradle" file of the imported module:

compileSdkVersion rootProject.compileSdkVersion

I tried to add "ext" section in the project "build.gradle" like this:

ext {
    compileSdkVersion 26
}

But in this way I receive a new error:

Gradle DSL method not found: 'compileSdkVersion()' Possible causes: ...


问:
Laravel (Eloquent) equivalent of Mongoose's populate() method
I understand that this question may have more than one DBMS-related answer, but maybe not, so here it goes.

So, I need my app to asynchronously grab some data from the backend, say something like a User and his Posts. I am using Vue2 with Axios on the frontend, so that it would be nice to write something like:

```<code>mounted: function() {
    axios.get('/users')
        .then((response) => {
            this.users = response.data;
        })
        .catch(function (err) {
            // Handle this
        });
}
</code>```

The outcome I'd like to have is the users object in my VueVM's data to contain also an array of posts for each User. Currently I build a custom associative array in my backend-side controller as follows:

```<code>$posts = Post::where('user_id', $id)->get();
return json_encode(['user' => $user, 'posts' => $posts]);
</code>```

Or, when feasible, I use the has_many method, which is also pretty handy, but I find this solution pretty ugly and lacking reusability.

With Mongoose and MongoDB I would use the populate() method, but I cannot find (that is I actually don't know how to search for it) an equivalent to this with Eloquent.

Any suggestion?

答:
If you have defined a posts() relationship in your User model, when retrieving the users, you can eager load the related data:

```<code>$users = User::with('posts')->get();
</code>```

or a specific User:

```<code>$user = User::with('posts')->find($id);
</code>```

Then $user->posts would contain a collection of the related Post models.

I suggest you read through https://laravel.com/docs/5.5/eloquent-relationships

Body:
I understand that this question may have more than one DBMS-related answer, but maybe not, so here it goes.

So, I need my app to asynchronously grab some data from the backend, say something like a User and his Posts. I am using Vue2 with Axios on the frontend, so that it would be nice to write something like:

mounted: function() {
    axios.get('/users')
        .then((response) => {
            this.users = response.data;
        })
        .catch(function (err) {
            // Handle this
        });
}

The outcome I'd like to have is the users object in my VueVM's data to contain also an array of posts for each User. Currently I build a custom associative array in my backend-side controller as follows:

$posts = Post::where('user_id', $id)->get();
return json_encode(['user' => $user, 'posts' => $posts]);

Or, when feasible, I use the has_many method, which is also pretty handy, but I find this solution pretty ugly and lacking reusability.

With Mongoose and MongoDB I would use the populate() method, but I cannot find (that is I actually don't know how to search for it) an equivalent to this with Eloquent.

Any suggestion?

Body:
If you have defined a posts() relationship in your User model, when retrieving the users, you can eager load the related data:

$users = User::with('posts')->get();

or a specific User:

$user = User::with('posts')->find($id);

Then $user->posts would contain a collection of the related Post models.

I suggest you read through https://laravel.com/docs/5.5/eloquent-relationships


问:
flash[:notice] or flash.notice?
FlashHash has convenience methods for :notice and :alert. My question then is, which is most appropriate? flash[:notice] or flash.notice? Is it simply a mater of taste or this there a compelling reason to chose one method over the other?</p>

答:
Is it simply a mater of taste or this there a compelling reason to chose one method over the other?

Pretty much. flash[:notice] is how Rails handles it internally, so if there's a "right" way to do it, that's probably it. Personally, I prefer flash.notice, but that's just my own preference.

Title: flash[:notice] or flash.notice?


问:
daterangepicker two different inputs
I have two different daterangepicker in the same form, because I need to have it in two inputs nor only in one.. So I initialize this with a class selector:
$('.daterange').daterangepicker({});

everithing works perfect, but I want to do change two both. If I select a range in the first one, when I open the second one I want to have the same range selected in the calendars. So I'm trying to do it in ON SHOW event

```<code>$('.daterange').daterangepicker()
.on('apply.daterangepicker' ,function(ev, picker) {
$('.scheduledStartGmt').val(picker.startDate.format(picker.format)).change();
$('.scheduledEndGmt').val(picker.endDate.format(picker.format)).change();
})
.on('show.daterangepicker' ,function(ev, picker){

$('.daterange').data('daterangepicker').setStartDate($('.scheduledStartGmt').val());
$('.daterange').data('daterangepicker').setEndDate($('.scheduledEndGmt').val());

});
</code>```

Only changes the first one. How can I do it?

答:
i was facing the same problem but found the Solution, this may help you:

Have a look at my code:

```<code>    if($('#search_checkin, #search_checkout').length){
    // check if element is available to bind ITS ONLY ON HOMEPAGE
    var currentDate = moment().format("DD-MM-YYYY");

    $('#search_checkin, #search_checkout').daterangepicker({
        locale: {
              format: 'DD-MM-YYYY'
        },
        "alwaysShowCalendars": true,
        "minDate": currentDate,
        "maxDate": moment().add('months', 1),
        autoApply: true,
        autoUpdateInput: false
    }, function(start, end, label) {
      // console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
      // Lets update the fields manually this event fires on selection of range
      var selectedStartDate = start.format('DD-MM-YYYY'); // selected start
      var selectedEndDate = end.format('DD-MM-YYYY'); // selected end

      $checkinInput = $('#search_checkin');
      $checkoutInput = $('#search_checkout');

      // Updating Fields with selected dates
      $checkinInput.val(selectedStartDate);
      $checkoutInput.val(selectedEndDate);

      // Setting the Selection of dates on calender on CHECKOUT FIELD (To get this it must be binded by Ids not Calss)
      var checkOutPicker = $checkoutInput.data('daterangepicker');
      checkOutPicker.setStartDate(selectedStartDate);
      checkOutPicker.setEndDate(selectedEndDate);

      // Setting the Selection of dates on calender on CHECKIN FIELD (To get this it must be binded by Ids not Calss)
      var checkInPicker = $checkinInput.data('daterangepicker');
      checkInPicker.setStartDate(selectedStartDate);
      checkInPicker.setEndDate(selectedEndDate);

    });

} // End Daterange Picker
</code>```

please let me know if you want me to explain.

Title: daterangepicker two different inputs

Body:
I have two different daterangepicker in the same form, because I need to have it in two inputs nor only in one.. So I initialize this with a class selector:
$('.daterange').daterangepicker({});

everithing works perfect, but I want to do change two both. If I select a range in the first one, when I open the second one I want to have the same range selected in the calendars. So I'm trying to do it in ON SHOW event

$('.daterange').daterangepicker()
.on('apply.daterangepicker' ,function(ev, picker) {
$('.scheduledStartGmt').val(picker.startDate.format(picker.format)).change();
$('.scheduledEndGmt').val(picker.endDate.format(picker.format)).change();
})
.on('show.daterangepicker' ,function(ev, picker){

$('.daterange').data('daterangepicker').setStartDate($('.scheduledStartGmt').val());
$('.daterange').data('daterangepicker').setEndDate($('.scheduledEndGmt').val());

});

Only changes the first one. How can I do it?

Body:
i was facing the same problem but found the Solution, this may help you:

Have a look at my code:

    if($('#search_checkin, #search_checkout').length){
    // check if element is available to bind ITS ONLY ON HOMEPAGE
    var currentDate = moment().format("DD-MM-YYYY");

    $('#search_checkin, #search_checkout').daterangepicker({
        locale: {
              format: 'DD-MM-YYYY'
        },
        "alwaysShowCalendars": true,
        "minDate": currentDate,
        "maxDate": moment().add('months', 1),
        autoApply: true,
        autoUpdateInput: false
    }, function(start, end, label) {
      // console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
      // Lets update the fields manually this event fires on selection of range
      var selectedStartDate = start.format('DD-MM-YYYY'); // selected start
      var selectedEndDate = end.format('DD-MM-YYYY'); // selected end

      $checkinInput = $('#search_checkin');
      $checkoutInput = $('#search_checkout');

      // Updating Fields with selected dates
      $checkinInput.val(selectedStartDate);
      $checkoutInput.val(selectedEndDate);

      // Setting the Selection of dates on calender on CHECKOUT FIELD (To get this it must be binded by Ids not Calss)
      var checkOutPicker = $checkoutInput.data('daterangepicker');
      checkOutPicker.setStartDate(selectedStartDate);
      checkOutPicker.setEndDate(selectedEndDate);

      // Setting the Selection of dates on calender on CHECKIN FIELD (To get this it must be binded by Ids not Calss)
      var checkInPicker = $checkinInput.data('daterangepicker');
      checkInPicker.setStartDate(selectedStartDate);
      checkInPicker.setEndDate(selectedEndDate);

    });

} // End Daterange Picker

please let me know if you want me to explain.


问:
nginx redirect to trailing slashes and substitude to index.php (if files and folders don't exists)

I want to redirect all urls without trailin slashes with 301 redirect to same urls with trailing slashes. Also I want to substitude all urls to index.php, if its not a folder or file.

I tried to make this with following code:

```<code>location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~* .*[^/]$ {
  try_files $uri $uri/ permanent;
}

location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
  fastcgi_read_timeout 300;
}
</code>```

First location working perfect alone, but this locations don't work together. It return normally files and folders, but when request urls without slash nginx returns 500 error, and just return file index.php to download, when url with trailing slash.

Also I tried to make it with code:

```<code>location / {
    try_files $uri $uri/ @addslash /index.php$is_args$args;
}
location @addslash {
    rewrite ^(.+[^/])$ $1/ permanent;
}
location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
  fastcgi_read_timeout 300;
}
</code>```

But it works without any redirections from urls without trailing slashes.

How can I make working both redirects to trailing slash and substitude to index.php?

答:
I found working solution. It uses bad practice (if is evil), but it's only working code. So if any will show better workig decision, I will be grateful.</p>

```<code>set $my_var 0;
if (-f $request_filename) {
  set $my_var 1;
}
if (-d $request_filename) {
  set $my_var 1;
}
if (-d $request_filename) {
  set $my_var 1;
}
if ($request_uri ~ "^.*/market/cart$") {
  set $my_var 1;
}
if ($request_uri ~ "^.*/market/order/accept$") {
  set $my_var 1;
}
if ($request_uri ~ "^.*/market/order/status$") {
  set $my_var 1;
}
if ($request_uri ~* "(.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$") {
  set $my_var 1;
}

if ($my_var = 0) {
  rewrite ^(.*[^/])$ $1/ permanent;
}

if ($request_uri ~* "^(.*/)index\.php$") {
  return 301 $1;
}

location ~* (.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$ {
  try_files $uri $1.$2;
}

location / {
  try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-newstom-fpm.sock;
  fastcgi_read_timeout 300;
}
</code>```

Body:
I want to redirect all urls without trailin slashes with 301 redirect to same urls with trailing slashes. Also I want to substitude all urls to index.php, if its not a folder or file.

I tried to make this with following code:

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~* .*[^/]$ {
  try_files $uri $uri/ permanent;
}

location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
  fastcgi_read_timeout 300;
}

First location working perfect alone, but this locations don't work together. It return normally files and folders, but when request urls without slash nginx returns 500 error, and just return file index.php to download, when url with trailing slash.

Also I tried to make it with code:

location / {
    try_files $uri $uri/ @addslash /index.php$is_args$args;
}
location @addslash {
    rewrite ^(.+[^/])$ $1/ permanent;
}
location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
  fastcgi_read_timeout 300;
}

But it works without any redirections from urls without trailing slashes.

How can I make working both redirects to trailing slash and substitude to index.php?

Body:
I found working solution. It uses bad practice (if is evil), but it's only working code. So if any will show better workig decision, I will be grateful.

set $my_var 0;
if (-f $request_filename) {
  set $my_var 1;
}
if (-d $request_filename) {
  set $my_var 1;
}
if (-d $request_filename) {
  set $my_var 1;
}
if ($request_uri ~ "^.*/market/cart$") {
  set $my_var 1;
}
if ($request_uri ~ "^.*/market/order/accept$") {
  set $my_var 1;
}
if ($request_uri ~ "^.*/market/order/status$") {
  set $my_var 1;
}
if ($request_uri ~* "(.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$") {
  set $my_var 1;
}

if ($my_var = 0) {
  rewrite ^(.*[^/])$ $1/ permanent;
}

if ($request_uri ~* "^(.*/)index\.php$") {
  return 301 $1;
}

location ~* (.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$ {
  try_files $uri $1.$2;
}

location / {
  try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-newstom-fpm.sock;
  fastcgi_read_timeout 300;
}


问:
Oracle Apex - Dynamic Actions
In Oracle Apex- Dynamic Actions:

My Queries about in Dynamic action to enable/disable two different items as below.
I am working with apex 5 and need to do enable/disable with these item

Having two items in my apex page

p1_text_field

p2_select_list

I want to disable the p2 when I am entering value in p1 which is enabled to type
vise-versa
I want to disable the p1 when I am entering value in p2 which is enabled to select the values.

答:
For item p1_text_field:

Create a dynamic action with properties: Event - Key down or Change, Selection Type - Item, Item(s) - p1_text_field

Add a Client Side Condition: Type - Item is null, Item - p1_text_field. This condition will allow you to unlock disabled field in a case you clear p1_text_field

Add True action with type Enable, Selection Type - Item, Item(s) - p2_select_list

Add False action with type Disable, Selection Type - Item, Item(s) - p2_select_list

After that, when a user input something into p1_text_field, p2_select_list will be disabled. If the user clears value of p1_text_field, p2_select_list will be enabled. If you don't need this, do not create Client Side Condition.

Repeat same steps for p2_select_list.

UPD - Important notice

I forgot about one "feature" of APEX. When you create a new true or false action, check field Fire on initialization. It have to be No, otherwise action will be executed on page load. The main problem is that APEX sometimes creates new actions with this field set to Yes.

Title: Oracle Apex - Dynamic Actions


问:
Restart app when coming out of background
I've seen many news apps do this, where when you click on the app (on the iphone desktop) that has been in background mode, it starts again by showing a loading screen, etc.  It basically looks like it starts again like it was never in background mode (I think what is called "refreshing the user interface).  Does anybody know how you do this?  I assume this is call from the app's delegate applicationWillEnterForeground or applicationDidBecomeActive method.</p>

答:
The application probably never went into the background.  Try adding this to the Info.plist file.

UIApplicationExitsOnSuspend=YES

As a boolean value.