问:
Setting readonly using ng-readonly dynamically is not working
I am fetching some data from the database server and displaying the same in tabular format on my GUI. I want to achieve the following in my GUI design

(a) Any cell in the table should be editable except the first column in the table.
(b) The first row of the table, if added newly to the GUI for accepting new inputs from the user, should be exempted from the above rule i.e., all columns of the first row should be editable.

To achieve this I wrote the following code.

HTML Code

```<code>    <tbody>
           <tr ng-repeat="x in sensordata">
           <td>
             <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="namereadonly" ng-init="ctrl2.setReadOnly(x.name,$index)"/>
           </td>
           <td>
              <input class="form-control" type="text" ng-model="x.unit" placeholder="Measurement Unit" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.type" placeholder="Sensor Type" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.periodicity" placeholder="Periodicity" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.formula" placeholder="Formula" required/>
           </td>
           <td>
               <input class="form-control" type="email" ng-model="x.vendor" placeholder="Email Id" required/>
           </td>
           </tr>
   </tbody>
</code>```

Controller code is as follows.

```<code>this.setReadOnly = function(name,idx) {
        console.log('name ' + name + ' idx ' + idx);
        if (name === undefined || name === null || name === '') $scope.namereadonly = false;
        if (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
    };
</code>```

When I am executing above code the first column of all the rows are getting uneditable as expected. But when I am adding new row to the (by adding new empty JSON object in the sensordata array in another function of the same controller) GUI, the first column of the row is getting uneditable which should not be the case as per the first if statement in the above method. I am unable to figure out why it is happening.

答:
<input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-model-options="{ updateOn: 'blur' }" ng-readonly="x.name.length"/> this line solved my problem. Without ng-model-options attribute as soon as one types a character in the newly added row the first column is becoming uneditable. With ng-model-options this issue is resolved as now the column would become uneditable upon moving focus from the input field.

No method is to be written in the controller.

Body:
I am fetching some data from the database server and displaying the same in tabular format on my GUI. I want to achieve the following in my GUI design

(a) Any cell in the table should be editable except the first column in the table.
(b) The first row of the table, if added newly to the GUI for accepting new inputs from the user, should be exempted from the above rule i.e., all columns of the first row should be editable.

To achieve this I wrote the following code.

HTML Code

             <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="namereadonly" ng-init="ctrl2.setReadOnly(x.name,$index)"/>

              <input class="form-control" type="text" ng-model="x.unit" placeholder="Measurement Unit" required/>

                <input class="form-control" type="text" ng-model="x.type" placeholder="Sensor Type" required/>

                <input class="form-control" type="text" ng-model="x.periodicity" placeholder="Periodicity" required/>

                <input class="form-control" type="text" ng-model="x.formula" placeholder="Formula" required/>

               <input class="form-control" type="email" ng-model="x.vendor" placeholder="Email Id" required/>

Controller code is as follows.

this.setReadOnly = function(name,idx) {
        console.log('name ' + name + ' idx ' + idx);
        if (name === undefined || name === null || name === '') $scope.namereadonly = false;
        if (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
    };

When I am executing above code the first column of all the rows are getting uneditable as expected. But when I am adding new row to the (by adding new empty JSON object in the sensordata array in another function of the same controller) GUI, the first column of the row is getting uneditable which should not be the case as per the first if statement in the above method. I am unable to figure out why it is happening.


来源: stackexchange

问:
Unable to upload Angular2 application gh-pages
I am getting this

I have a website live on my another host and its working perfectly fine. But i will like to upload on github pages too. For testing and other reasons. But when i uploaded my angular2 webapp, I got the above error. Do we have to any special setting to do for pages?

Index.html

```<code><html>
  <head>
    <title>Smit Shah</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="Smit Shah">
      <link rel="icon" href="app/img/smitico.ico">
    <link rel="stylesheet" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Gruppo" rel="stylesheet">
    <!-- 1. Load libraries -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
 <body class="indexStyle">
    <my-app></my-app>
  </body>
</html>
</code>```

systemjs.config.js

```<code>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);
</code>```

Package.json

```<code>{
  "name": "smit-web",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "lite": "lite-server",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/common": "~2.4.1",
    "@angular/compiler": "~2.4.1",
    "@angular/core": "~2.4.1",
    "@angular/forms": "~2.4.1",
    "@angular/http": "~2.4.1",
    "@angular/platform-browser": "~2.4.1",
    "@angular/platform-browser-dynamic": "~2.4.1",
    "@angular/router": "~3.4.1",
    "@angular/upgrade": "~2.4.1",
    "angular-in-memory-web-api": "~0.2.2",
    "angular2-bootstrap-confirm": "^1.0.4",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "systemjs": "0.19.41",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.34",
    "@types/node": "^6.0.45",
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.3"
  }
}
</code>```

I have tried providing more information. If there anything else let me know. Thanks.

And here it the github pages url.

答:
I deployed my agular2 example app to github gh-pages
Here try to follow these steps.

Delete your gh-pages branch on git.

```<code> git branch -D gh-pages
</code>```

Install this angular-cli dependency to your project

```<code> npm install --save   @angular/cli
</code>```

Build your project for deploy

```<code> ng build --prod--aot --base-href "https://<username>.github.io/<repo-name>/"
</code>```

If you have problem when compiling replace this code in app.module.ts file

```<code> "environments": {
     "source": "environments/environment.ts",
     "dev": "environments/environment.ts",
     "prod": "environments/environment.prod.ts"
   }
</code>```

To

```<code> "environmentSource": "environments/environment.ts",
           "environments": {
                   "dev": "environments/environment.ts",
                   "prod": "environments/environment.prod.ts"
            }
</code>```

After successful compiled(100%) just run this command to deploy to gh-pahes

```<code>      ngh --message "Deploy gh pages"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting this

I have a website live on my another host and its working perfectly fine. But i will like to upload on github pages too. For testing and other reasons. But when i uploaded my angular2 webapp, I got the above error. Do we have to any special setting to do for pages?

Index.html

    <title>Smit Shah</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="Smit Shah">
      <link rel="icon" href="app/img/smitico.ico">
    <link rel="stylesheet" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Gruppo" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

    <my-app></my-app>

systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

Package.json

{
  "name": "smit-web",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "lite": "lite-server",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/common": "~2.4.1",
    "@angular/compiler": "~2.4.1",
    "@angular/core": "~2.4.1",
    "@angular/forms": "~2.4.1",
    "@angular/http": "~2.4.1",
    "@angular/platform-browser": "~2.4.1",
    "@angular/platform-browser-dynamic": "~2.4.1",
    "@angular/router": "~3.4.1",
    "@angular/upgrade": "~2.4.1",
    "angular-in-memory-web-api": "~0.2.2",
    "angular2-bootstrap-confirm": "^1.0.4",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "systemjs": "0.19.41",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.34",
    "@types/node": "^6.0.45",
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.3"
  }
}

I have tried providing more information. If there anything else let me know. Thanks.

And here it the github pages url.

Body:
I deployed my agular2 example app to github gh-pages
Here try to follow these steps.

Delete your gh-pages branch on git.

 git branch -D gh-pages

Install this angular-cli dependency to your project

 npm install --save   @angular/cli

Build your project for deploy

 ng build --prod--aot --base-href "https://<username>.github.io/<repo-name>/"

If you have problem when compiling replace this code in app.module.ts file

 "environments": {
     "source": "environments/environment.ts",
     "dev": "environments/environment.ts",
     "prod": "environments/environment.prod.ts"
   }

To

 "environmentSource": "environments/environment.ts",
           "environments": {
                   "dev": "environments/environment.ts",
                   "prod": "environments/environment.prod.ts"
            }

After successful compiled(100%) just run this command to deploy to gh-pahes

      ngh --message "Deploy gh pages"


问:
how to disable main menu using javascript in sub pages?
I want to disable main menu item in sub page using it's id. Tried "setAttribute" and "disabled" options.

```<code>document.getElementById("bloc_menu:j_id14").setAttribute("disabled","disabled");
document.getElementById("bloc_menu:j_id14").disabled = true;
</code>```

Any suggestions are welcome, thank u.

答:
I'm still not 100% sure what you're trying to do or why you can't handle this serverside, but I've made a little example of a simple menu that can be disabled/enabled.

var $mainMenu, $links;

$(function() {
  $mainMenu = $('#main-menu');
  $links = $mainMenu.find('.menu-item__link').each(function() {
    var $link = $(this);
    $link.data('href', $link.attr('href'));
  });
  $('#toggle-main-menu').on('click', function() {
    toggleMainMenu();
  });
});

function toggleMainMenu() {
  if ($mainMenu.hasClass('disabled')) {
    $mainMenu.removeClass('disabled');
    restoreLinks();
  }
  else {
    $mainMenu.addClass('disabled');
    removeLinks();
  }
}

function removeLinks() {
  $links.removeAttr('href');
}

function restoreLinks() {
  $links.each(function() {
    var $link = $(this);
    $link.attr('href', $link.data('href'));
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main-menu .menu-item__link {
  color: #000;
}

#main-menu.disabled .menu-item__link {
  color: #ccc;
}</code>```

    Some link 1

    Some link 2

    Some link 3

<button id="toggle-main-menu">Toggle the menu</button>```

Body:
I want to disable main menu item in sub page using it's id. Tried "setAttribute" and "disabled" options.

document.getElementById("bloc_menu:j_id14").setAttribute("disabled","disabled");
document.getElementById("bloc_menu:j_id14").disabled = true;

Any suggestions are welcome, thank u.

Body:
I'm still not 100% sure what you're trying to do or why you can't handle this serverside, but I've made a little example of a simple menu that can be disabled/enabled.

var $mainMenu, $links;

$(function() {
  $mainMenu = $('#main-menu');
  $links = $mainMenu.find('.menu-item__link').each(function() {
    var $link = $(this);
    $link.data('href', $link.attr('href'));
  });
  $('#toggle-main-menu').on('click', function() {
    toggleMainMenu();
  });
});

function toggleMainMenu() {
  if ($mainMenu.hasClass('disabled')) {
    $mainMenu.removeClass('disabled');
    restoreLinks();
  }
  else {
    $mainMenu.addClass('disabled');
    removeLinks();
  }
}

function removeLinks() {
  $links.removeAttr('href');
}

function restoreLinks() {
  $links.each(function() {
    var $link = $(this);
    $link.attr('href', $link.data('href'));
  });
}

#main-menu .menu-item__link {
  color: #000;
}

#main-menu.disabled .menu-item__link {
  color: #ccc;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="main-menu">
  <li class="menu-item">
    <a class="menu-item__link" href="#someLink1">Some link 1</a>
  </li>
  <li class="menu-item">
    <a class="menu-item__link" href="#someLink2">Some link 2</a>
  </li>
  <li class="menu-item">
    <a class="menu-item__link" href="#someLink3">Some link 3</a>
  </li>
</ul>
<button id="toggle-main-menu">Toggle the menu</button>


问:
How to write teamplate for handler
Handler not processing select with name="ordertype". I try write normal code, where is my mistakes? Help me please, thank you for spending your time!

https://pastebin.com/mbmiapg2 (rd-mailform.tpl)

https://pastebin.com/mL1HdhhS (rd-mailform.php)

```<code> <!-- RD Mailform-->
              <form data-form-output="form-output-global" data-form-type="contact" method="post" action="bat/rd-mailform.php" class="rd-mailform text-left">
                <div class="form-group"><span class="icon material-icons-person"></span>
                  <label for="contact-name" class="form-label">Full name</label>
                  <input id="contact-name" type="text" name="name" data-constraints="@Required" class="form-control">
                </div>
                <div class="form-group"><span class="icon material-icons-markunread"></span>
                  <label for="contact-email" class="form-label">Email</label>
                  <input id="contact-email" type="email" name="email" data-constraints="@Email @Required" class="form-control">
                </div>
                <div class="form-group"><span class="icon material-icons-phone"></span>
                  <label for="contact-phone" class="form-label">Phone</label>
                  <input id="contact-phone" type="text" name="message" data-constraints="@Numeric @Required" class="form-control">
                </div>
                <div class="form-group"><span class="icon material-icons-add"></span>
                  <!--Select 2-->
                  <select data-placeholder="Тип заявки" name="ordertype" data-minimum-results-for-search="Infinity" data-constraints="@Required" class="form-control select-filter">
                    <option value="">empty</option>
                    <option value="2">Консультация</option>
                    <option value="3">Заказ</option>
                  </select>
                </div>
                <button type="submit" class="btn btn-salem">Оставь заявку сейчас!</button>
              </form>
</code>```

答:
In your rd-mailform.php file, you've got an underscore in your variable name, so you're assigning the details to a new variable that isn't being used. You are also missing a # on your OrdertypeState tag.

You've got

```<code>$_template= str_replace(
        array("<!-- {OrdertypeState} -->", "<!-- #{FromOrdertype} -->"),
        array("Ordertype:", $_POST['ordertype']),
        $template);
</code>```

instead of

```<code>$template= str_replace(
        array("<!-- #{OrdertypeState} -->", "<!-- #{FromOrdertype} -->"),
        array("Ordertype:", $_POST['ordertype']),
        $template);
</code>```

Title: How to write teamplate for handler

Body:
Handler not processing select with name="ordertype". I try write normal code, where is my mistakes? Help me please, thank you for spending your time!

https://pastebin.com/mbmiapg2 (rd-mailform.tpl)

https://pastebin.com/mL1HdhhS (rd-mailform.php)

              <form data-form-output="form-output-global" data-form-type="contact" method="post" action="bat/rd-mailform.php" class="rd-mailform text-left">

                  Full name
                  <input id="contact-name" type="text" name="name" data-constraints="@Required" class="form-control">

                  Email
                  <input id="contact-email" type="email" name="email" data-constraints="@Email @Required" class="form-control">

                  Phone
                  <input id="contact-phone" type="text" name="message" data-constraints="@Numeric @Required" class="form-control">

                  <select data-placeholder="Тип заявки" name="ordertype" data-minimum-results-for-search="Infinity" data-constraints="@Required" class="form-control select-filter">
                    <option value="">empty</option>
                    <option value="2">Консультация</option>
                    <option value="3">Заказ</option>
                  </select>

                <button type="submit" class="btn btn-salem">Оставь заявку сейчас!</button>
              </form>

Body:
In your rd-mailform.php file, you've got an underscore in your variable name, so you're assigning the details to a new variable that isn't being used. You are also missing a # on your OrdertypeState tag.

You've got

$_template= str_replace(
        array("<!-- {OrdertypeState} -->", "<!-- #{FromOrdertype} -->"),
        array("Ordertype:", $_POST['ordertype']),
        $template);

instead of

$template= str_replace(
        array("<!-- #{OrdertypeState} -->", "<!-- #{FromOrdertype} -->"),
        array("Ordertype:", $_POST['ordertype']),
        $template);


问:
Nested loops output to dict in parallel
I have two set of data:

```<code>aDict = {'barcode1': [('barcode1', 184), ('barcode1_mut', 2)], 'barcode2': [('barcode2', 138)], 'barcode3': [('barcode3', 375)]}
bList = [(('barcode1', 'mut1'), 184), (('barcode1_mut', 'mut2'), 2), (('barcode2', 'mut3'), 136), (('barcode2', 'mut4'), 1), (('barcode2', 'mut5'), 1), (('barcode3', 'mut6'), 373), (('barcode3', 'mut7'), 2)]
</code>```

And i'm matching for every keys in dict aDict with barcode in list bList and result:

```<code>>>>print(result)
{'barcode1': {'barcode1': [('mut1', 184)], 'barcode1_mut': [('mut2', 2)]},
'barcode2': {'barcode2': [('mut3', 136), ('mut4', 1), ('mut5', 1)]},
'barcode3': {'barcode3': [('mut6', 373), ('mut7', 2)]}}
</code>```

But it's too slow for me. I tried paralleling the code with the output of information on the number of processed lines. But in my implementation, each line is processed simultaneously by all workers.

Now, my implementation looks like:

```<code>from collections import defaultdict
import multiprocessing as mp

def f(uniqueBarcode):
    mutBarcodeList = [x[0] for x in aDict[uniqueBarcode]]
    a = filter(lambda x: x[0][0] in mutBarcodeList, bList.items())
    d = defaultdict(tuple)
    b = [(x[0][0], (x[0][1], x[1])) for x in a]
    for tup in b: d[tup[0]] += (tup[1],)
    result = {i[0]:[y for y in i[1]] for i in d.items()}
    return result

seqDict={}

if __name__=='__main__':
    cpus = mp.cpu_count()
    pool = mp.Pool(cpus)
    for barcode in aDict.keys():
        seqDict[barcode] = pool.map(f, [barcode])
        if len(seqDict) % 100 == 0:
            print("Processed {} barcodes".format(len(seqDict)))
    pool.close()
    pool.join()
</code>```

Output:

```<code>Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
...
</code>```

And dict seqDict is empty, but it must not be so - the first line is processed by the first process, the second line is the second one ... the eighth is the eighth process, the ninth line is again the first process and etc.

How to do it in parallel correctly?

Upd0: I'm adapted Flomp's code to me

```<code>res={}
for key in aDict:
    if len(aDict[key]) == 1:
        res[key] = {key:[(a[1],b) for a,b in bList if a[0] == key]}
    elif len(aDict[key]) > 1:
        res[key] = {x[0]:[(a[1],b) for a,b in bList if a[0] == x[0]] for x in aDict[key]}
</code>```

But it work so long

答:
I see a lot of for-loops in your code. This slows down your program. Here is some code with a better runtime:

```<code>bcDict = {'TTCTCTTACCGGGTAC':1,'ACCTCTCGAGAATTCA':2,'TGCAGTTCTGTGCATC':3}

bcMutCount = [(('TTCTCTTACCGGGTAC', 'ATTCAACA'), 184),
(('ACCTCTCGAGAATTCA', 'CATCCCAC'), 136),
(('ACCTCTCGAGAATTCA', 'CATGCCAC'), 1),
(('ACCTCTCGAGAATTCA', 'CATCCCCC'), 1),
(('TGCAGTTCTGTGCATC', 'TCTACATT'), 373),
(('TGCAGTTCTGTGCATC', 'ACTGCGCA'), 2)]

for key in bcDict:
  print({key:[(a[1],b) for a,b in bcMutCount if a[0] == key]})
</code>```

Output:

```<code>{'TTCTCTTACCGGGTAC': [('ATTCAACA', 184)]}
{'ACCTCTCGAGAATTCA': [('CATCCCAC', 136), ('CATGCCAC', 1), ('CATCCCCC', 1)]}
{'TGCAGTTCTGTGCATC': [('TCTACATT', 373), ('ACTGCGCA', 2)]}
</code>```

Please correct me if this is not what you want. The code above should run in O(m*n) where m is the number of keys in bcDict and n is the length of bcMutCount.
Does this run sufficiently fast?

Title: Nested loops output to dict in parallel

Body:
I have two set of data:

aDict = {'barcode1': [('barcode1', 184), ('barcode1_mut', 2)], 'barcode2': [('barcode2', 138)], 'barcode3': [('barcode3', 375)]}
bList = [(('barcode1', 'mut1'), 184), (('barcode1_mut', 'mut2'), 2), (('barcode2', 'mut3'), 136), (('barcode2', 'mut4'), 1), (('barcode2', 'mut5'), 1), (('barcode3', 'mut6'), 373), (('barcode3', 'mut7'), 2)]

And i'm matching for every keys in dict aDict with barcode in list bList and result:

>>>print(result)
{'barcode1': {'barcode1': [('mut1', 184)], 'barcode1_mut': [('mut2', 2)]},
'barcode2': {'barcode2': [('mut3', 136), ('mut4', 1), ('mut5', 1)]},
'barcode3': {'barcode3': [('mut6', 373), ('mut7', 2)]}}

But it's too slow for me. I tried paralleling the code with the output of information on the number of processed lines. But in my implementation, each line is processed simultaneously by all workers.

Now, my implementation looks like:

from collections import defaultdict
import multiprocessing as mp

def f(uniqueBarcode):
    mutBarcodeList = [x[0] for x in aDict[uniqueBarcode]]
    a = filter(lambda x: x[0][0] in mutBarcodeList, bList.items())
    d = defaultdict(tuple)
    b = [(x[0][0], (x[0][1], x[1])) for x in a]
    for tup in b: d[tup[0]] += (tup[1],)
    result = {i[0]:[y for y in i[1]] for i in d.items()}
    return result

seqDict={}

if __name__=='__main__':
    cpus = mp.cpu_count()
    pool = mp.Pool(cpus)
    for barcode in aDict.keys():
        seqDict[barcode] = pool.map(f, [barcode])
        if len(seqDict) % 100 == 0:
            print("Processed {} barcodes".format(len(seqDict)))
    pool.close()
    pool.join()

Output:

Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 100 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
Processed 200 barcodes
...

And dict seqDict is empty, but it must not be so - the first line is processed by the first process, the second line is the second one ... the eighth is the eighth process, the ninth line is again the first process and etc.

How to do it in parallel correctly?

Upd0: I'm adapted Flomp's code to me

res={}
for key in aDict:
    if len(aDict[key]) == 1:
        res[key] = {key:[(a[1],b) for a,b in bList if a[0] == key]}
    elif len(aDict[key]) > 1:
        res[key] = {x[0]:[(a[1],b) for a,b in bList if a[0] == x[0]] for x in aDict[key]}

But it work so long

Body:
I see a lot of for-loops in your code. This slows down your program. Here is some code with a better runtime:

bcDict = {'TTCTCTTACCGGGTAC':1,'ACCTCTCGAGAATTCA':2,'TGCAGTTCTGTGCATC':3}

bcMutCount = [(('TTCTCTTACCGGGTAC', 'ATTCAACA'), 184),
(('ACCTCTCGAGAATTCA', 'CATCCCAC'), 136),
(('ACCTCTCGAGAATTCA', 'CATGCCAC'), 1),
(('ACCTCTCGAGAATTCA', 'CATCCCCC'), 1),
(('TGCAGTTCTGTGCATC', 'TCTACATT'), 373),
(('TGCAGTTCTGTGCATC', 'ACTGCGCA'), 2)]

for key in bcDict:
  print({key:[(a[1],b) for a,b in bcMutCount if a[0] == key]})

Output:

{'TTCTCTTACCGGGTAC': [('ATTCAACA', 184)]}
{'ACCTCTCGAGAATTCA': [('CATCCCAC', 136), ('CATGCCAC', 1), ('CATCCCCC', 1)]}
{'TGCAGTTCTGTGCATC': [('TCTACATT', 373), ('ACTGCGCA', 2)]}

Please correct me if this is not what you want. The code above should run in O(m*n) where m is the number of keys in bcDict and n is the length of bcMutCount.
Does this run sufficiently fast?


问:
QTableView, how to change dragging multiple items display
I have a QTableView with my own implemented QAbstractItemModel, in which I can drag and drop multiple items inside. My problem is that when dragging the items and while trying to drop them in a destination cell, it is not so obvious for the user what the result is going to be. For example, I have the following,but I would prefer sth like the default widows displaying, which makes all 3 items like one item:

my QT Table

vs

windows dragging n dropping folders

答:
After eyllanesc's suggestion for QPixmap, I found the correct solution to my problem, so that I can keep the mime data coming from my model. I have re-implemented startDrag(Qt::DropActions supportedActions) in my QTreeView class, so that when multiple objects are moved, one icon will be displayed along with the number of items moved. Now looks like this:</p>

```<code>void MyTreeView::startDrag(Qt::DropActions supportedActions)
{
    QModelIndexList indexes = selectedIndexes();
    if (indexes.size() == 1)
        return QAbstractItemView::startDrag(supportedActions);
    if (indexes.count() > 0)
    {
        QMimeData *data = model()->mimeData(indexes);
        if (!data)
           return;
        QRect rect;
        rect.adjust(horizontalOffset(), verticalOffset(), 0, 0);
        QDrag *drag = new QDrag(this);

        ActionTreeItem* pItem = static_cast<ActionTreeItem*>(indexes[0].internalPointer());
        if (pItem != NULL)
        {
            QPixmap pixmap = myIcon.pixmap(myIcon.actualSize(QSize(32, 32)));
            QPainter *paint = new QPainter(&pixmap);
            paint->setPen(Qt::black);
            paint->setBrush(QBrush(Qt::white));
            QRect numberRect(18, 18, 13, 13);
            paint->drawRect(numberRect);
            paint->drawText(numberRect, Qt::AlignHCenter | Qt::AlignVCenter, QString("%1").arg(indexes.count()));
           drag->setPixmap(pixmap);
        }
       drag->setMimeData(data);
       Qt::DropAction defaultDropAction = Qt::MoveAction;
       drag->exec(supportedActions, defaultDropAction);
    }
  }
</code>```

Body:
After eyllanesc's suggestion for QPixmap, I found the correct solution to my problem, so that I can keep the mime data coming from my model. I have re-implemented startDrag(Qt::DropActions supportedActions) in my QTreeView class, so that when multiple objects are moved, one icon will be displayed along with the number of items moved. Now looks like this:

void MyTreeView::startDrag(Qt::DropActions supportedActions)
{
    QModelIndexList indexes = selectedIndexes();
    if (indexes.size() == 1)
        return QAbstractItemView::startDrag(supportedActions);
    if (indexes.count() > 0)
    {
        QMimeData *data = model()->mimeData(indexes);
        if (!data)
           return;
        QRect rect;
        rect.adjust(horizontalOffset(), verticalOffset(), 0, 0);
        QDrag *drag = new QDrag(this);

        ActionTreeItem* pItem = static_cast<ActionTreeItem*>(indexes[0].internalPointer());
        if (pItem != NULL)
        {
            QPixmap pixmap = myIcon.pixmap(myIcon.actualSize(QSize(32, 32)));
            QPainter *paint = new QPainter(&pixmap);
            paint->setPen(Qt::black);
            paint->setBrush(QBrush(Qt::white));
            QRect numberRect(18, 18, 13, 13);
            paint->drawRect(numberRect);
            paint->drawText(numberRect, Qt::AlignHCenter | Qt::AlignVCenter, QString("%1").arg(indexes.count()));
           drag->setPixmap(pixmap);
        }
       drag->setMimeData(data);
       Qt::DropAction defaultDropAction = Qt::MoveAction;
       drag->exec(supportedActions, defaultDropAction);
    }
  }


问:
How to use *ngIf for async http.get data request - Angular 2
I have a web application that is retrieving data from multiple api and is supposed to use the data into some charts. The problem is that when the charts get rendered the data from the api are not in yet. I tried using .then() method but it tells me that property then does not exist on type void. Furthermore I tried using the ngIf method, following this answer, but is not working either. Do you know how could I solve this please?

Below are my component and my component template.

app.component.ts

```<code>import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mimesi dashboard graphs';

  //COUNTS
  public countIndexerMetaApi; //array of one number populated from http.get
  public countIndexerMetaNumber; //number extracted into array and stored as an int
  public countIndexerMetaArray; //array to store countNumber afterwards

  public countIndexerServedApi;
  public countIndexerServedNumber;
  public countIndexerServedArray;

  public countRealTimeServedApi;
  public countRealTimeServedNumber;
  public countRealTimeServedArray;

  //DATES
  public dateIndexerMetaToStore; //date got from moment method that needs to be stored
  public dateIndexerMetaArray; //array to store dates for graph label

  public dateIndexerServedToStore;
  public dateIndexerServedArray;

  public dateRealTimeServedToStore;
  public dateRealTimeServedArray;

  //API LINKS
  private apiCountIndexerMetaUrl: string = 'http://localhost:3000/api/countIndexerMetaApi';
  /*      TODO - API FOR COUNT OF OTHER TWO TABLES      */
  private apiCountIndexerServedUrl: string = 'http://localhost:3000/api/countIndexerServedApi';
  private apiCountRealTimeServedUrl: string = 'http://localhost:3000/api/countRealTimeServedApi';

  //VARIABLE FOR TIMEOUT
  public isDataAvailable:boolean = false;

  constructor(private http:Http) {
    let now = moment.locale("it");

    //COUNT
    this.countIndexerMetaApi = 0;
    this.countIndexerMetaNumber = 0;
    this.countIndexerMetaArray = [];

    this.countIndexerServedApi = 0;
    this.countIndexerServedNumber = 0;
    this.countIndexerServedArray = []

    this.countRealTimeServedApi = 0;
    this.countRealTimeServedNumber = 0;
    this.countRealTimeServedArray = []

    //DATES
    this.dateIndexerMetaToStore = "";
    this.dateIndexerMetaArray = [];

    this.dateIndexerServedToStore = "";
    this.dateIndexerServedArray = [];

    this.dateRealTimeServedToStore = "";
    this.dateRealTimeServedArray = [];
  }

  ngOnInit() {
    this.getIndexerMetaCount();
    this.getIndexerServedCount();
    this.getRealTimeServedCount();
  }

  //COUNT
  getIndexerMetaCount(){
    this.http.get(this.apiCountIndexerMetaUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerMetaApi = data.map(countIndexerMetaApiObj => countIndexerMetaApiObj.countIndexerMetaApi))
            },
        );
    //this.countIndexerMetaNumber = this.countIndexerMetaApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerMetaArray.push(this.countIndexerMetaNumber); // problem follows through
  }
  printCountIndexerMetaArray(){
    this.countIndexerMetaApi.forEach(element => {
      console.log(element);
    });
  }

  getIndexerServedCount(){
    this.http.get(this.apiCountIndexerServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerServedApi = data.map(countObj => countObj.countIndexerServedApi))
            },
        );
    //this.countIndexerServedNumber = this.countIndexerServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerServedArray.push(this.countIndexerServedNumber); // problem follows through
  }
  printCountIndexerServedArray(){
    this.countIndexerServedApi.forEach(element => {
      console.log(element);
    });
  }

  getRealTimeServedCount(){
    this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countRealTimeServedApi = data.map(countObj => countObj.countRealTimeServedApi))
            },
        );
    //this.countRealTimeServedNumber = this.countRealTimeServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countRealTimeServedArray.push(this.countRealTimeServedNumber); // problem follows through
  }
  printRealTimeServedArray(){
    this.countRealTimeServedApi.forEach(element => {
      console.log(element);
    });
  }

  //DATES
  dateIndexerMeta() {
    this.dateIndexerMetaToStore = moment().add(-122, 'days');
    this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
  }

  dateIndexerServed() {
    this.dateIndexerServedToStore = moment().add(-122, 'days');
    this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
  }

  dateRealTimeServed() {
    this.dateRealTimeServedToStore = moment().add(-122, 'days');
    this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
  }

  //TIMEOUT TRIAL
  timeoutTrial(){
    console.log(this.isDataAvailable);
    setTimeout(function() {this.isDataAvailable = true;
      console.log(this.isDataAvailable);
    }, 5000); //<-- timeout works but other functions don't refresh even if isDataAvailable changed
  }

  /*      CHARTS      */

  //DATA
  public lineChartData:Array<any> = [
    {data: this.countIndexerMetaArray, label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: this.countIndexerServedArray, label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: this.countRealTimeServedArray, label: 'Real-Time served links'},
  ];

  //LABELS
  public lineChartLabels:Array<any> = this.dateIndexerMetaArray;

  public lineChartLabels1:Array<any> = this.dateIndexerServedArray;

  public lineChartLabels2:Array<any> = this.dateRealTimeServedArray;

  //OPTIONS
  public lineChartOptions:any = {
    responsive: true,

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },

  };

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  //COLORS
  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  //EVENTS
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}
</code>```

app.component.html

```<code><div class="container">

<div class="front-end-app">
    <ul>
      <h3>Count Indexer Meta:</h3>
      <li *ngFor="let countIndexerMetaNumber of countIndexerMetaApi">
        {{countIndexerMetaNumber}}
      </li>
      <h3>Count Indexer Served:</h3>
      <li *ngFor="let countIndexerServedNumber of countIndexerServedApi">
        {{countIndexerServedNumber}}
      </li>
      <h3>Count Real Time Served:</h3>
      <li *ngFor="let countRealTimeServedNumber of countRealTimeServedApi">
        {{countRealTimeServedNumber}}
      </li>
    </ul>
    <hr>

    <div class="head">
      <h1>{{title}}</h1>
    </div>
    <hr>
    <div class="row">
      <div class="col-md-6">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                  [datasets]="lineChartData"
                  [labels]="lineChartLabels"
                  [options]="lineChartOptions"
                  [colors]="lineChartColors"
                  [legend]="lineChartLegend"
                  [chartType]="lineChartType"
                  (chartHover)="chartHovered($event)"
                  (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData1"
                    [labels]="lineChartLabels1"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
      <div class="col-md-6 offset-md-3">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData2"
                    [labels]="lineChartLabels2"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerMetaArray()"> Click to print count indexer meta array</button>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerServedArray()"> Click to print count indexer served array</button>
  <button type="button" class="btn btn-primary" (click)="printRealTimeServedArray()"> Click to print count real time served array</button>
</div>
</code>```

For any question or further explanation just comment and I'll answer straight away. Thanks!

答:
I am not getting what exactly is your problem, could you please clarify a little more.
But if your problem is with these lines

```<code>this.countIndexerServedNumber = this.countIndexerServedApi[0];
  //<-- timing problem since this.count is not yet
  // got from http.get() so it seems undefined
this.countIndexerServedArray.push(this.countIndexerServedNumber);
   // problem follows through
</code>```

then it's not working because get method works asynchronously, and therefore this.countIndexerServedApi is yet not initialized. So, to overcome this problem you should move these statements inside the subscribe block and then these statements will be executed only after  this.countIndexerServedApi gets initialized.

Body:
I have a web application that is retrieving data from multiple api and is supposed to use the data into some charts. The problem is that when the charts get rendered the data from the api are not in yet. I tried using .then() method but it tells me that property then does not exist on type void. Furthermore I tried using the ngIf method, following this answer, but is not working either. Do you know how could I solve this please?

Below are my component and my component template.

app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mimesi dashboard graphs';

  //COUNTS
  public countIndexerMetaApi; //array of one number populated from http.get
  public countIndexerMetaNumber; //number extracted into array and stored as an int
  public countIndexerMetaArray; //array to store countNumber afterwards

  public countIndexerServedApi;
  public countIndexerServedNumber;
  public countIndexerServedArray;

  public countRealTimeServedApi;
  public countRealTimeServedNumber;
  public countRealTimeServedArray;

  //DATES
  public dateIndexerMetaToStore; //date got from moment method that needs to be stored
  public dateIndexerMetaArray; //array to store dates for graph label

  public dateIndexerServedToStore;
  public dateIndexerServedArray;

  public dateRealTimeServedToStore;
  public dateRealTimeServedArray;

  //API LINKS
  private apiCountIndexerMetaUrl: string = 'http://localhost:3000/api/countIndexerMetaApi';
  /*      TODO - API FOR COUNT OF OTHER TWO TABLES      */
  private apiCountIndexerServedUrl: string = 'http://localhost:3000/api/countIndexerServedApi';
  private apiCountRealTimeServedUrl: string = 'http://localhost:3000/api/countRealTimeServedApi';

  //VARIABLE FOR TIMEOUT
  public isDataAvailable:boolean = false;

  constructor(private http:Http) {
    let now = moment.locale("it");

    //COUNT
    this.countIndexerMetaApi = 0;
    this.countIndexerMetaNumber = 0;
    this.countIndexerMetaArray = [];

    this.countIndexerServedApi = 0;
    this.countIndexerServedNumber = 0;
    this.countIndexerServedArray = []

    this.countRealTimeServedApi = 0;
    this.countRealTimeServedNumber = 0;
    this.countRealTimeServedArray = []

    //DATES
    this.dateIndexerMetaToStore = "";
    this.dateIndexerMetaArray = [];

    this.dateIndexerServedToStore = "";
    this.dateIndexerServedArray = [];

    this.dateRealTimeServedToStore = "";
    this.dateRealTimeServedArray = [];
  }

  ngOnInit() {
    this.getIndexerMetaCount();
    this.getIndexerServedCount();
    this.getRealTimeServedCount();
  }

  //COUNT
  getIndexerMetaCount(){
    this.http.get(this.apiCountIndexerMetaUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerMetaApi = data.map(countIndexerMetaApiObj => countIndexerMetaApiObj.countIndexerMetaApi))
            },
        );
    //this.countIndexerMetaNumber = this.countIndexerMetaApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerMetaArray.push(this.countIndexerMetaNumber); // problem follows through
  }
  printCountIndexerMetaArray(){
    this.countIndexerMetaApi.forEach(element => {
      console.log(element);
    });
  }

  getIndexerServedCount(){
    this.http.get(this.apiCountIndexerServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerServedApi = data.map(countObj => countObj.countIndexerServedApi))
            },
        );
    //this.countIndexerServedNumber = this.countIndexerServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerServedArray.push(this.countIndexerServedNumber); // problem follows through
  }
  printCountIndexerServedArray(){
    this.countIndexerServedApi.forEach(element => {
      console.log(element);
    });
  }

  getRealTimeServedCount(){
    this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countRealTimeServedApi = data.map(countObj => countObj.countRealTimeServedApi))
            },
        );
    //this.countRealTimeServedNumber = this.countRealTimeServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countRealTimeServedArray.push(this.countRealTimeServedNumber); // problem follows through
  }
  printRealTimeServedArray(){
    this.countRealTimeServedApi.forEach(element => {
      console.log(element);
    });
  }

  //DATES
  dateIndexerMeta() {
    this.dateIndexerMetaToStore = moment().add(-122, 'days');
    this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
  }

  dateIndexerServed() {
    this.dateIndexerServedToStore = moment().add(-122, 'days');
    this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
  }

  dateRealTimeServed() {
    this.dateRealTimeServedToStore = moment().add(-122, 'days');
    this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
  }

  //TIMEOUT TRIAL
  timeoutTrial(){
    console.log(this.isDataAvailable);
    setTimeout(function() {this.isDataAvailable = true;
      console.log(this.isDataAvailable);
    }, 5000); //<-- timeout works but other functions don't refresh even if isDataAvailable changed
  }

  /*      CHARTS      */

  //DATA
  public lineChartData:Array<any> = [
    {data: this.countIndexerMetaArray, label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: this.countIndexerServedArray, label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: this.countRealTimeServedArray, label: 'Real-Time served links'},
  ];

  //LABELS
  public lineChartLabels:Array<any> = this.dateIndexerMetaArray;

  public lineChartLabels1:Array<any> = this.dateIndexerServedArray;

  public lineChartLabels2:Array<any> = this.dateRealTimeServedArray;

  //OPTIONS
  public lineChartOptions:any = {
    responsive: true,

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },

  };

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  //COLORS
  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  //EVENTS
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}

app.component.html

Count Indexer Meta:

        {{countIndexerMetaNumber}}

Count Indexer Served:

        {{countIndexerServedNumber}}

Count Real Time Served:

        {{countRealTimeServedNumber}}

{{title}}

            <canvas baseChart width="600" height="400"
                  [datasets]="lineChartData"
                  [labels]="lineChartLabels"
                  [options]="lineChartOptions"
                  [colors]="lineChartColors"
                  [legend]="lineChartLegend"
                  [chartType]="lineChartType"
                  (chartHover)="chartHovered($event)"
                  (chartClick)="chartClicked($event)"></canvas>

            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData1"
                    [labels]="lineChartLabels1"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>

            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData2"
                    [labels]="lineChartLabels2"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>

  <button type="button" class="btn btn-primary" (click)="printCountIndexerMetaArray()"> Click to print count indexer meta array</button>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerServedArray()"> Click to print count indexer served array</button>
  <button type="button" class="btn btn-primary" (click)="printRealTimeServedArray()"> Click to print count real time served array</button>

For any question or further explanation just comment and I'll answer straight away. Thanks!

Body:
I am not getting what exactly is your problem, could you please clarify a little more.
But if your problem is with these lines

this.countIndexerServedNumber = this.countIndexerServedApi[0];
  //<-- timing problem since this.count is not yet
  // got from http.get() so it seems undefined
this.countIndexerServedArray.push(this.countIndexerServedNumber);
   // problem follows through

then it's not working because get method works asynchronously, and therefore this.countIndexerServedApi is yet not initialized. So, to overcome this problem you should move these statements inside the subscribe block and then these statements will be executed only after  this.countIndexerServedApi gets initialized.


问:
Image need to be replaced with another image each time with a different button click in html page
I have 3 buttons in a html page and each button is associated with an image.
I need the working as follows,

ButtonA, ButtonB, ButtonC and ImageA, ImageB, Image C.

When ButtonA is clicked, ImageA should be displayed.
When ButtonB is clicked, ImageA should be REPLACED with ImageB.
When ButtonC is clicked, ImageB should be REPLACED with ImageC.
Again when ButtonA is clicked ImageC should be REPLACED with ImageA.

I can use only javascript and html for coding. Is it possible to accomplish it? If yes, Can you give me sample code which i can refer?

答:
Please include any Javascript Code that you have attempted. If you simply want to set the source of an image through javascript, this can be seen in this fiddle.
Using a custom attribute on a button, as so:

```<code><input type="button" class="imgBtn" value="A" id="btnA" imageSrc="https://www.w3schools.com/css/img_fjords.jpg" onClick="changeImage(this)">
</code>```

Then, through hooking this button up to a function, passing in the button, you can access this attribute and set the image accordingly. Such as:

```<code>    function changeImage(buttonClicked) {
  var imageDiv = document.getElementById("newImg");
  imageDiv.src = buttonClicked.getAttribute("imageSrc");
  }
</code>```

However, using JQuery, this could be made simpler, without requiring an onClick function:

```<code>$('.imgBtn').on('click', function(e) {
    $('#newImg').attr('src', $(this).attr('imageSrc'));
});
</code>```

Body:
Please include any Javascript Code that you have attempted. If you simply want to set the source of an image through javascript, this can be seen in this fiddle.
Using a custom attribute on a button, as so:

<input type="button" class="imgBtn" value="A" id="btnA" imageSrc="https://www.w3schools.com/css/img_fjords.jpg" onClick="changeImage(this)">

Then, through hooking this button up to a function, passing in the button, you can access this attribute and set the image accordingly. Such as:

    function changeImage(buttonClicked) {
  var imageDiv = document.getElementById("newImg");
  imageDiv.src = buttonClicked.getAttribute("imageSrc");
  }

However, using JQuery, this could be made simpler, without requiring an onClick function:

$('.imgBtn').on('click', function(e) {
    $('#newImg').attr('src', $(this).attr('imageSrc'));
});


答:
You can simply do it like this

SIMPLE HTML AND JS (Beginner approach for learning)

<button onclick="document.getElementById('myImage').src='https://www.w3schools.com/js/pic_bulbon.gif'">Turn on the light</button>

<button onclick="document.getElementById('myImage').src='https://www.w3schools.com/js/pic_bulboff.gif'">Turn off the light</button>```
</div>
</div>
</p>

<p><strong>Using jQuery (Practical Approach)</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.light_switch').click(function(){

    var action= jQuery(this).attr('data-toggle');
   if(action=="on"){
        jQuery('#myImage').attr('src', 'https://www.w3schools.com/js/pic_bulbon.gif');
      }
  else{
    jQuery('#myImage').attr('src', 'https://www.w3schools.com/js/pic_bulboff.gif');
  }

});</code>```

<button class="light_switch" data-toggle="on">Turn on the light</button>

    <button class="light_switch" data-toggle="off">Turn off the light</button>```

Title: Image need to be replaced with another image each time with a different button click in html page

Body:
I have 3 buttons in a html page and each button is associated with an image.
I need the working as follows,

ButtonA, ButtonB, ButtonC and ImageA, ImageB, Image C.

When ButtonA is clicked, ImageA should be displayed.
When ButtonB is clicked, ImageA should be REPLACED with ImageB.
When ButtonC is clicked, ImageB should be REPLACED with ImageC.
Again when ButtonA is clicked ImageC should be REPLACED with ImageA.

I can use only javascript and html for coding. Is it possible to accomplish it? If yes, Can you give me sample code which i can refer?

Body:
You can simply do it like this

SIMPLE HTML AND JS (Beginner approach for learning)

<button onclick="document.getElementById('myImage').src='https://www.w3schools.com/js/pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="https://www.w3schools.com/js/pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='https://www.w3schools.com/js/pic_bulboff.gif'">Turn off the light</button>

Using jQuery (Practical Approach)

$('.light_switch').click(function(){

    var action= jQuery(this).attr('data-toggle');
   if(action=="on"){
        jQuery('#myImage').attr('src', 'https://www.w3schools.com/js/pic_bulbon.gif');
      }
  else{
    jQuery('#myImage').attr('src', 'https://www.w3schools.com/js/pic_bulboff.gif');
  }

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="light_switch" data-toggle="on">Turn on the light</button>

    <img id="myImage" src="https://www.w3schools.com/js/pic_bulboff.gif" style="width:100px">

    <button class="light_switch" data-toggle="off">Turn off the light</button>


问:
Specific example: Is it possible to aviod the use of a global variable?
I have the following program and the variable(dictionary) in question is player_info that stores player information (name and goals). In order to solve the error that results currently, I simply need to make player_info a global variable, but I was wondering if stackoverflow experts could suggest or discuss the possibility of alternate ways of solving this problem WITHOUT the use of global variables.

Code

```<code>#FOOTBALL COACH app

#The program allows a user to enter a number of players (their names and goals scored) and then search for a player, returning their average goals for the three matches

import sys
def main():
 mainmenu()

def mainmenu():

  print("=====WELCOME to the MAIN MENU=============")
  print("""
  1..........Add New Players & Goals
  2..........Search by Players
  3..........Quit

  =========================================
  """)

  choice=int(input("Enter choice:"))
  if choice==1:
    addplayers()
  elif choice==2:
    searchplayer(player_info)
  elif choice==3:
    sys.exit()
  else:
    print("You must make a valid choice - 1, 2 or 3")

def addplayers():

  player_info= {} #create a dictionary that stores the player name: player goals

  num_players = int(input("Please enter number of players you wish to enter:"))
  print ("You are entering %s players" %num_players)
  player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
  for i in range(0,num_players):
      player_name = input("Enter Player Name :")
      player_info[player_name] = {}
      for entry in player_data:
          player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

  mainmenu()

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")

main()
</code>```

As mentioned, I am aware that re-writing this in the addplayer() sub would fix the problem:

```<code>global player_info
player_info = {} #create a dictionary that stores the player name: player goals
</code>```

...I am looking for ways to solve the problem WITHOUT the use of global variables.

Update:

One answer below using return player_info is what I would like to go with, but it doesn't quite work yet. Also, I need to return to the main menu each time a player is added, not quite sure how to do this, without a mainmenu call each time. Any suggestions? https://repl.it/JRl5/1

答:
Store everything related to the game in a data structure, for example a dictionary, and pass it along in all functions where it can be updated as needed. Write a function "newgame" that creates this structure and initialises it.

In a way, this is object-oriented programming without using Python's syntax for classes and objects. Probably, you will learn these later in your class / tutorial.

Body:
I have the following program and the variable(dictionary) in question is player_info that stores player information (name and goals). In order to solve the error that results currently, I simply need to make player_info a global variable, but I was wondering if stackoverflow experts could suggest or discuss the possibility of alternate ways of solving this problem WITHOUT the use of global variables.

Code

#FOOTBALL COACH app

#The program allows a user to enter a number of players (their names and goals scored) and then search for a player, returning their average goals for the three matches

import sys
def main():
 mainmenu()

def mainmenu():

  print("=====WELCOME to the MAIN MENU=============")
  print("""
  1..........Add New Players & Goals
  2..........Search by Players
  3..........Quit

  =========================================
  """)

  choice=int(input("Enter choice:"))
  if choice==1:
    addplayers()
  elif choice==2:
    searchplayer(player_info)
  elif choice==3:
    sys.exit()
  else:
    print("You must make a valid choice - 1, 2 or 3")

def addplayers():

  player_info= {} #create a dictionary that stores the player name: player goals

  num_players = int(input("Please enter number of players you wish to enter:"))
  print ("You are entering %s players" %num_players)
  player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
  for i in range(0,num_players):
      player_name = input("Enter Player Name :")
      player_info[player_name] = {}
      for entry in player_data:
          player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

  mainmenu()

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")

main()

As mentioned, I am aware that re-writing this in the addplayer() sub would fix the problem:

global player_info
player_info = {} #create a dictionary that stores the player name: player goals

...I am looking for ways to solve the problem WITHOUT the use of global variables.

Update:

One answer below using return player_info is what I would like to go with, but it doesn't quite work yet. Also, I need to return to the main menu each time a player is added, not quite sure how to do this, without a mainmenu call each time. Any suggestions? https://repl.it/JRl5/1


问:
HyperlinkButton in C# XAMARIN.FORMS
I want to create Label with click possibility like in WIN phone xaml

```<code><HyperlinkButton Content="My Text to click"/>
</code>```

Is there a possibility to do it in Xamarin.Forms?

I found this but is not the same:

https://github.com/XLabs/Xamarin-Forms-Labs/wiki/HyperLinkLabel

答:
XAML code would be as follows:

```<code><Label
    Text="My Text to click"
    HorizontalOptions="Center" >

    <Label.GestureRecognizers>
        <TapGestureRecognizer
            Tapped="OnLabelTapped"
            NumberOfTapsRequired="2" />
    </Label.GestureRecognizers>
</Label>
</code>```

Note: By default, NumberOfTapsRequired is 1.

Then in your .cs file, add the method OnLabelTapped.

```<code>public void OnLabelTapped(object sender, EventArgs args)
{
    // Your code here
    // Example:
    // DisplayAlert("Message", "You clicked on the label", "OK");
}
</code>```

Title: HyperlinkButton in C# XAMARIN.FORMS

Body:
I want to create Label with click possibility like in WIN phone xaml

<HyperlinkButton Content="My Text to click"/>

Is there a possibility to do it in Xamarin.Forms?

I found this but is not the same:

https://github.com/XLabs/Xamarin-Forms-Labs/wiki/HyperLinkLabel

Body:
XAML code would be as follows:

<Label
    Text="My Text to click"
    HorizontalOptions="Center" >

    <Label.GestureRecognizers>
        <TapGestureRecognizer
            Tapped="OnLabelTapped"
            NumberOfTapsRequired="2" />
    </Label.GestureRecognizers>
</Label>

Note: By default, NumberOfTapsRequired is 1.

Then in your .cs file, add the method OnLabelTapped.

public void OnLabelTapped(object sender, EventArgs args)
{
    // Your code here
    // Example:
    // DisplayAlert("Message", "You clicked on the label", "OK");
}


问:
Mask video in A-Frame
I am evaluating the A-Frame framework and I am struggling with one task.

I need to mask a video. A static mask, say a feathered oval, would be fine.

My first idea was to simply include a webm video with an Alfa channel, but that video format doesn't play (with or without A-Frame) on iOS, so some other solution will be needed.
https://simpl.info/videoalpha/video/dancer1.webm

I found some reading on masking with three.js but cannot quite figure out how to take that first use case (static mask) to A-Frame:
http://blog.cjgammon.com/masking-5-glsl

I am also evaluating if it can be done with React VR.

Thank you for any insights!!

答:
The anwser should lie in materials, but since I have almost no knowledge of them I can only offer a really simple workaround, until someone posts a real solution.

If Your background is a single color, You can just make a transparent image - mask, in the backgrounds color, which You could place in front of the video.
 If placed 0.001 in front of the video, it looks like part of the masked image/video.

If Your background is complicated, I would make a black image mask, and feather both the inner circle and the outer one, so it wouldn't look pasted inside the scene.

I'm really hoping for a material solution, as we could learn something really useful.

Title: Mask video in A-Frame


问:
Options Menu null at runtime
I am changing the drawable of a specific menu item when certain actions are made within my app.

Everything works as it should except for when I try and do this in the onCreate method of my Activity.

I am using the following method:

```<code>menu.findItem(R.id.favorite).setIcon(R.drawable.ic_action_icons8_star_filled_100);
</code>```

In an onClick event and it works flawlessly.

But when I use the same method in my onCreate, it gives me the following eror:

```<code>java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference
</code>```

This is the code I am using to inflate the menu

```<code>private Menu menu;

--------------------

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.image_details, menu);

        this.menu = menu;

        return super.onCreateOptionsMenu(menu);
    }
</code>```

Any ideas? thanks.

答: According to the Activity lifecycle, onCreateOptionsMenu is called after onResume, so when onCreate is called, the field menu has not yet been set. If you move the call to onPrepareOptionsMenu it should work.

Title: Options Menu null at runtime

Body:
I am changing the drawable of a specific menu item when certain actions are made within my app.

Everything works as it should except for when I try and do this in the onCreate method of my Activity.

I am using the following method:

menu.findItem(R.id.favorite).setIcon(R.drawable.ic_action_icons8_star_filled_100);

In an onClick event and it works flawlessly.

But when I use the same method in my onCreate, it gives me the following eror:

java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

This is the code I am using to inflate the menu

private Menu menu;

--------------------

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.image_details, menu);

        this.menu = menu;

        return super.onCreateOptionsMenu(menu);
    }

Any ideas? thanks.


问:
Selecting records with latest year using data.table in R
I have a datatable where the same entity appears more than one time with a different date.

My objective is to retain a single record for each entity, the one with the latest date.

My code is not right though.  For a reproducible example see below:

```<code>data(mtcars)
mtcars
mtcars$model <- row.names(mtcars)
setDT(mtcars)
mtcars[, year := 2000]
mtcars1 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars1[, year := 2001]
mtcars2 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars2[, year := 2002]
mtcars <- rbind(mtcars, mtcars1, mtcars2)
setDT(mtcars)
mtcars

mtcars_latest <- mtcars[year == max(year) , names(mtcars), with = FALSE , by = model]
</code>```

With the last line I intend to group by model and then within each group select the record with the latest year (year == max(year)).  Moreover, I want all the variables (columns) of the original datatable to be returned, so I put names(mtcars), with = FALSE.

答:
dplyr offers an excellent interface for such operations:

```<code>library(dplyr)
mtcars_latest=
  copy(mtcars) %>%
  group_by(model) %>% # For each model
  arrange(year) %>%   # Sort by year
  filter(row_number()==n())  # And take the last row
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a datatable where the same entity appears more than one time with a different date.

My objective is to retain a single record for each entity, the one with the latest date.

My code is not right though.  For a reproducible example see below:

data(mtcars)
mtcars
mtcars$model <- row.names(mtcars)
setDT(mtcars)
mtcars[, year := 2000]
mtcars1 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars1[, year := 2001]
mtcars2 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars2[, year := 2002]
mtcars <- rbind(mtcars, mtcars1, mtcars2)
setDT(mtcars)
mtcars

mtcars_latest <- mtcars[year == max(year) , names(mtcars), with = FALSE , by = model]

With the last line I intend to group by model and then within each group select the record with the latest year (year == max(year)).  Moreover, I want all the variables (columns) of the original datatable to be returned, so I put names(mtcars), with = FALSE.

Body:
dplyr offers an excellent interface for such operations:

library(dplyr)
mtcars_latest=
  copy(mtcars) %>%
  group_by(model) %>% # For each model
  arrange(year) %>%   # Sort by year
  filter(row_number()==n())  # And take the last row


问:
Text and Images in Column - align image
I have two or more columns with an image + text flow.

Image size could be 50 to 400px, text from 1 line to 2 paragraphs

```<code>+---+
|   | +---+
|   | |   |
+---+ +---+
text  text
text  text
text
text
</code>```

Is it possible using flex to align about the bottom of the images without using js?

* { box-sizing: border-box; }

body { line-height: 1.5; }

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap row;
  max-width: 60rem;
  margin-right: auto;
  margin-left: auto;
}

.col {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 33.33333%;
  padding-right: .5rem;
  padding-left: .5rem;
}

.col-img {
  display: flex;
  flex: 1 0 auto;
  overflow: hidden;
  align-items: flex-end;
}

img {
  width: 100%;
  height: auto;
}

.col-content {
  flex: 1 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">
    <div class="col-img">
      <img src="//placehold.it/600x200">
    </div>
    <div class="col-content">
      <h1>Title</h1>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    </div>
  </div>
  <div class="col">
    <div class="col-img">
      <img src="//placehold.it/600x300">
    </div>
    <div class="col-content">
      <h1>Title</h1>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    </div>
  </div>
  <div class="col">
    <div class="col-img">
      <img src="//placehold.it/600x400">
    </div>
    <div class="col-content">
      <h1>Title</h1>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    </div>
  </div>
</div></code>```

https://jsfiddle.net/87j37r81/

答:
Try this? Flexbox Guide</p>

```<code>div#imageContainer {
  height: 160px;
  align-items: flex-end;
  display: flex;
  flex-direction: column;
}
</code>```

Title: Text and Images in Column - align image

Body:
I have two or more columns with an image + text flow.

Image size could be 50 to 400px, text from 1 line to 2 paragraphs

+---+
|   | +---+
|   | |   |
+---+ +---+
text  text
text  text
text
text

Is it possible using flex to align about the bottom of the images without using js?

* { box-sizing: border-box; }

body { line-height: 1.5; }

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap row;
  max-width: 60rem;
  margin-right: auto;
  margin-left: auto;
}

.col {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 33.33333%;
  padding-right: .5rem;
  padding-left: .5rem;
}

.col-img {
  display: flex;
  flex: 1 0 auto;
  overflow: hidden;
  align-items: flex-end;
}

img {
  width: 100%;
  height: auto;
}

.col-content {
  flex: 1 0 auto;
}

Title

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

Title

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

Title

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

https://jsfiddle.net/87j37r81/

Body:
Try this? Flexbox Guide

div#imageContainer {
  height: 160px;
  align-items: flex-end;
  display: flex;
  flex-direction: column;
}


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
Try

```<code>int *q = new int(8);
</code>```

But working with pointers here is not normally required. If you have to use pointer, use smart pointer shared_ptr<int> or uniqe_ptr<int>.

Body:
Try

int *q = new int(8);

But working with pointers here is not normally required. If you have to use pointer, use smart pointer shared_ptr<int> or uniqe_ptr<int>.


问:
Overlapping border div
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div></code>```

答:
That is because your styling for border under col class gets applied for both of the adjacent columns[cells]. If you do not want to add classes, try giving "id" and defining styles in CSS, or give inline styles. Negative values in CSS are avoided in general.

CSS:

```<code>.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border-right: solid 2px black;
  border-top: solid 2px black;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}
</code>```

HTML:

```<code><div style="border: solid 2px black;">
  <div class="row">
    <div style="border-top: none" class="col">x</div>
    <div style="border-top: none; border-right: none" class="col">x</div>
  </div>
  <div class="row">
    <div style="border-right: none" class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
    <div style="border-right: none" class="col">x</div>
  </div>
  <div class="row">
    <div class="row">
      <div class="col">x</div>
      <div style="border-right: none" class="col">x</div>
    </div>
    <div class="row">
      <div class="col">x</div>
      <div style="border-right: none" class="col">x</div>
    </div>
  </div>
</div>
</code>```

Title: Overlapping border div

Body:
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}

x

x

x

x

x

x

x

x

x

x

Body:
That is because your styling for border under col class gets applied for both of the adjacent columns[cells]. If you do not want to add classes, try giving "id" and defining styles in CSS, or give inline styles. Negative values in CSS are avoided in general.

CSS:

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border-right: solid 2px black;
  border-top: solid 2px black;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}

HTML:

<div style="border: solid 2px black;">
  <div class="row">
    <div style="border-top: none" class="col">x</div>
    <div style="border-top: none; border-right: none" class="col">x</div>
  </div>
  <div class="row">
    <div style="border-right: none" class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
    <div style="border-right: none" class="col">x</div>
  </div>
  <div class="row">
    <div class="row">
      <div class="col">x</div>
      <div style="border-right: none" class="col">x</div>
    </div>
    <div class="row">
      <div class="col">x</div>
      <div style="border-right: none" class="col">x</div>
    </div>
  </div>
</div>


问:
Android layout in keyboard view
Is it possible to create a custom layout like below shown
. Can someone help me figure out if it is possible?

答:
Yes.
Whoever happen to get similar idea can follow this guide.

Which basically explains step by step how to use KeyboardView to put custom keyboard inside your layout xml. And keys there could be defined to have any icon

```<code><Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    <Row>
        <Key android:codes="48"    android:keyLabel="0" />
        <Key android:codes="-3"    android:keyIcon="@drawable/human_saying_hello_icon" />
    </Row>
</Keyboard>
</code>```

Title: Android layout in keyboard view

Body:
Yes.
Whoever happen to get similar idea can follow this guide.

Which basically explains step by step how to use KeyboardView to put custom keyboard inside your layout xml. And keys there could be defined to have any icon

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    <Row>
        <Key android:codes="48"    android:keyLabel="0" />
        <Key android:codes="-3"    android:keyIcon="@drawable/human_saying_hello_icon" />
    </Row>
</Keyboard>


问:
Counting boolean values based on certain conditions

Dear All, Attached is the sql server 2016 database table. I want to get counts of column IsAssetIssued for true and flase values based on the condition AssetTypeID. I am trying

```<code>SELECT COUNT(IsAssetIssued) AS AvlAssets
FROM AssetStatus
WHERE (IsAssetIssued = True)
  AND (AssetTypeID = 1)
</code>```

but this is does not providing exact result for false values in the column. Please suggest a better solution.

Thanks,

答:
Thanks for your help you people helped me log. There was only a slight change in the query i.e. i put the IsAssetIssued value fixed to false and set the AssetTypeID to be dynamic.

SELECT COUNT(IsAssetIssued) AS AvlAssets FROM AssetStatus WHERE (IsAssetIssued = 'False') AND (AssetTypeID = 1);

it it worked perfectly.

Body:
Dear All, Attached is the sql server 2016 database table. I want to get counts of column IsAssetIssued for true and flase values based on the condition AssetTypeID. I am trying

SELECT COUNT(IsAssetIssued) AS AvlAssets
FROM AssetStatus
WHERE (IsAssetIssued = True)
  AND (AssetTypeID = 1)

but this is does not providing exact result for false values in the column. Please suggest a better solution.

Thanks,


问:
How to replace everything with blank after question mark in a string?
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

```<code>var str = "/root/Users?SkillId=201;"
</code>```

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

```<code>var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable
</code>```

I don't want to use for loop for this. Isn't there is any better way to do this?

答:
```<code>var str = "/root/Users?SkillId=201;"
var parts = str.split('?', 2);
</code>```

parts[0] contains string before '?'

Body:
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

var str = "/root/Users?SkillId=201;"

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable

I don't want to use for loop for this. Isn't there is any better way to do this?

Body:
var str = "/root/Users?SkillId=201;"
var parts = str.split('?', 2);

parts[0] contains string before '?'


问:
bootstrap make accordion responsive?
I'm using the Bootstrap 3 Accordion Collapse,right now everything loads in one column, how can I make it so the panels use multiple columns in desktop resolution and one column in mobile mode?

```<code>        <div class="row">

            <div class="panel-group" id="accordion">

                <?php
                foreach ($states as &$state) {
                    ?>
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h4 class="panel-title">
                                <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                    <?php echo $state; ?></a>
                            </h4>
                        </div>
                        <div id="<?php echo $state; ?>" class="panel-collapse collapse in">
                            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                                commodo consequat.</div>
                        </div>
                    </div>
                <?php }
                ?>
            </div>

        </div>
</code>```

EDIT

This is my edided html

```<code>            <div class="row">

                <div class="col-md-4 col-xs-12">

                    <div class="panel-group" id="accordion">

                        <?php
                        foreach ($states as &$state) {
                            ?>
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo preg_replace('/\s+/', '', $state); ?>">
                                            <?php echo $state; ?></a>
                                    </h4>
                                </div>
                                <div id="<?php echo preg_replace('/\s+/', '', $state); ?>" class="panel-collapse collapse in">
                                    <div class="panel-body">test</div>
                                </div>
                            </div>
                        <?php }
                        ?>

                    </div>

                </div>

            </div>
</code>```

and it looks like this now. Only one slim column in desktop resolution

答:
if this is your answer:

all you have to do is add bootstrap column classes before the panel group.

col-xs-12  smaller screen sizes, col-md-4 medium screen sizes / PC,
  col-lg-12 for large screen sizes, col-sm-6 for tablet screen sizes.

Title: bootstrap make accordion responsive?

Body:
I'm using the Bootstrap 3 Accordion Collapse,right now everything loads in one column, how can I make it so the panels use multiple columns in desktop resolution and one column in mobile mode?

                <?php
                foreach ($states as &$state) {
                    ?>

                                <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                    <?php echo $state; ?>

                        <div id="<?php echo $state; ?>" class="panel-collapse collapse in">

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                                commodo consequat.

                <?php }
                ?>

EDIT

This is my edided html

                        <?php
                        foreach ($states as &$state) {
                            ?>

                                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo preg_replace('/\s+/', '', $state); ?>">
                                            <?php echo $state; ?>

                                <div id="<?php echo preg_replace('/\s+/', '', $state); ?>" class="panel-collapse collapse in">

test

                        <?php }
                        ?>

and it looks like this now. Only one slim column in desktop resolution


问:
Remove Time from a DateTime object
I have a Datetime object and I want to remove time part from it. I tried the following line of code but still auth.dob contains time. How can I just set 2017-01-01 in it?

```<code>auth.dob = Convert.ToDateTime("2017-01-01").Date;
</code>```

答:
Sadly .Net does not include a type that only stores the date. Generally we use DateTime and set the time to midnight. Then when you output the value you just omit the Time when displaying it see DateTime.ToString(string), DateTime.ToShortDateString() and DateTime.ToLongDateString().

While this works it does lead to all sorts of confusion. I've often felt it would have been better to have a Date struct a Time struct and a DateTime struct that was a composition of the other two. But sadly that isn't the case.

There is the Noda Time library, but that is probably overkill in this case.

Alternatively you can role your own and store the day, month and year as separate numeric variables.

Title: Remove Time from a DateTime object

Body:
I have a Datetime object and I want to remove time part from it. I tried the following line of code but still auth.dob contains time. How can I just set 2017-01-01 in it?

auth.dob = Convert.ToDateTime("2017-01-01").Date;


问:
How do I write rgb2yuv based on the existing yuv2rgb method？
I took over an Android project, which already has a yuv2rgb method. I have to write this method rgb2yuv. Please help me, thank you!

```<code>public static int[] yuv2rgb(byte[] pYUV, int width, int height) {
    int[] pRGB = new int[width * height];
    int i, j, yp;
    int hfWidth = width >> 1;
    int size = width * height;
    int qtrSize = size >> 2;
    for (i = 0, yp = 0; i < height; i++) {
        int uvp = size + (i >> 1) * hfWidth, u = 0, v = 0;
        for (j = 0; j < width; j++, yp++) {
            int y = (0xff & pYUV[yp]) - 16;
            if ((j & 1) == 0) {
                u = (0xff & pYUV[uvp + (j >> 1)]) - 128;
                v = (0xff & pYUV[uvp + qtrSize + (j >> 1)]) - 128;
            }

            int y1192 = 1192 * y;
            int r = (y1192 + 1634 * v);
            int g = (y1192 - 833 * v - 400 * u);
            int b = (y1192 + 2066 * u);

            if (r < 0) r = 0;
            else if (r > 262143) r = 262143;
            if (g < 0) g = 0;
            else if (g > 262143) g = 262143;
            if (b < 0) b = 0;
            else if (b > 262143) b = 262143;

            pRGB[i * width + j] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff);
        }
    }
    return pRGB;
}
</code>```

答:
My colleague helped me find a way，it's work！</p>

```<code>public static byte[] colorconvertRGB_IYUV_I420(int[] aRGB, int width, int height) {
    final int frameSize = width * height;
    final int chromasize = frameSize / 4;

    int yIndex = 0;
    int uIndex = frameSize;
    int vIndex = frameSize + chromasize;
    byte[] yuv = new byte[width * height * 3 / 2];

    int a, R, G, B, Y, U, V;
    int index = 0;
    for (int j = 0; j < height; j++) {
        for (int i = 0; i < width; i++) {

            //a = (aRGB[index] & 0xff000000) >> 24; //not using it right now
            R = (aRGB[index] & 0xff0000) >> 16;
            G = (aRGB[index] & 0xff00) >> 8;
            B = (aRGB[index] & 0xff) >> 0;

            Y = ((66 * R + 129 * G + 25 * B + 128) >> 8) + 16;
            U = ((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128;
            V = ((112 * R - 94 * G - 18 * B + 128) >> 8) + 128;

            yuv[yIndex++] = (byte) ((Y < 0) ? 0 : ((Y > 255) ? 255 : Y));

            if (j % 2 == 0 && index % 2 == 0) {
                yuv[uIndex++] = (byte) ((U < 0) ? 0 : ((U > 255) ? 255 : U));
                yuv[vIndex++] = (byte) ((V < 0) ? 0 : ((V > 255) ? 255 : V));
            }

            index++;
        }
    }
    return yuv;
}
</code>```

Body:
I took over an Android project, which already has a yuv2rgb method. I have to write this method rgb2yuv. Please help me, thank you!

public static int[] yuv2rgb(byte[] pYUV, int width, int height) {
    int[] pRGB = new int[width * height];
    int i, j, yp;
    int hfWidth = width >> 1;
    int size = width * height;
    int qtrSize = size >> 2;
    for (i = 0, yp = 0; i < height; i++) {
        int uvp = size + (i >> 1) * hfWidth, u = 0, v = 0;
        for (j = 0; j < width; j++, yp++) {
            int y = (0xff & pYUV[yp]) - 16;
            if ((j & 1) == 0) {
                u = (0xff & pYUV[uvp + (j >> 1)]) - 128;
                v = (0xff & pYUV[uvp + qtrSize + (j >> 1)]) - 128;
            }

            int y1192 = 1192 * y;
            int r = (y1192 + 1634 * v);
            int g = (y1192 - 833 * v - 400 * u);
            int b = (y1192 + 2066 * u);

            if (r < 0) r = 0;
            else if (r > 262143) r = 262143;
            if (g < 0) g = 0;
            else if (g > 262143) g = 262143;
            if (b < 0) b = 0;
            else if (b > 262143) b = 262143;

            pRGB[i * width + j] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff);
        }
    }
    return pRGB;
}

Body:
My colleague helped me find a way，it's work！

public static byte[] colorconvertRGB_IYUV_I420(int[] aRGB, int width, int height) {
    final int frameSize = width * height;
    final int chromasize = frameSize / 4;

    int yIndex = 0;
    int uIndex = frameSize;
    int vIndex = frameSize + chromasize;
    byte[] yuv = new byte[width * height * 3 / 2];

    int a, R, G, B, Y, U, V;
    int index = 0;
    for (int j = 0; j < height; j++) {
        for (int i = 0; i < width; i++) {

            //a = (aRGB[index] & 0xff000000) >> 24; //not using it right now
            R = (aRGB[index] & 0xff0000) >> 16;
            G = (aRGB[index] & 0xff00) >> 8;
            B = (aRGB[index] & 0xff) >> 0;

            Y = ((66 * R + 129 * G + 25 * B + 128) >> 8) + 16;
            U = ((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128;
            V = ((112 * R - 94 * G - 18 * B + 128) >> 8) + 128;

            yuv[yIndex++] = (byte) ((Y < 0) ? 0 : ((Y > 255) ? 255 : Y));

            if (j % 2 == 0 && index % 2 == 0) {
                yuv[uIndex++] = (byte) ((U < 0) ? 0 : ((U > 255) ? 255 : U));
                yuv[vIndex++] = (byte) ((V < 0) ? 0 : ((V > 255) ? 255 : V));
            }

            index++;
        }
    }
    return yuv;
}