问:
How can I fix impaired functionality caused by disallowed useragent?
I'm building a web browser an recently I came across an error while trying to login using my Google account on a website.

This is strange because I checked the user agent of my app and Safari's and they are both identical.

Any suggestions?

UPDATE

The WKWebView is nested 3 levels deep inside a tree of custom UIViews.

Here's the initialization code:

```<code>_webView = [[WKWebView alloc] init];
_webView.allowsBackForwardNavigationGestures = NO;
_webView.allowsLinkPreview = NO;
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
_webView.frame = CGRectMake(0.0, 0.0, self.contentView.frame.size.width, self.contentView.frame.size.height);
[self.contentView addSubview:_webView];
</code>```

答:
From Google Modernizing OAuth interactions in Native Apps for Better Usability and Security article:

On April 20, 2017, we will start blocking OAuth requests using web-views for all OAuth clients on platforms where viable alternatives exist.

So, Google now allows sign-in with Google Account only in normal browsers, it restricts it in web-views due to security reasons and recommends Google SDKs for iOS and Android for this purpose.

But if you still want to use WKWebView you may do a little trick, suggested in this answer, setting customUserAgent so it can pass validation:

```<code>// Check for selector availability, as it is available only on iOS 9+
if ([_webView respondsToSelector:@selector(setCustomUserAgent:)]) {
    _webView.customUserAgent = @"MyCustomUserAgent";
}
</code>```

Body:
I'm building a web browser an recently I came across an error while trying to login using my Google account on a website.

This is strange because I checked the user agent of my app and Safari's and they are both identical.

Any suggestions?

UPDATE

The WKWebView is nested 3 levels deep inside a tree of custom UIViews.

Here's the initialization code:

_webView = [[WKWebView alloc] init];
_webView.allowsBackForwardNavigationGestures = NO;
_webView.allowsLinkPreview = NO;
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
_webView.frame = CGRectMake(0.0, 0.0, self.contentView.frame.size.width, self.contentView.frame.size.height);
[self.contentView addSubview:_webView];

Body:
From Google Modernizing OAuth interactions in Native Apps for Better Usability and Security article:

On April 20, 2017, we will start blocking OAuth requests using web-views for all OAuth clients on platforms where viable alternatives exist.

So, Google now allows sign-in with Google Account only in normal browsers, it restricts it in web-views due to security reasons and recommends Google SDKs for iOS and Android for this purpose.

But if you still want to use WKWebView you may do a little trick, suggested in this answer, setting customUserAgent so it can pass validation:

// Check for selector availability, as it is available only on iOS 9+
if ([_webView respondsToSelector:@selector(setCustomUserAgent:)]) {
    _webView.customUserAgent = @"MyCustomUserAgent";
}


来源: stackexchange

问:
How to create a sub array from another array in Java?
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

```<code>methodName(object array, int start, int end)
</code>```

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

```<code>import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}
</code>```

答: Arrays.copyOfRange(..) was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)

ContentLicense: CC BY-SA 3.0

Body:
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int end)

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}

ContentLicense: CC BY-SA 2.5


问:
Levenstein distance substring
Is there a good way to use levenstein distance to match one particular string to any region within a second longer string?

Example:

```<code>str1='aaaaa'
str2='bbbbbbaabaabbbb'

if str1 in str2 with a distance < 2:
    return True
</code>```

So in the above example part of string 2 is aabaa and distance(str1,str2) < 2 so the statement should return True.

The only way I can think to do this is take 5 chars from str2 at a time, compare that with str1 and then repeat this moving through str2. Unfortunately this seems really inefficient and I need to process a large amount of data this way.

答:
The trick is usually to play with the insert (for shorter) or delete (for longer) costs. You may also want to consider using Damerau-Levenshtein instead.
https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance</p>

Title: Levenstein distance substring

Body:
Is there a good way to use levenstein distance to match one particular string to any region within a second longer string?

Example:

str1='aaaaa'
str2='bbbbbbaabaabbbb'

if str1 in str2 with a distance < 2:
    return True

So in the above example part of string 2 is aabaa and distance(str1,str2) < 2 so the statement should return True.

The only way I can think to do this is take 5 chars from str2 at a time, compare that with str1 and then repeat this moving through str2. Unfortunately this seems really inefficient and I need to process a large amount of data this way.


问:
angular 1.5.x ngRepeat memory leak
I created a list module that can display multiple pages of items. I am using a nested ng-repeat to iterate through pages and the items on each page. However, I've noticed DOM Nodes keep increasing in Chrome Timeline tool like this when I keep refreshing the list and load new pages and items, memory usage is also increasing(I made sure I clicked on garbage collection button during recording, so there must be something leaking):

I am using angular 1.5.5 and requireJS, I've heard ng-repeat used to have a memory leak but that already got fixed in 1.4.x. The code is simple and I didn't register any DOM handlers in the code, I have been poking around on this for a week and still couldn't figure out the reason, I am very desperate now and help is super appreciated.

My code file structure is like this:

```<code>list-container
     |___module.js
     |
     |___controllers
     |       |____list-container.js
     |
     |___directives
     |       |____list-container.js
     |
     |___views
           |____directive-list-container.html
</code>```

Below is the code:

module.js

```<code>define([
  'angular',
], function (angular) {
  'use strict';

  return angular.module('ui.listContainer', []);
});
</code>```

list-container.js(directive)

```<code>define([
  'angular',
  '../module',
  '../controllers/list-container'
], function (angular, module) {
  'use strict';

  return angular
    .module('ui.listContainer')
    .directive('listContainer', function () {
    return {
      replace: true,
      restrict: 'E',
      templateUrl: '/modules/list-container/views/directive-list-container.html',
      bindToController: {},
      scope: {},
      controllerAs: 'listVm',
      controller: 'listContainerController'
    };
  });
});
</code>```

list-container.js(controller)

```<code>define([
   'angular',
   '../module'
 ], function (angular, module) {
   'use strict';
   angular.module('ui.listContainer').controller('listContainerController', ['$scope', function ($scope) {

     var listVm = this;

     $scope.refreshPage = function () {
       if (listVm.list) {
         listVm.list = null; //Clear the data
       }
       listVm.list = {};
       listVm.list.pages = feedData(); //Load mock data
     };

     function feedData() {
       var pages = [];
       for(var i = 0; i < 10; i++) {
         pages.push(new PageMock());
       }
       return pages;
     }

     function PageMock() {
       this.items = [];
       for (var i = 0; i < 50; i++) {
         this.items.push(new ItemMock());
       }
     }

     function ItemMock() {
       this.id = Math.floor(Math.random() * 10000000);
     }

   }]);
 });
</code>```

directive-list-container.html(view)

```<code><div class="list-container row">
    <div id="list-container-pages">
        <div class="list-container-pages row">
            <div ng-click="refreshPage()">Refresh Page</div>
            <div class="list-container-page row" ng-repeat="page in listVm.list.pages track by $index">
                <div class="row" ng-repeat="listItem in page.items track by listItem.id">
                    <span class="col-md-12">{{listItem.id}}</span>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

I created a plunker to mimic the code I have above, however it's not leaking at all in the plunker example, which is super weird.
Plunker Example

答:
Seems like a bug in angular, see the other post.
AngularJS: Memory Leak with ng-repeat using custom objects (w/simple PLUNKR)
</p>

Title: angular 1.5.x ngRepeat memory leak

Body:
I created a list module that can display multiple pages of items. I am using a nested ng-repeat to iterate through pages and the items on each page. However, I've noticed DOM Nodes keep increasing in Chrome Timeline tool like this when I keep refreshing the list and load new pages and items, memory usage is also increasing(I made sure I clicked on garbage collection button during recording, so there must be something leaking):

I am using angular 1.5.5 and requireJS, I've heard ng-repeat used to have a memory leak but that already got fixed in 1.4.x. The code is simple and I didn't register any DOM handlers in the code, I have been poking around on this for a week and still couldn't figure out the reason, I am very desperate now and help is super appreciated.

My code file structure is like this:

list-container
     |___module.js
     |
     |___controllers
     |       |____list-container.js
     |
     |___directives
     |       |____list-container.js
     |
     |___views
           |____directive-list-container.html

Below is the code:

module.js

define([
  'angular',
], function (angular) {
  'use strict';

  return angular.module('ui.listContainer', []);
});

list-container.js(directive)

define([
  'angular',
  '../module',
  '../controllers/list-container'
], function (angular, module) {
  'use strict';

  return angular
    .module('ui.listContainer')
    .directive('listContainer', function () {
    return {
      replace: true,
      restrict: 'E',
      templateUrl: '/modules/list-container/views/directive-list-container.html',
      bindToController: {},
      scope: {},
      controllerAs: 'listVm',
      controller: 'listContainerController'
    };
  });
});

list-container.js(controller)

define([
   'angular',
   '../module'
 ], function (angular, module) {
   'use strict';
   angular.module('ui.listContainer').controller('listContainerController', ['$scope', function ($scope) {

     var listVm = this;

     $scope.refreshPage = function () {
       if (listVm.list) {
         listVm.list = null; //Clear the data
       }
       listVm.list = {};
       listVm.list.pages = feedData(); //Load mock data
     };

     function feedData() {
       var pages = [];
       for(var i = 0; i < 10; i++) {
         pages.push(new PageMock());
       }
       return pages;
     }

     function PageMock() {
       this.items = [];
       for (var i = 0; i < 50; i++) {
         this.items.push(new ItemMock());
       }
     }

     function ItemMock() {
       this.id = Math.floor(Math.random() * 10000000);
     }

   }]);
 });

directive-list-container.html(view)

Refresh Page

                    {{listItem.id}}

I created a plunker to mimic the code I have above, however it's not leaking at all in the plunker example, which is super weird.
Plunker Example


问:
Finding similar strings (same words in different order) in a list
I have a list of strings:

```<code> listA = [u'hour block', u'block hour', u'package hour', u'hour block hour']
</code>```

I want to find all strings that are similar (i.e., from the above example 'hour block' and 'block hour') and include only the string that occurred first from the two (i.e., 'hour block' in this case), and the remaining strings occur in their order.

So, the output of the above should be:

```<code>[u'hour block', u'package hour', u'hour block hour']
</code>```

I'm thinking in the following terms:

```<code>>>> for x in listA:
...     y = x.split()
</code>```

But, I can't figure out how do I compare each word of the strings in the list optimally?

答:
Not the cleanest solution, but it gets the job done.

```<code>listB = [y.split() for y in listA]
listC = []
for i, l1 in enumerate(listB[::-1]):
   flag = 0
   for j, l2 in enumerate(listB[::-1][i + 1:]):
      if len(l1) == len(l2) and set(l1) == set(l2):
          flag = 1
          break
   if flag == 0:
      listC.append(l1)

listC = [' '.join(c) for c in listC[::-1]]
print listC
</code>```

Output:

```<code>[u'hour block', u'package hour', u'hour block hour']
</code>```

Body:
I have a list of strings:

 listA = [u'hour block', u'block hour', u'package hour', u'hour block hour']

I want to find all strings that are similar (i.e., from the above example 'hour block' and 'block hour') and include only the string that occurred first from the two (i.e., 'hour block' in this case), and the remaining strings occur in their order.

So, the output of the above should be:

[u'hour block', u'package hour', u'hour block hour']

I'm thinking in the following terms:

>>> for x in listA:
...     y = x.split()

But, I can't figure out how do I compare each word of the strings in the list optimally?

Body:
Not the cleanest solution, but it gets the job done.

listB = [y.split() for y in listA]
listC = []
for i, l1 in enumerate(listB[::-1]):
   flag = 0
   for j, l2 in enumerate(listB[::-1][i + 1:]):
      if len(l1) == len(l2) and set(l1) == set(l2):
          flag = 1
          break
   if flag == 0:
      listC.append(l1)

listC = [' '.join(c) for c in listC[::-1]]
print listC

Output:

[u'hour block', u'package hour', u'hour block hour']


问:
How to handle continuous or quickly repeating actions with redux
I am trying to reason about the best way to handle continuous, quickly repeating actions in Redux.

Say for example, I have a series of sliders representing RGB values and a component of my state is Color which is set via action by these sliders.

A user could be flying back and forth across a slider, if I trigger a new action for every change, then it's possible the slider could appear to stutter. For example, the user could be manipulating the Red slider. One action could be dispatched at a value of 0.5, and the user keeps sliding very quickly to 1.0. by the time the state update gets back the user is at 1.0 but the state update is for 0.5, followed soon after by the 1.0 event.

The result will be a slider knob that jumps back then jumps forward. For the sake of the question, lets just assume that's the case.

Anyway, I am curious how to prevent something like that. My first instinct would be to debounce the Action and let the view update it's representation accordingly. Then when the debounced action does eventually fire, it means the user has stopped, so when the new value of Color comes in from the state they will be equal and it will look like nothing has changed.

Is this the right way to handle something like this or am I missing something?

答: Yep, handling updates locally via component state and debouncing dispatch of a Redux action is an absolutely viable strategy.  I actually discussed this in my blog post Practical Redux, Part 7: Form Change Handling, Data Editing, and Feature Reducers, where I show off a reusable generic form input buffering component that can handle that for you.</p>


问:
Blueimp Image Gallery: More than one Gallery getting Collapsed
```<code>I am using Blueimp Image Gallery Library to create my gallery. I am having multiple galleries across several pages.

<div id="bangles">
    <a href="images/banles.jpg" title="banles" data-gallery>
        <img src="images/thumbnails/banles.jpg" alt="banles">
    </a>
    <a href="images/banles1.jpg" title="bangles1" data-gallery>
        <img src="images/thumbnails/banles1.jpg" alt="banles">
    </a>
    <a href="images/banles2.jpg" title="banles2" data-gallery>
    <img src="images/thumbnails/banles2.jpg" alt="banles">
    </a>
</div>

<div id="florals">
    <a href="images/florals.jpg" title="florals" data-gallery>
        <img src="images/thumbnails/florals.jpg" alt="florals">
    </a>
    <a href="images/florals1.jpg" title="florals1" data-gallery>
        <img src="images/thumbnails/florals1.jpg" alt="florals">
    </a>
    <a href="images/florals2.jpg" title="florals2" data-gallery>
    <img src="images/thumbnails/florals2.jpg" alt="florals">
    </a>
</div>
</code>```

Here is my sample code. while i am trying open image gallery images collapsed across all.

I want to view each gallery in each page.

How do acheive this?

答:
Simply modify your data-gallery tag with each gallery parent-ID

for eg:
you have 2 gallery in your post, those id's are florals and bangles
so you can modify data-gallery inside gallery preceded by #blueimp-gallery

1)

2)  data-gallery="#blueimp-gallery-florals">

now you can able to open each gallery as you want.

Check out the href="https://github.com/blueimp/Gallery#container-ids-and-link-grouping" rel="nofollow noreferrer">Documentation on Github

Body:
I am using Blueimp Image Gallery Library to create my gallery. I am having multiple galleries across several pages.

Here is my sample code. while i am trying open image gallery images collapsed across all.

I want to view each gallery in each page.

How do acheive this?

Body:
Simply modify your data-gallery tag with each gallery parent-ID

for eg:
you have 2 gallery in your post, those id's are florals and bangles
so you can modify data-gallery inside gallery preceded by #blueimp-gallery

1)  <a data-gallery="#blueimp-gallery-bangles">

2)  <a data-gallery="#blueimp-gallery-florals">

now you can able to open each gallery as you want.

Check out the Documentation on Github


问:
Raw LWIP UDP Broadcast
So, I've got a working TCP Echo example working. What I'm attempting to accomplish is to be able to receive TCP Transmissions, as well as send data over TCP and UDP. I'm using raw LWIP and will have a PC App I'll interact with. I want to be able to send a UDP Broadcast or TCP Unicast on demand. I'm having issues where I get a -6 ( ERR_VAL        -6    /* Illegal value.           */) error from the sendto function. Any input as to what I may be missing would be helpful. My first pass at getting a UDP Broadcast Working is here (at the moment I just added this function to the bottom of echo.c):</p>

```<code>void echo_tx()
{

// Attempt a UDP Broadcast
// l_udp_pcb
  err_t wr_err = ERR_OK;
  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, 1024, PBUF_RAM);
  l_udp_pcb = udp_new();
  wr_err = udp_bind(l_udp_pcb, IP_ADDR_ANY, 0);
  wr_err = udp_connect(l_udp_pcb, IP_ADDR_ANY, 10);
  unsigned char buffer_send[1024] = "My Name Is What";
  p->payload = buffer_send;
  p->len = 1024;
  p->tot_len = 1024;
  wr_err = udp_sendto(l_udp_pcb,p, IP_ADDR_BROADCAST, 10);
  if(wr_err != ERR_OK)
  {
    wr_err = udp_sendto(l_udp_pcb,p, IP_ADDR_BROADCAST, 10);
  }
  pbuf_free(p);
}
</code>```

答:
You need to set the broadcast option on the PCB after you allocate it with udp_new():

```<code>ip_set_option(l_udp_pcb, SOF_BROADCAST);
</code>```

Title: Raw LWIP UDP Broadcast

Body:
So, I've got a working TCP Echo example working. What I'm attempting to accomplish is to be able to receive TCP Transmissions, as well as send data over TCP and UDP. I'm using raw LWIP and will have a PC App I'll interact with. I want to be able to send a UDP Broadcast or TCP Unicast on demand. I'm having issues where I get a -6 ( ERR_VAL        -6    /* Illegal value.           */) error from the sendto function. Any input as to what I may be missing would be helpful. My first pass at getting a UDP Broadcast Working is here (at the moment I just added this function to the bottom of echo.c):

void echo_tx()
{

// Attempt a UDP Broadcast
// l_udp_pcb
  err_t wr_err = ERR_OK;
  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, 1024, PBUF_RAM);
  l_udp_pcb = udp_new();
  wr_err = udp_bind(l_udp_pcb, IP_ADDR_ANY, 0);
  wr_err = udp_connect(l_udp_pcb, IP_ADDR_ANY, 10);
  unsigned char buffer_send[1024] = "My Name Is What";
  p->payload = buffer_send;
  p->len = 1024;
  p->tot_len = 1024;
  wr_err = udp_sendto(l_udp_pcb,p, IP_ADDR_BROADCAST, 10);
  if(wr_err != ERR_OK)
  {
    wr_err = udp_sendto(l_udp_pcb,p, IP_ADDR_BROADCAST, 10);
  }
  pbuf_free(p);
}

Body:
You need to set the broadcast option on the PCB after you allocate it with udp_new():

ip_set_option(l_udp_pcb, SOF_BROADCAST);


问:
where should I save a complex MVC application UI state?
I've been having a look at several MVC frameworks (like rails, merb, cakephp, codeignitier, and similars...)

All the samples I've seen are basically plain and simple CRUD pages, carrying all the infr needed in the querystring and the posted field values.

I've got a couple of apps made with some sort of framework built with classic asp.

This framework handles some CRUD stuff a little more complex than the examples I found.

Something like master-detail, filtering by example, paging, sorting and similars.

I have a controller class that it's just a finite state machine, that goes thru diferent states (like new, browse, filter, show, etc.), then performs the appropiate action depending on the event raised and finally retrieves the neede info to the calling page.

To achieve this I have several hidden inputs to keep the state of the web page (like current id, filter criterias, order criterias, previous state, previous event, well, you get the idea)

What do you think would be the finnest approach to achieve this kind of funcionality?

hidden inputs built in the view and used from the controller??? (I guess that would be the equivalent of what I'm doing right now in classi asp)

--

(added in response to tvanfosson)

basically, my question refers to the third category, the context-dependent setting (in respect to the other two categories I agree with you) the info I was storing in hidden fields to store them on the querystring, I guess that when you click on the "next page" you include everything you need to save in the querystring, right? so that piece of query string gets appended in each and every link that performns some kind of action...

I'm not sure, what are the advantages and disadvantages of using the querystring instead of hidden inputs???

答:
I use different strategies depending on the character of the actual data.  Things that are preferences, like default page size, I keep in a Preferences object (table) that is associated with the current logged in user and retrieve from there when needed.

Persistent settings associated with the current logon, like filter settings for a page, are stored in the user's session.  Generally these are things that if a user sets them in the current session they should remain sticky.  I think filter settings and visibility are like this.  If I filter a list, navigate away from it to drill down into a particular item, then come back to the list, I want my filter settings to be reapplied -- so I make it part of the session.

Context-dependent settings -- like the current sort column or page number, are controlled using query parameters.  Paging and sort controls (links) are built with the appropriate query parameters to "do the right thing" when clicked and pass any necessary query parameters to maintain or update the current context of the control.  Using the query parameters allows you to use an HTTP GET, which is bookmarkable, rather than a POST.  Using hidden form parameters makes it much harder for the user to save or enter a URL that takes them directly where they want to go.  This is probably more useful for sorting than it is for paging, but the principle applies equally.

OwnerDisplayName: tvanfosson

LastEditorDisplayName: tvanfosson


问:
Could not find com.android.support:appcompat-v7:25.3.1
I suddenly started getting this error when trying to build. This was all working a few weeks ago with no changes that I know of. The issue seems to be related to react-native-fbsdk, but looking through its build.gradle it does not list support.appcompat-v7.25.x. Any advice?

```<code>A problem occurred configuring project ':app'.
> A problem occurred configuring project ':react-native-fbsdk'.
   > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugCompile'.
      > Could not find com.android.support:appcompat-v7:25.3.1.
        Searched in the following locations:
            file:/Users/a/.m2/repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.pom
            file:/Users/a/.m2/repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.jar
            https://jcenter.bintray.com/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.pom
            https://jcenter.bintray.com/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.jar
</code>```

build.gradle

```<code>apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

import com.android.build.OutputFile

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "___"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 22
        versionName "1.5.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        manifestPlaceholders = [manifestApplicationId: "___",
                                onesignal_app_id: "___",
                                onesignal_google_project_number: "___"]
        multiDexEnabled true
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true
    }
    signingConfigs {
      release {
        storeFile file(MYAPP_RELEASE_STORE_FILE)
        storePassword MYAPP_RELEASE_STORE_PASSWORD
        keyAlias MYAPP_RELEASE_KEY_ALIAS
        keyPassword MYAPP_RELEASE_KEY_PASSWORD
      }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-device-info')
    compile project(':react-native-code-push')
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-image-picker')
    compile project(':react-native-fs')
    compile project(':react-native-vector-icons')
    compile project(':react-native-material-kit')
    compile project(':react-native-config')
    compile project(':react-native-onesignal')
    compile project(':react-native-push-notification')
    compile project(':react-native-android-permissions')
    compile project(':react-native-android-keyboard-adjust')
    compile project(':react-native-fbsdk')
    compile (project(':react-native-fbads')) {
      exclude group: 'com.google.android.gms'
    }
    compile 'com.facebook.android:audience-network-sdk:4.18.+'
    compile 'com.google.ads.mediation:facebook:4.18.+'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-ads:10.2.0'
    compile project(':react-native-billing')
    compile project(':react-native-blur')
    compile project(':instabug-reactnative')
    compile project(':mobile-center-analytics')
    compile project(':mobile-center-crashes')
    compile (project(':react-native-appodeal')) {
      exclude group: 'com.facebook.ads'
      exclude (group: 'javax.inject', module: 'javax.inject')
    }
    compile project(':cheetah')

    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile "com.facebook.fresco:animated-gif:0.12.0"
    compile "com.android.support:multidex:1.0.1"
}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'
</code>```

答: If you upgraded react-native-fbsdk from 0.5 to 0.6 versions and have this issue then open your android project (pathToYourApp/android) in Android Studio and it automatically offers you to update dependencies. Now It should work fine!

Body:
I suddenly started getting this error when trying to build. This was all working a few weeks ago with no changes that I know of. The issue seems to be related to react-native-fbsdk, but looking through its build.gradle it does not list support.appcompat-v7.25.x. Any advice?

A problem occurred configuring project ':app'.
> A problem occurred configuring project ':react-native-fbsdk'.
   > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugCompile'.
      > Could not find com.android.support:appcompat-v7:25.3.1.
        Searched in the following locations:
            file:/Users/a/.m2/repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.pom
            file:/Users/a/.m2/repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.jar
            https://jcenter.bintray.com/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.pom
            https://jcenter.bintray.com/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.jar

build.gradle

apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

import com.android.build.OutputFile

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "___"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 22
        versionName "1.5.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        manifestPlaceholders = [manifestApplicationId: "___",
                                onesignal_app_id: "___",
                                onesignal_google_project_number: "___"]
        multiDexEnabled true
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true
    }
    signingConfigs {
      release {
        storeFile file(MYAPP_RELEASE_STORE_FILE)
        storePassword MYAPP_RELEASE_STORE_PASSWORD
        keyAlias MYAPP_RELEASE_KEY_ALIAS
        keyPassword MYAPP_RELEASE_KEY_PASSWORD
      }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-device-info')
    compile project(':react-native-code-push')
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-image-picker')
    compile project(':react-native-fs')
    compile project(':react-native-vector-icons')
    compile project(':react-native-material-kit')
    compile project(':react-native-config')
    compile project(':react-native-onesignal')
    compile project(':react-native-push-notification')
    compile project(':react-native-android-permissions')
    compile project(':react-native-android-keyboard-adjust')
    compile project(':react-native-fbsdk')
    compile (project(':react-native-fbads')) {
      exclude group: 'com.google.android.gms'
    }
    compile 'com.facebook.android:audience-network-sdk:4.18.+'
    compile 'com.google.ads.mediation:facebook:4.18.+'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-ads:10.2.0'
    compile project(':react-native-billing')
    compile project(':react-native-blur')
    compile project(':instabug-reactnative')
    compile project(':mobile-center-analytics')
    compile project(':mobile-center-crashes')
    compile (project(':react-native-appodeal')) {
      exclude group: 'com.facebook.ads'
      exclude (group: 'javax.inject', module: 'javax.inject')
    }
    compile project(':cheetah')

    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile "com.facebook.fresco:animated-gif:0.12.0"
    compile "com.android.support:multidex:1.0.1"
}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'


问:
How can I get the timezone offset without the DST formatted correctly?
I have not found a way to get the timezone offset without  Daylight Savings Time interference.

```<code>LocalDateTime dt = LocalDateTime.now();
...
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();
</code>```

This would seem like it works, but the initial DataTime might be influenced by DST.

There is also this:

```<code>int rawOffset = tZone.getRawOffset();
</code>```

However, this is always a positive number, so we don't ever get -05:00 back.

So what I want is a way to get the offset without DST interference. Any thoughts?

答:
TimeZone.getRawOffset() will return the correct historical offset, according to the Java API Documentation.

public abstract int getRawOffset()

Returns the amount of time in milliseconds to add to UTC to get standard time in this time zone. Because this value is not affected by daylight saving time, it is called raw offset.

If an underlying TimeZone implementation subclass supports historical GMT offset changes, the method returns the raw offset value of the current date. In Honolulu, for example, its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and this method always returns -36000000 milliseconds (i.e., -10 hours).

Returns:
     the amount of raw offset time in milliseconds to add to UTC.
  See Also:
     Calendar.ZONE_OFFSET

from: https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getRawOffset()

Body:
I have not found a way to get the timezone offset without  Daylight Savings Time interference.

LocalDateTime dt = LocalDateTime.now();
...
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();

This would seem like it works, but the initial DataTime might be influenced by DST.

There is also this:

int rawOffset = tZone.getRawOffset();

However, this is always a positive number, so we don't ever get -05:00 back.

So what I want is a way to get the offset without DST interference. Any thoughts?


问:
elasticsearch - Could not find or load main class -Xms2g
I installed elasticsearch with homebrew on Mac OSX Sierra (10.12.5).

The installation with homebrew appears successful and brew info states it is installed meeting all prerequisites.

When I go to run the "elasticsearch" command, I get the following error...

```<code>Error: Could not find or load main class -Xms2g
</code>```

I have tried installing java 1.8 both via homebrew and manually.

I am using java JDK not JRE.

I also tried installing elasticsearch manually, however the installation itself fails with the same exact error.

Any insight would be appreciated.

=== UPDATE ===

Quick answer below.

Additional information can be found here:
Unable to install Elasticsearch on Mac Sierra (10.12.2)

答:
If you have set :

```<code>export GREP_OPTIONS='--color=always'
</code>```

in your .bashrc or somewhere else, it will probably broke shell pipes and causes problems. Try to remove it.

Body:
I installed elasticsearch with homebrew on Mac OSX Sierra (10.12.5).

The installation with homebrew appears successful and brew info states it is installed meeting all prerequisites.

When I go to run the "elasticsearch" command, I get the following error...

Error: Could not find or load main class -Xms2g

I have tried installing java 1.8 both via homebrew and manually.

I am using java JDK not JRE.

I also tried installing elasticsearch manually, however the installation itself fails with the same exact error.

Any insight would be appreciated.

=== UPDATE ===

Quick answer below.

Additional information can be found here:
Unable to install Elasticsearch on Mac Sierra (10.12.2)

Body:
If you have set :

export GREP_OPTIONS='--color=always'

in your .bashrc or somewhere else, it will probably broke shell pipes and causes problems. Try to remove it.


问:
Debugging source files using chrome extension
I am trying to control the debugger using Chrome Extension.

I am using devtools-protocol and chrome extension documentation, but I have no idea how to implement them as I have not seen any samples of the methods in use. I used the sample extension from here which shows how to pause and resume the debugger only, but that's absolutely no use to me. I tried to implement some methods in the sample, but nothing happens.

```<code>function onDebuggerEnabled(debuggeeId) {
  chrome.debugger.sendCommand(debuggeeId, "Debugger.setBreakpointByUrl", {
        lineNumber: 45825,
        url: 'full https link to the js file from source tab'
  });
}
</code>```

The problem is that the js file I am trying to debug is loaded from the website inside the sources tab and it's huge, we talking 150k+ lines after its been formatted and it takes some time to load.

Now can anyone tell me how to simply add a break point inside the js file from the sources (USING CHROME EXTENSION) so it could be triggered on action which will then stops the debugger so I could change values etc?

答:
```<code>function breakhere() {
    debugger;
}
</code>```

Body:
I am trying to control the debugger using Chrome Extension.

I am using devtools-protocol and chrome extension documentation, but I have no idea how to implement them as I have not seen any samples of the methods in use. I used the sample extension from here which shows how to pause and resume the debugger only, but that's absolutely no use to me. I tried to implement some methods in the sample, but nothing happens.

function onDebuggerEnabled(debuggeeId) {
  chrome.debugger.sendCommand(debuggeeId, "Debugger.setBreakpointByUrl", {
        lineNumber: 45825,
        url: 'full https link to the js file from source tab'
  });
}

The problem is that the js file I am trying to debug is loaded from the website inside the sources tab and it's huge, we talking 150k+ lines after its been formatted and it takes some time to load.

Now can anyone tell me how to simply add a break point inside the js file from the sources (USING CHROME EXTENSION) so it could be triggered on action which will then stops the debugger so I could change values etc?

Body:
function breakhere() {
    debugger;
}


问:
Handling Logs/Transactions of huge volume
We have a Multi-threaded Enterprise application that is deployed in three different data centers and they receive XML messages in queues from an upstream system. The Volume of data that is being drained by the application is very huge and the logs that the system writes is in order of 200GB/hour. The Logs are maintained for a very shorter period of time. The application basically, writes to cassandra DB / IBM Extreme Scale Grid / Oracle DB. Now the exact issue, is that, we don't have a track on the transactions that are received/processed by the application. Said that, There are a lot of data synch up issues with the upstream systems and we don't have a way to track whether we recived/processed the message successfully after a period of time. We also don't have capacity to save the messages or redirect logs to any Big data file system because of the infrastructure limitations we have. Is there a way that this issue can be addressed. Please give in your comments and suggestions. Thanks in advance.</p>

答: For problem determination, the easiest and simplest method is to make sure every XML message has a unique transaction id.  Hence, your application logs/stores the transaction id and not the whole XML message.  When there are issues then you compare the transaction ids for which one(s) is/are missing.  And transaction id that is missing, you have the sender application resend the XML message.</p>


问:
Multi-list iteration with default value in Python
I'm running an experiment with python simulation, and need to create a list of input cases.

Each case is an instance taken from a list of list of parameters, For example:

```<code>heights = [100,110,120]
alphas = [0.1,0.01,0.001]
C = [0.1,0.2,0.5,0.9]
B = [1,2]
</code>```

and the list of lists is:

```<code>params = [heights,alphas,C,B]
</code>```

The original amount is bigger (~30x100) so it's not efficient to address each list directly.

Eventually each input case is a tuple/namedtuple/dictionary of one parameter from each category, for example:

```<code>instance = {'height':100, 'alpha':0.1,'C:0.1, 'B':1}
</code>```

I would like to iterate the parameter space in order to create a list of instances - but here is the catch:

Instead of making a cartesian product of all of them, per each parameter I want to iterate all the options, while the rest of categories are set to a default value (the first). For example:

```<code>params = [[1,2,3],[4,5][7,8]]
</code>```

the expected set of instances (with no repeat) is:

[(1,4,7),(2,4,7),(3,4,7),(1,5,7)(1,4,8)]

where 1 is the default of first index, 4 is the default of the second index and 7 is the default of the 3rd.

Making a cartesian product is quite easy with itertools:

```<code>from itertools import product
params = [[1,2,3],[4,5],[7,8]]
list(product(*params))
</code>```

[(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

then I can filter out unnecessary instances, but it sounds ineficient to generate them at first place. Is there any elegant way to build this iteration?

答:
```<code>params = [[1, 2, 3], [4, 5], [7, 8]]
default = [par[0] for par in params]
instances = set()

for ii, pp in enumerate(params):
    for value in pp:
        new_instance = default[:ii] + [value] + default[ii + 1:]
        instances.add(tuple(new_instance))
</code>```

Body:
I'm running an experiment with python simulation, and need to create a list of input cases.

Each case is an instance taken from a list of list of parameters, For example:

heights = [100,110,120]
alphas = [0.1,0.01,0.001]
C = [0.1,0.2,0.5,0.9]
B = [1,2]

and the list of lists is:

params = [heights,alphas,C,B]

The original amount is bigger (~30x100) so it's not efficient to address each list directly.

Eventually each input case is a tuple/namedtuple/dictionary of one parameter from each category, for example:

instance = {'height':100, 'alpha':0.1,'C:0.1, 'B':1}

I would like to iterate the parameter space in order to create a list of instances - but here is the catch:

Instead of making a cartesian product of all of them, per each parameter I want to iterate all the options, while the rest of categories are set to a default value (the first). For example:

params = [[1,2,3],[4,5][7,8]]

the expected set of instances (with no repeat) is:

[(1,4,7),(2,4,7),(3,4,7),(1,5,7)(1,4,8)]

where 1 is the default of first index, 4 is the default of the second index and 7 is the default of the 3rd.

Making a cartesian product is quite easy with itertools:

from itertools import product
params = [[1,2,3],[4,5],[7,8]]
list(product(*params))

[(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

then I can filter out unnecessary instances, but it sounds ineficient to generate them at first place. Is there any elegant way to build this iteration?


问:
Clear cell contents in a data bound datagridview
I am trying to implement a delete functionality in my DataGridView to clear the contents of highlighted cells.

One of the columns contains a double, and when the value is less than zero I display it as blank. If the user edits the cell to blank, this is handled via the CellParsing event.

The DataGridView is databound using a BindingSource and BindingList.

The issue I'm having is that when I change the cell Value to blank via my clear function, the CellParsing event does not fire and I get a FormatException saying that "" is not a valid value for Double. When the user clears the cell, the CellParsing event fires and everything happens as expected.

The reason I am setting the value to blank is that some of the columns are text and others are numbers, and I'd like to be able to delete them all at once.

I've googled and searched through StackOverflow and haven't found something yet that will solve my issue. Is there a way to route this through the CellParsing event or some other obvious solution that I'm missing?

See the CellParsing and clearing code below.

```<code>System::Void dataGridViewWells_CellParsing(System::Object^  sender, System::Windows::Forms::DataGridViewCellParsingEventArgs^  e)
{
    //Handle blank values in the mass column
    e->ParsingApplied = false;
    if(this->dataGridViewWells->Columns[e->ColumnIndex]->HeaderText == "Mass (ng)")
    {
        if(e->Value->ToString() == "" || e->Value->ToString() == " ")
        {
            e->Value = -1.0;
            e->ParsingApplied = true;
        }
    }
}

void DeleteHighlightedCells(DataGridView^ dgv)
{
    try
    {
        System::Windows::Forms::DataGridViewSelectedCellCollection^ sCells = dgv->SelectedCells;
        for(int i = 0; i < sCells->Count; i++)
        {
            if(!sCells[i]->ReadOnly)
            {
                dgv->Rows[sCells[i]->RowIndex]->Cells[sCells[i]->ColumnIndex]->Value = "";
            }
        }
    }
    catch(Exception^ e)
    {
        LogError("Unable to delete contents of DataGridView cells: " + e->ToString());
    }
}

System::Void dataGridViewWells_KeyDown(System::Object^  sender, System::Windows::Forms::KeyEventArgs^  e)
{
    if(e->Control && e->KeyCode == Keys::C)
    {
        this->CopyContentsToClipBoard(this->dataGridViewWells);
    }

    if(e->Control && e->KeyCode == Keys::V)
    {
        this->PasteContentsFromClipBoard(this->dataGridViewWells);
    }

    if(e->KeyCode == Keys::Delete)
    {
        this->DeleteHighlightedCells(this->dataGridViewWells);
    }
}
</code>```

答:
I ended up abandoning the CellParsing event and putting in a custom TypeConverter for my class property as was done in this question.

TypeConverter code:

```<code>public ref class MassTypeConverter : System::ComponentModel::TypeConverter
{
public:
    virtual bool CanConvertFrom(System::ComponentModel::ITypeDescriptorContext^ context, Type^ sourceType) override
    {
        return sourceType == String::typeid || System::ComponentModel::TypeConverter::CanConvertFrom(context, sourceType);
    }
    virtual Object^ ConvertFrom(System::ComponentModel::ITypeDescriptorContext^ context, System::Globalization::CultureInfo^ culture, Object^ value) override
    {
        if(value != nullptr && value->GetType() == String::typeid)
        {
            //
            double converted;
            bool success = double::TryParse((String^)value, converted);
            if(((String^)value) == "" || ((String^)value) == " ")
            {
                converted = -1.0;
                success = true;
            }
            if(success)
            {
                return converted;
            }
        }
        return System::ComponentModel::TypeConverter::ConvertFrom(context, culture, value);
    }
};
</code>```

And then put the following above my class Property:

```<code>[System::ComponentModel::TypeConverter(MassTypeConverter::typeid)]
</code>```

Body:
I am trying to implement a delete functionality in my DataGridView to clear the contents of highlighted cells.

One of the columns contains a double, and when the value is less than zero I display it as blank. If the user edits the cell to blank, this is handled via the CellParsing event.

The DataGridView is databound using a BindingSource and BindingList.

The issue I'm having is that when I change the cell Value to blank via my clear function, the CellParsing event does not fire and I get a FormatException saying that "" is not a valid value for Double. When the user clears the cell, the CellParsing event fires and everything happens as expected.

The reason I am setting the value to blank is that some of the columns are text and others are numbers, and I'd like to be able to delete them all at once.

I've googled and searched through StackOverflow and haven't found something yet that will solve my issue. Is there a way to route this through the CellParsing event or some other obvious solution that I'm missing?

See the CellParsing and clearing code below.

System::Void dataGridViewWells_CellParsing(System::Object^  sender, System::Windows::Forms::DataGridViewCellParsingEventArgs^  e)
{
    //Handle blank values in the mass column
    e->ParsingApplied = false;
    if(this->dataGridViewWells->Columns[e->ColumnIndex]->HeaderText == "Mass (ng)")
    {
        if(e->Value->ToString() == "" || e->Value->ToString() == " ")
        {
            e->Value = -1.0;
            e->ParsingApplied = true;
        }
    }
}

void DeleteHighlightedCells(DataGridView^ dgv)
{
    try
    {
        System::Windows::Forms::DataGridViewSelectedCellCollection^ sCells = dgv->SelectedCells;
        for(int i = 0; i < sCells->Count; i++)
        {
            if(!sCells[i]->ReadOnly)
            {
                dgv->Rows[sCells[i]->RowIndex]->Cells[sCells[i]->ColumnIndex]->Value = "";
            }
        }
    }
    catch(Exception^ e)
    {
        LogError("Unable to delete contents of DataGridView cells: " + e->ToString());
    }
}

System::Void dataGridViewWells_KeyDown(System::Object^  sender, System::Windows::Forms::KeyEventArgs^  e)
{
    if(e->Control && e->KeyCode == Keys::C)
    {
        this->CopyContentsToClipBoard(this->dataGridViewWells);
    }

    if(e->Control && e->KeyCode == Keys::V)
    {
        this->PasteContentsFromClipBoard(this->dataGridViewWells);
    }

    if(e->KeyCode == Keys::Delete)
    {
        this->DeleteHighlightedCells(this->dataGridViewWells);
    }
}

Body:
I ended up abandoning the CellParsing event and putting in a custom TypeConverter for my class property as was done in this question.

TypeConverter code:

public ref class MassTypeConverter : System::ComponentModel::TypeConverter
{
public:
    virtual bool CanConvertFrom(System::ComponentModel::ITypeDescriptorContext^ context, Type^ sourceType) override
    {
        return sourceType == String::typeid || System::ComponentModel::TypeConverter::CanConvertFrom(context, sourceType);
    }
    virtual Object^ ConvertFrom(System::ComponentModel::ITypeDescriptorContext^ context, System::Globalization::CultureInfo^ culture, Object^ value) override
    {
        if(value != nullptr && value->GetType() == String::typeid)
        {
            //
            double converted;
            bool success = double::TryParse((String^)value, converted);
            if(((String^)value) == "" || ((String^)value) == " ")
            {
                converted = -1.0;
                success = true;
            }
            if(success)
            {
                return converted;
            }
        }
        return System::ComponentModel::TypeConverter::ConvertFrom(context, culture, value);
    }
};

And then put the following above my class Property:

[System::ComponentModel::TypeConverter(MassTypeConverter::typeid)]


问:
AWS Elastic Beanstalk: Add custom logs to CloudWatch?
How to add custom logs to CloudWatch? Defaults logs are sent but how to add a custom one?

I already added a file like this: (in .ebextensions)

```<code>files:
  "/opt/elasticbeanstalk/tasks/bundlelogs.d/applogs.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*

  "/opt/elasticbeanstalk/tasks/taillogs.d/cloud-init.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*
</code>```

As I did bundlelogs.d and taillogs.d these custom logs are now tailed or retrieved from the console or web, that's nice but they don't persist and are not sent on CloudWatch.

In CloudWatch I have the defaults logs like

 /aws/elasticbeanstalk/InstanceName/var/log/eb-activity.log

And I want to have another one like this

/aws/elasticbeanstalk/InstanceName/var/app/current/logs/mycustomlog.log

答:
The awslogs agent looks in the configuration file for the log files which it's supposed to send. There are some defaults in it. You need to edit it and specify the files.

You can check and edit the configuration file located at:

```<code>/etc/awslogs/awslogs.conf
</code>```

Make sure to restart the service:

```<code>sudo service awslogs restart
</code>```

You can specify your own files there and create different groups and what not.

Please refer to the following link and you'll be able to get your logs in no time.

Resources:

https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html

Edit:

As you don't want to edit the files on the instance, you can add the relevant code to the .ebextensions folder in the root of your code. For example, this is my 01_cloudwatch.config :

```<code>packages:
  yum:
    awslogs: []

container_commands:
  01_get_awscli_conf_file:
    command: "aws s3 cp s3://project/awscli.conf /etc/awslogs/awscli.conf"
  02_get_awslogs_conf_file:
    command: "aws s3 cp s3://project/awslogs.conf.${NODE_ENV} /etc/awslogs/awslogs.conf"
  03_restart_awslogs:
    command: "sudo service awslogs restart"
  04_start_awslogs_at_system_boot:
    command: "sudo chkconfig awslogs on"
</code>```

In this config, I am fetching the appropriate config file from a S3 bucket depending on the NODE_ENV. You can do anything you want in your config.

Body:
How to add custom logs to CloudWatch? Defaults logs are sent but how to add a custom one?

I already added a file like this: (in .ebextensions)

files:
  "/opt/elasticbeanstalk/tasks/bundlelogs.d/applogs.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*

  "/opt/elasticbeanstalk/tasks/taillogs.d/cloud-init.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*

As I did bundlelogs.d and taillogs.d these custom logs are now tailed or retrieved from the console or web, that's nice but they don't persist and are not sent on CloudWatch.

In CloudWatch I have the defaults logs like

 /aws/elasticbeanstalk/InstanceName/var/log/eb-activity.log

And I want to have another one like this

/aws/elasticbeanstalk/InstanceName/var/app/current/logs/mycustomlog.log

Body:
The awslogs agent looks in the configuration file for the log files which it's supposed to send. There are some defaults in it. You need to edit it and specify the files.

You can check and edit the configuration file located at:

/etc/awslogs/awslogs.conf

Make sure to restart the service:

sudo service awslogs restart

You can specify your own files there and create different groups and what not.

Please refer to the following link and you'll be able to get your logs in no time.

Resources:

https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html

Edit:

As you don't want to edit the files on the instance, you can add the relevant code to the .ebextensions folder in the root of your code. For example, this is my 01_cloudwatch.config :

packages:
  yum:
    awslogs: []

container_commands:
  01_get_awscli_conf_file:
    command: "aws s3 cp s3://project/awscli.conf /etc/awslogs/awscli.conf"
  02_get_awslogs_conf_file:
    command: "aws s3 cp s3://project/awslogs.conf.${NODE_ENV} /etc/awslogs/awslogs.conf"
  03_restart_awslogs:
    command: "sudo service awslogs restart"
  04_start_awslogs_at_system_boot:
    command: "sudo chkconfig awslogs on"

In this config, I am fetching the appropriate config file from a S3 bucket depending on the NODE_ENV. You can do anything you want in your config.


问:
Regex to match strings with substring "/status" unless it contains "subscription/status"
I know how to match strings that end with "/status": ^.*status$.

However, I don't want this to apply to strings that end in "subscription/status".

Your help is much appreciated!

EDIT: I'm using a Javascript library to execute a mongoDB query. This is what I have so far:

```<code>const query = {
  "handler_url_str": {
    "$regex": "^.*status$"
  }
};
</code>```

Unfortunately, this matches all documents that end in "/status".

答:
You may use

```<code>"$regex": /^(?!.*subscription\/status$).*\/status$/
</code>```

See the regex demo

Details:

^ - start of string

(?!.*subscription/status$) - a negative lookahead failing the match if, after any 0+ chars other than line break chars (.*), there is subscription/status at the end of the string

.* -  any 0+ chars other than line break chars

/status  - a literal substring

$ - end of string.

Body:
I know how to match strings that end with "/status": ^.*status$.

However, I don't want this to apply to strings that end in "subscription/status".

Your help is much appreciated!

EDIT: I'm using a Javascript library to execute a mongoDB query. This is what I have so far:

const query = {
  "handler_url_str": {
    "$regex": "^.*status$"
  }
};

Unfortunately, this matches all documents that end in "/status".

Body:
You may use

"$regex": /^(?!.*subscription\/status$).*\/status$/

See the regex demo

Details:

^ - start of string

(?!.*subscription/status$) - a negative lookahead failing the match if, after any 0+ chars other than line break chars (.*), there is subscription/status at the end of the string

.* -  any 0+ chars other than line break chars

/status  - a literal substring

$ - end of string.


问:
Joomla - Cannot configure RSSocial! module
I am currently trying to use RSSocial! extension to add social media button that can link to my social media site. However, when I follow the instruction to edit the module, there is no parameter that I can change and this is what it showed:

Pressing "Show full description..." show nothing.

Can anyone help me with this issue? Many thanks.

P/s: If there is other way to do the same, I would really appreciated it.

答:
Try the following:

Uninstall and then re-install the extension

Disable PowerAdmin (I suspect that this is the problem)

Let us know of your findings.


问:
Putting Anaconda pip onto Flash drive and installing off it
I am unable to install pip normally because of a proxy at work.  I am going to use a flash drive to transfer it onto the computer.  Is it possible to put just pip onto a flashdrive and transfer it onto different computer to install? If so how?</p>

答: You can install Anaconda to virtualenv and write your venv to flashdrive or write only site-packages/anaconda folder to flash drive


问:
JavaFX Preloader never called from main
My IDE is IntelliJ. I tried this document to learn preloader but for some reason preloader never gets called from my main class, or even its methods get called.

So here is my main class:

```<code>public class LongInitApp extends Application {
Stage stage;
BooleanProperty ready = new SimpleBooleanProperty(false);
private void longStart() {
    //simulate long init in background
    Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            int max = 10;
            for (int i = 1; i <= max; i++) {
                Thread.sleep(200);
                notifyPreloader(new ProgressNotification(((double) i)/max));
            }
            ready.setValue(Boolean.TRUE);

            notifyPreloader(new StateChangeNotification(
                StateChangeNotification.Type.BEFORE_START));
           return null;
        }};
    new Thread(task).start();
}

 public static void main(String args[]) {
    launch(args);
  }

@Override
public void start(final Stage stage) throws Exception {
    longStart();
    stage.setScene(new Scene(new Label("Application started"),400, 400));
    ready.addListener(new ChangeListener<Boolean>(){
        public void changed(
            ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
                if (Boolean.TRUE.equals(t1)) {
                    Platform.runLater(new Runnable() {
                        public void run() {
                            stage.show();
                        }});}}});;}}
</code>```

And my preloader class:

```<code>public class LongAppInitPreloader extends Preloader {
ProgressBar bar;
Stage stage;
boolean noLoadingProgress = true;

private Scene createPreloaderScene() {
    bar = new ProgressBar(0);
    BorderPane p = new BorderPane();
    p.setCenter(bar);
    return new Scene(p, 300, 150);
}

public void start(Stage stage) throws Exception {
    this.stage = stage;
    stage.setScene(createPreloaderScene());
    stage.show();
}

@Override
public void handleProgressNotification(ProgressNotification pn) {
    if (pn.getProgress() != 1.0 || !noLoadingProgress) {
      bar.setProgress(pn.getProgress()/2);
      if (pn.getProgress() > 0) {
          noLoadingProgress = false;
      }
    }
}

@Override
public void handleStateChangeNotification(StateChangeNotification evt) {
    //ignore, hide after application signals it is ready
}

@Override
public void handleApplicationNotification(PreloaderNotification pn) {
    if (pn instanceof ProgressNotification) {
       double v = ((ProgressNotification) pn).getProgress();
       if (!noLoadingProgress) {
           v = 0.5 + v/2;
       }
       bar.setProgress(v);
    } else if (pn instanceof StateChangeNotification) {
        stage.hide();
    }
}
 }
</code>```

You can check this http://docs.oracle.com/javafx/2/deployment/preloaders.htm document too. This codes belong to example 9-11 and 9-12.

答:
You need to specify the preloader class to the application when it launches. A "quick and dirty" way to do this is to use the non-public API class com.sun.javafx.application.LauncherImpl. Note that this class is not guaranteed to be available in future releases of JavaFX, and so you should use this for quick testing only (if at all). Use the following main method in your LongInitApp class:

```<code>public static void main(String[] args) {
    LauncherImpl.launchApplication(LongInitApp.class, LongAppInitPreloader.class, args);
}
</code>```

The "official" way to include a preloader is by specifying it as part of the JavaFX deployment process. Full documentation of the deployment process is at http://docs.oracle.com/javase/8/docs/technotes/guides/deploy/, but a minimal approach is as follows.

Compile the application (your IDE will typically do this when you save anyway)

From the command line, run the javapackager tool with the createjar command:

```<code>javapackager -createjar -outfile myapp.jar -appclass my.package.LongInitApp \
  -preloader my.package.LongAppInitPreloader -srcdir dir
</code>```

where my.package is the package containing your application and preloader classes (these can be in different packages) and dir is the root of the directory structure containing all your classes (e.g. if my.package really were your package name, then dir would have a sub-directory my, which would have a subdirectory package, which would contain the .class files).

This will generate a myapp.jar file which is executable and aware of your preloader, so you can then execute it with java -jar myapp.jar. If you're interested, you can extract the generated manifest from the jar file and see what's in it with jar xf myapp.jar META-INF/MANIFEST.MF (and then view the file META-INF/MANIFEST.MF). (In brief, what this does is declare the main class to be an internal class designed to launch a JavaFX application. The manifest file contains properties specifying the JavaFX application class (LongInitApp in your case) and the preloader class, if one exists. The internal class that launches the application retrieves these properties and its main method basically launches the application you have defined, using the preloader if it's there.)

Note your application class LongInitApp does not need (and probably should not have) a main method if you use this approach.

Most IDEs have some form of support for this. E.g. if you use Eclipse with the E(fx)clipse plugin, and create a JavaFX project, it will generate a build.fxbuild file for you. Double-clicking that file will open a visual editor where you can set the properties defined in the javapackager command above. Clicking on "Generate ant build.xml and run" will then create the jar file.

Unless you need the specific functionality that a preloader provides, above and beyond that which you can easily program yourself, it may not be worth the effort of going through this. Specifically, a preloader is particularly useful if you are deploying your application via Java Web Start, and the download of the main jar file will take a long time. The preloader can be shown while that is occurring. If you are using a standalone application (or self-contained application package), then you can pretty easily create the "preloader" functionality yourself.

For example, unless I were using Java Web Start and the main jar file were large, I would probably refactor your example code by making the "preloader" just a regular old class:

```<code>import javafx.scene.Scene;
import javafx.beans.property.DoubleProperty ;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class LongAppInitPreloader {
    private ProgressBar bar;

    private Stage stage;

    public LongAppInitPreloader() {
        this.stage = new Stage();
        stage.setScene(createPreloaderScene());
    }

    private Scene createPreloaderScene() {
        bar = new ProgressBar(0);
        BorderPane p = new BorderPane();
        p.setCenter(bar);
        return new Scene(p, 300, 150);
    }

    public void show() {
        stage.show();
    }

    public void hide() {
        stage.hide();
    }

    public DoubleProperty progressProperty() {
        return bar.progressProperty();
    }
}
</code>```

and then your application class can just use a task and update its progress:

```<code>import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class LongInitApp extends Application {

    @Override
    public void start(final Stage stage) throws Exception {
        Task<Void> task = createLongStartTask();

        stage.setScene(new Scene(new Label("Application started"), 400, 400));

        LongAppInitPreloader preloader = new LongAppInitPreloader();
        preloader.progressProperty().bind(task.progressProperty());

        task.setOnSucceeded(e -> {
            stage.show();
            preloader.hide();
        });
        preloader.show();

        new Thread(task).start();
    }

    private Task<Void> createLongStartTask() {
        // simulate long init in background
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                int max = 10;
                for (int i = 1; i <= max; i++) {
                    Thread.sleep(200);
                    updateProgress(i, max);
                }

                return null;
            }
        };
        return task ;
    }

    // just here so I can run directly from Eclipse:
    public static void main(String args[]) {
        launch(args);
    }
}
</code>```

Title: JavaFX Preloader never called from main

Body:
My IDE is IntelliJ. I tried this document to learn preloader but for some reason preloader never gets called from my main class, or even its methods get called.

So here is my main class:

public class LongInitApp extends Application {
Stage stage;
BooleanProperty ready = new SimpleBooleanProperty(false);
private void longStart() {
    //simulate long init in background
    Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            int max = 10;
            for (int i = 1; i <= max; i++) {
                Thread.sleep(200);
                notifyPreloader(new ProgressNotification(((double) i)/max));
            }
            ready.setValue(Boolean.TRUE);

            notifyPreloader(new StateChangeNotification(
                StateChangeNotification.Type.BEFORE_START));
           return null;
        }};
    new Thread(task).start();
}

 public static void main(String args[]) {
    launch(args);
  }

@Override
public void start(final Stage stage) throws Exception {
    longStart();
    stage.setScene(new Scene(new Label("Application started"),400, 400));
    ready.addListener(new ChangeListener<Boolean>(){
        public void changed(
            ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
                if (Boolean.TRUE.equals(t1)) {
                    Platform.runLater(new Runnable() {
                        public void run() {
                            stage.show();
                        }});}}});;}}

And my preloader class:

public class LongAppInitPreloader extends Preloader {
ProgressBar bar;
Stage stage;
boolean noLoadingProgress = true;

private Scene createPreloaderScene() {
    bar = new ProgressBar(0);
    BorderPane p = new BorderPane();
    p.setCenter(bar);
    return new Scene(p, 300, 150);
}

public void start(Stage stage) throws Exception {
    this.stage = stage;
    stage.setScene(createPreloaderScene());
    stage.show();
}

@Override
public void handleProgressNotification(ProgressNotification pn) {
    if (pn.getProgress() != 1.0 || !noLoadingProgress) {
      bar.setProgress(pn.getProgress()/2);
      if (pn.getProgress() > 0) {
          noLoadingProgress = false;
      }
    }
}

@Override
public void handleStateChangeNotification(StateChangeNotification evt) {
    //ignore, hide after application signals it is ready
}

@Override
public void handleApplicationNotification(PreloaderNotification pn) {
    if (pn instanceof ProgressNotification) {
       double v = ((ProgressNotification) pn).getProgress();
       if (!noLoadingProgress) {
           v = 0.5 + v/2;
       }
       bar.setProgress(v);
    } else if (pn instanceof StateChangeNotification) {
        stage.hide();
    }
}
 }

You can check this http://docs.oracle.com/javafx/2/deployment/preloaders.htm document too. This codes belong to example 9-11 and 9-12.

Body:
You need to specify the preloader class to the application when it launches. A "quick and dirty" way to do this is to use the non-public API class com.sun.javafx.application.LauncherImpl. Note that this class is not guaranteed to be available in future releases of JavaFX, and so you should use this for quick testing only (if at all). Use the following main method in your LongInitApp class:

public static void main(String[] args) {
    LauncherImpl.launchApplication(LongInitApp.class, LongAppInitPreloader.class, args);
}

The "official" way to include a preloader is by specifying it as part of the JavaFX deployment process. Full documentation of the deployment process is at http://docs.oracle.com/javase/8/docs/technotes/guides/deploy/, but a minimal approach is as follows.

Compile the application (your IDE will typically do this when you save anyway)

From the command line, run the javapackager tool with the createjar command:

javapackager -createjar -outfile myapp.jar -appclass my.package.LongInitApp \
  -preloader my.package.LongAppInitPreloader -srcdir dir

where my.package is the package containing your application and preloader classes (these can be in different packages) and dir is the root of the directory structure containing all your classes (e.g. if my.package really were your package name, then dir would have a sub-directory my, which would have a subdirectory package, which would contain the .class files).

This will generate a myapp.jar file which is executable and aware of your preloader, so you can then execute it with java -jar myapp.jar. If you're interested, you can extract the generated manifest from the jar file and see what's in it with jar xf myapp.jar META-INF/MANIFEST.MF (and then view the file META-INF/MANIFEST.MF). (In brief, what this does is declare the main class to be an internal class designed to launch a JavaFX application. The manifest file contains properties specifying the JavaFX application class (LongInitApp in your case) and the preloader class, if one exists. The internal class that launches the application retrieves these properties and its main method basically launches the application you have defined, using the preloader if it's there.)

Note your application class LongInitApp does not need (and probably should not have) a main method if you use this approach.

Most IDEs have some form of support for this. E.g. if you use Eclipse with the E(fx)clipse plugin, and create a JavaFX project, it will generate a build.fxbuild file for you. Double-clicking that file will open a visual editor where you can set the properties defined in the javapackager command above. Clicking on "Generate ant build.xml and run" will then create the jar file.

Unless you need the specific functionality that a preloader provides, above and beyond that which you can easily program yourself, it may not be worth the effort of going through this. Specifically, a preloader is particularly useful if you are deploying your application via Java Web Start, and the download of the main jar file will take a long time. The preloader can be shown while that is occurring. If you are using a standalone application (or self-contained application package), then you can pretty easily create the "preloader" functionality yourself.

For example, unless I were using Java Web Start and the main jar file were large, I would probably refactor your example code by making the "preloader" just a regular old class:

import javafx.scene.Scene;
import javafx.beans.property.DoubleProperty ;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class LongAppInitPreloader {
    private ProgressBar bar;

    private Stage stage;

    public LongAppInitPreloader() {
        this.stage = new Stage();
        stage.setScene(createPreloaderScene());
    }

    private Scene createPreloaderScene() {
        bar = new ProgressBar(0);
        BorderPane p = new BorderPane();
        p.setCenter(bar);
        return new Scene(p, 300, 150);
    }

    public void show() {
        stage.show();
    }

    public void hide() {
        stage.hide();
    }

    public DoubleProperty progressProperty() {
        return bar.progressProperty();
    }
}

and then your application class can just use a task and update its progress:

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class LongInitApp extends Application {

    @Override
    public void start(final Stage stage) throws Exception {
        Task<Void> task = createLongStartTask();

        stage.setScene(new Scene(new Label("Application started"), 400, 400));

        LongAppInitPreloader preloader = new LongAppInitPreloader();
        preloader.progressProperty().bind(task.progressProperty());

        task.setOnSucceeded(e -> {
            stage.show();
            preloader.hide();
        });
        preloader.show();

        new Thread(task).start();
    }

    private Task<Void> createLongStartTask() {
        // simulate long init in background
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                int max = 10;
                for (int i = 1; i <= max; i++) {
                    Thread.sleep(200);
                    updateProgress(i, max);
                }

                return null;
            }
        };
        return task ;
    }

    // just here so I can run directly from Eclipse:
    public static void main(String args[]) {
        launch(args);
    }
}


问:
C# disable listbox from parent form
I have an mdi child form as a dockable content in my application and I want to disable/enable a listbox in it from the parent form depending on a certain event. I thought this would be simple as:

```<code>_child.listBox1.Enabled = false;
</code>```

But it doesn't seem to disable it. _child is an object reference of the mdi child form btw. Why does it not work and how can I fix this?

答:
Can't you create a function on your MDI child which would disable the listbox, you could call from the MDI parent?

I guess that here listBox1 is private (which is the default if you have constructed your form using VS designer)

Title: C# disable listbox from parent form

Body:
I have an mdi child form as a dockable content in my application and I want to disable/enable a listbox in it from the parent form depending on a certain event. I thought this would be simple as:

_child.listBox1.Enabled = false;

But it doesn't seem to disable it. _child is an object reference of the mdi child form btw. Why does it not work and how can I fix this?


问:
webRTC convert webm to mp4 with ffmpeg.js
I am trying to convert webM files to mp4 with ffmpeg.js.
I am recording a video from canvas(overlayer with some information) and recording the audio data from the video.

```<code>stream = new MediaStream();
var videoElem = document.getElementById('video');
var videoStream = videoElem.captureStream();
stream.addTrack(videoStream.getAudioTracks()[0]);
stream.addTrack(canvas.captureStream().getVideoTracks()[0]);
var options = {mimeType: 'video/webm'};
  recordedBlobs = [];
  mediaRecorder = new MediaRecorder(stream, options);
  mediaRecorder.onstop = handleStop;
  mediaRecorder.ondataavailable = handleDataAvailable;
  mediaRecorder.start(100); // collect 100ms of data

function handleDataAvailable(event) {
  if (event.data && event.data.size > 0) {
    recordedBlobs.push(event.data);
  }
}
mediaRecorder.stop();
</code>```

This code works as expected and returns a webm video

```<code>var blob = new Blob(recordedBlobs, {type: 'video/webm'});
</code>```

Now I want a mp4 file and checked the ffmpeg.js from muaz-khan.
The examples just show how to convert to mp4 when you have 2 single streams (audio and video). But I have one stream with an additional audio track. Can I convert such a stream to mp4? How can that be done?

答:
As per the provided code sample, your recorder stream is having only one audio & one video tracks.

If your input file is having both Audio & Video, then you need to specify output codec for both tracks here as following.

```<code>worker.postMessage({
    type: 'command',
    arguments: [
       '-i', 'audiovideo.webm',
       '-c:v', 'mpeg4',
       '-c:a', 'aac', // or vorbis
       '-b:v', '6400k',  // video bitrate
       '-b:a', '4800k',  // audio bitrate
       '-strict', 'experimental', 'audiovideo.mp4'
     ],
    files: [
        {
            data: new Uint8Array(fileReaderData),
            name: 'audiovideo.webm'
        }
     ]
    });
</code>```

Trans-coding the video inside browser is not recommend, as it will consume more CPU Time & Memory. And ffmpeg_asm.js is heavy. May be ok for POC :)

What is your use case? webm(vp8/vp9) is widely using these days.

Chrome will support following mime types:

```<code>"video/webm"
"video/webm;codecs=vp8"
"video/webm;codecs=vp9"
"video/webm;codecs=h264"
"video/x-matroska;codecs=avc1"
</code>```

So you can get mp4 recording directly from chrome MediaRecorder with following hack

```<code>var options = {mimeType: 'video/webm;codecs=h264'};
mediaRecorder = new MediaRecorder(stream, options);
.....
//Before merging blobs change output mime
var blob = new Blob(recordedBlobs, {type: 'video/mp4'});
// And name your file as video.mp4
</code>```

Body:
I am trying to convert webM files to mp4 with ffmpeg.js.
I am recording a video from canvas(overlayer with some information) and recording the audio data from the video.

stream = new MediaStream();
var videoElem = document.getElementById('video');
var videoStream = videoElem.captureStream();
stream.addTrack(videoStream.getAudioTracks()[0]);
stream.addTrack(canvas.captureStream().getVideoTracks()[0]);
var options = {mimeType: 'video/webm'};
  recordedBlobs = [];
  mediaRecorder = new MediaRecorder(stream, options);
  mediaRecorder.onstop = handleStop;
  mediaRecorder.ondataavailable = handleDataAvailable;
  mediaRecorder.start(100); // collect 100ms of data

function handleDataAvailable(event) {
  if (event.data && event.data.size > 0) {
    recordedBlobs.push(event.data);
  }
}
mediaRecorder.stop();

This code works as expected and returns a webm video

var blob = new Blob(recordedBlobs, {type: 'video/webm'});

Now I want a mp4 file and checked the ffmpeg.js from muaz-khan.
The examples just show how to convert to mp4 when you have 2 single streams (audio and video). But I have one stream with an additional audio track. Can I convert such a stream to mp4? How can that be done?

Body:
As per the provided code sample, your recorder stream is having only one audio & one video tracks.

If your input file is having both Audio & Video, then you need to specify output codec for both tracks here as following.

worker.postMessage({
    type: 'command',
    arguments: [
       '-i', 'audiovideo.webm',
       '-c:v', 'mpeg4',
       '-c:a', 'aac', // or vorbis
       '-b:v', '6400k',  // video bitrate
       '-b:a', '4800k',  // audio bitrate
       '-strict', 'experimental', 'audiovideo.mp4'
     ],
    files: [
        {
            data: new Uint8Array(fileReaderData),
            name: 'audiovideo.webm'
        }
     ]
    });

Trans-coding the video inside browser is not recommend, as it will consume more CPU Time & Memory. And ffmpeg_asm.js is heavy. May be ok for POC :)

What is your use case? webm(vp8/vp9) is widely using these days.

Chrome will support following mime types:

"video/webm"
"video/webm;codecs=vp8"
"video/webm;codecs=vp9"
"video/webm;codecs=h264"
"video/x-matroska;codecs=avc1"

So you can get mp4 recording directly from chrome MediaRecorder with following hack

var options = {mimeType: 'video/webm;codecs=h264'};
mediaRecorder = new MediaRecorder(stream, options);
.....
//Before merging blobs change output mime
var blob = new Blob(recordedBlobs, {type: 'video/mp4'});
// And name your file as video.mp4


问:
How to change the redirect url when logging out?
I'm working with Laravel 5 authentification system provided by default.
After logging out, a user is redirected to the root page but I'd like to change that.
I managed to do it for the "login" and "registering" process by defining "$redirectTo" in "AuthController.php". But for "logout", I defined "$redirectAfterLogout" at the same place but it seems to not be taken into account.

Could anyone explain me where is the problem and how to fix it please?
Thanks a lot.

答:
I have a same problem in Laravel 5.0. Override a method does the trick.

1) Go to app/Http/Controllers/Auth/AuthController.php
2) Add a new method :

```<code>// Override Logout method (define custom url)
public function getLogout()
{
    $this->auth->logout();
    return redirect('auth/login');  // Your Custom URL
}
</code>```

Body:
I have a same problem in Laravel 5.0. Override a method does the trick.

1) Go to app/Http/Controllers/Auth/AuthController.php
2) Add a new method :

// Override Logout method (define custom url)
public function getLogout()
{
    $this->auth->logout();
    return redirect('auth/login');  // Your Custom URL
}


问:
awk concatenate based on column value
I'm trying to concatenate strings in column 2 based on shared value in column 1.
my file is like this:

2,John Doe
2,Roger Sterling
2,Blake Chaser
3,Rocky Horror
3,Jason Biggs
3,Bill Shakespeare```
</div>
</div>
</p>

<p>and I need this:</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-html lang-html prettyprint-override"><code>2,John Doe, Roger Sterling, Blake Chaser
3,Rocky Horror, Jason Biggs, Bill Shakespeare</code>```

I've tried a number of awk commands but I can't get it. Any help is appreciated

答:
try: following will provide you output in same order of $1 in your Input_file.

```<code>awk -F, '!($1 in a){++i} {a[$1]=a[$1]?a[$1] OFS $NF:$1 OFS $NF;}{b[i]=a[$1]} END{;for(j=1;j<=i;j++){print b[j]}}' OFS=,   Input_file
</code>```

EDIT1: Adding a non-one liner form of solution too here with a line by line detailed explanation too. I hope this helps you.

```<code>awk -F, '!($1 in a){                            ####checking here if $1 is not present in array a. If not then go to following block to execute statements.
        ++i                                     ####increment value of variable named i with 1 each time cursor comes into this block.
                   }
                   {
        a[$1]=a[$1]?a[$1] OFS $NF:$1 OFS $NF;   ####putting array a value and concatenating its value if that is already present using ? and : operators.
                   }
                   {
        b[i]=a[$1]                              ####creating an array b whose index is value of variable i and whose value is array a with current lines $1.
                   }
        END        {;
        for(j=1;j<=i;j++){                      ####starting a for loop now whose value will go till the value of variable i from 1.
        print b[j]                              ####printing the value of array b whose index is variable j.
                         }
                   }
        ' OFS=,  file117                        ####mentioning the value of output field separator as , and mentioning the Input_file name too here.
</code>```

Title: awk concatenate based on column value

Body:
I'm trying to concatenate strings in column 2 based on shared value in column 1.
my file is like this:

2,John Doe
2,Roger Sterling
2,Blake Chaser
3,Rocky Horror
3,Jason Biggs
3,Bill Shakespeare

and I need this:

2,John Doe, Roger Sterling, Blake Chaser
3,Rocky Horror, Jason Biggs, Bill Shakespeare

I've tried a number of awk commands but I can't get it. Any help is appreciated

Body:
try: following will provide you output in same order of $1 in your Input_file.

awk -F, '!($1 in a){++i} {a[$1]=a[$1]?a[$1] OFS $NF:$1 OFS $NF;}{b[i]=a[$1]} END{;for(j=1;j<=i;j++){print b[j]}}' OFS=,   Input_file

EDIT1: Adding a non-one liner form of solution too here with a line by line detailed explanation too. I hope this helps you.

awk -F, '!($1 in a){                            ####checking here if $1 is not present in array a. If not then go to following block to execute statements.
        ++i                                     ####increment value of variable named i with 1 each time cursor comes into this block.
                   }
                   {
        a[$1]=a[$1]?a[$1] OFS $NF:$1 OFS $NF;   ####putting array a value and concatenating its value if that is already present using ? and : operators.
                   }
                   {
        b[i]=a[$1]                              ####creating an array b whose index is value of variable i and whose value is array a with current lines $1.
                   }
        END        {;
        for(j=1;j<=i;j++){                      ####starting a for loop now whose value will go till the value of variable i from 1.
        print b[j]                              ####printing the value of array b whose index is variable j.
                         }
                   }
        ' OFS=,  file117                        ####mentioning the value of output field separator as , and mentioning the Input_file name too here.


问:
For how long does a blob persist in azure storage account?
I have created a storage account in azure portal, and a streamanalytics job that sends query results to a blob in that storage account.

I wish to know - for how long will that data be kept in that blob?
Is there a default period of time when the blob will be deleted automatically?
Is there a way for me to configure when to delete the blob content in my account?

答: It stays the as long as the subscription is paid for. There is a populair vote to create some kind of retention policy but AFAIK it is not available yet. So you will have to write your own logic if you need to have it deleted after a certain period.</p>


问:
pseudo selector for uppercase chars/words?
Is there a CSS pseudoselector for uppercase characters/letters/words? I want all my capitals to be a pt smaller and all the other characters the same size. A capital is not neccesarily the first character of a sentence (or word) nor the other way around.

Or maybe there's another way to find these characters in CSS? With a trick? I like tricks.

答:
I do not think this is possible.

Better to just wrap the capital letters with a span with a class and use that to style them.


问:
z-index not working between image and text box
JSFiddle

I have an image with a text box below. I scaled the image, and it goes over the text box, i wan't the text box to be on top of the image, but it is not working with z-index.

HTML:

```<code><a href="#">
  <img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" />
  <div class="text">
    This is some text.
  </div>
</a>
</code>```

CSS:

```<code>a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
}
</code>```

答:
I thought this is what you were after:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.container {
  width: 400px;
  height: 400px;
}

.container img {
  position: absolute;
  top: 0;
  left: 0;
}

.container div {
  color: white;
  background-color: rgba(0, 0, 0, 0.6);
  position: absolute;
  opacity: 0;
  transition: all .5s ease;
  width: inherit;
  height: inherit;
  text-align: center;
}

.container:hover div {
  opacity: 1;
}
.container div span {
  font-size: 30px;
  line-height: 30px;
  position: relative;
  top: calc(50% - 15px);
  transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="http://placehold.it/400" />
  <div>
    <span>Image text</span>
  </div>
</div></code>```

Body:
JSFiddle

I have an image with a text box below. I scaled the image, and it goes over the text box, i wan't the text box to be on top of the image, but it is not working with z-index.

HTML:

    This is some text.

CSS:

a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
}

Body:
I thought this is what you were after:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.container {
  width: 400px;
  height: 400px;
}

.container img {
  position: absolute;
  top: 0;
  left: 0;
}

.container div {
  color: white;
  background-color: rgba(0, 0, 0, 0.6);
  position: absolute;
  opacity: 0;
  transition: all .5s ease;
  width: inherit;
  height: inherit;
  text-align: center;
}

.container:hover div {
  opacity: 1;
}
.container div span {
  font-size: 30px;
  line-height: 30px;
  position: relative;
  top: calc(50% - 15px);
  transform: translateY(-50%);
}

<div class="container">
  <img src="http://placehold.it/400" />
  <div>
    <span>Image text</span>
  </div>
</div>


问:
How to convert UTC date to local date object?
I dont know why, but I have tried all the solutions available around the internet but still couldnt succeed. Event MomentJs couldnt help.
So, I have a date string, "2017-06-05T15:00:00Z", it is coming from rest api.
I even tried with moment js but doenst help.
Note I want date object to be returned as the library expects date object not local string.
So, far I tried:

```<code>var d = new Date('2017-06-05T15:00:00Z')
console.log(d.getHours())
</code>```

The above code prints 17 rather than 15! So, what is it I am doing wrong? As the library also while doing its own thing gets 1700 hours as in calendar it shows 1700 hrs rather than 1500 hrs.

答:
You should be able to use the getTimezoneOffsetMethod

```<code>var d = new Date('2017-06-05T15:00:00Z')
d.setHours(d.getHours() + (d.getTimezoneOffset() / 60))
console.log(d.getHours()) // 15
</code>```

Body:
I dont know why, but I have tried all the solutions available around the internet but still couldnt succeed. Event MomentJs couldnt help.
So, I have a date string, "2017-06-05T15:00:00Z", it is coming from rest api.
I even tried with moment js but doenst help.
Note I want date object to be returned as the library expects date object not local string.
So, far I tried:

var d = new Date('2017-06-05T15:00:00Z')
console.log(d.getHours())

The above code prints 17 rather than 15! So, what is it I am doing wrong? As the library also while doing its own thing gets 1700 hours as in calendar it shows 1700 hrs rather than 1500 hrs.

Body:
You should be able to use the getTimezoneOffsetMethod

var d = new Date('2017-06-05T15:00:00Z')
d.setHours(d.getHours() + (d.getTimezoneOffset() / 60))
console.log(d.getHours()) // 15