Q:

Retrieve elements created with Aura:Iteration

I'm trying to retrieve elements using document.getElementsByClassName("") within the afterRender function. This works as expected with normal elements. However, I can't seem to retrieve elements being created inside of my aura:iteration tags.
Is there a way to retrieve aura:iteration elements that I'm missing? Has aura:iteration not finished at the time that the afterRender function is called?

A:

This could depend on a lot of things.
For example, if your <aura:iteration> is looping over data that you're retrieving via an Apex controller, then the first time it is rendered there will be no components because it hasn't got the data from the server yet. One of the later renderings will include the data.
As a general rule, you would be better advised to use component.find('myAuraId') instead of document.getElementsByClassName(""). The framework prefers you to access things via component rather than mess around with the DOM directly. Messing with the DOM can lead you into strange difficulties as Locker Service stops you from doing things you might outside of Lightning. So, better to just go with the grain and use component.find('myAuraId').
Note that aura:id does not have to be unique and component.find('myAuraId') will return an array if it matches multiple elements. Annoyingly, if there is only one match, it does not return an array with one component, it just returns a single component. So, to treat it simply, you tend to have to write
var findResults = component.find('myAuraId');
if($A.util.isEmpty(findResults)) {
  findResults = [];
}
if(!$A.util.isArray(findResults)) {
  findResults = [ findResults ];
}

Once you have a reference to the component, you can call getElement() if you really must interact directly with the DOM. But, again, I'd strongly advise against it if you can possibly avoid it. If you call getElement() before the component is rendered, you will get null. If you call it after, you will get a Locker Service proxy for the element.


Q:

NullInjectorError: No provider for Store! AUTH GUARD Angular 9

I'm trying to develop Auth guard with Angular 9 but when I try to implement it into component in browser console gives me ERROR:

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(SampleModule)[AuthGuard -> Store -> Store -> Store ->
    Store]:    NullInjectorError: No provider for Store!
    NullInjectorError: R3InjectorError(SampleModule)[AuthGuard -> Store ->
    Store -> Store -> Store]:    NullInjectorError: No provider for Store!
        at NullInjector.get (core.js:1050)
        at R3Injector.get (core.js:16521)
        at R3Injector.get (core.js:16521)
        at R3Injector.get (core.js:16521)
        at NgModuleRef$1.get (core.js:35539)
        at R3Injector.get (core.js:16521)
        at injectInjectorOnly (core.js:905)
        at Module.ɵɵinject (core.js:915)
        at Object.AuthGuard_Factory [as factory] (auth.guard.ts:17)
        at R3Injector.hydrate (core.js:16747)
        at resolvePromise (zone-evergreen.js:793)
        at resolvePromise (zone-evergreen.js:752)
        at zone-evergreen.js:854
        at ZoneDelegate.invokeTask (zone-evergreen.js:400)
        at Object.onInvokeTask (core.js:40744)
        at ZoneDelegate.invokeTask (zone-evergreen.js:399)
        at Zone.runTask (zone-evergreen.js:168)
        at drainMicroTaskQueue (zone-evergreen.js:570)

Here is the Guard:
import {
  CanActivate,
  CanActivateChild,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router'
import { Store } from '@ngrx/store'
import { AppState } from '../auth.store/states/app.state'
import { AuthService } from '../auth.services/auth.services'
import { AuthActions } from '../auth.store/actions/auth.actions'

@Injectable({
    providedIn: 'root'
})

export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private store$: Store<AppState>,
              private authService: AuthService) {
  }

This is my Sample module
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';

import { SampleComponent } from './sample.component';
import { AuthGuard } from 'app/auth.app/auth.guards/auth.guard';

const routes = [
    {
        path     : 'sample',
        component: SampleComponent,
        canActivate : [AuthGuard]
    }
];

@NgModule({
    declarations: [
        SampleComponent
    ],
    imports     : [
        RouterModule.forChild(routes),

        TranslateModule,
    ],

    providers:[
        AuthGuard
    ],

    exports     : [
        SampleComponent
    ]
})

export class SampleModule
{
}

And this is my app module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule, Routes } from '@angular/router';
import { MatMomentDateModule } from '@angular/material-moment-adapter';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { TranslateModule } from '@ngx-translate/core';
import 'hammerjs';
import { AppComponent } from 'app/app.component';
import { LayoutModule } from 'app/layout/layout.module';

const appRoutes: Routes = [
    {
        path        : '',
        loadChildren: () => import('./auth.app/auth.module').then(m => m.AuthModule)
    },
    {
        path        : '',
        loadChildren: () => import('./main/sample/sample.module').then(m => m.SampleModule)
    }
];

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports     : [
        BrowserModule,
        BrowserAnimationsModule,
        HttpClientModule,
        RouterModule.forRoot(appRoutes),

        TranslateModule.forRoot(),

        // Material moment date module
        MatMomentDateModule,

        // Material
        MatButtonModule,
        MatIconModule,

        // App modules
        LayoutModule,
        // SampleModule,
    ],
    bootstrap   : [
        AppComponent
    ]
})
export class AppModule
{
}

A:

You will have to add the store to the imports:
imports: [
 StoreModule.forRoot(...)
]


Q:

Apache, SSL, UCC not working on CN but works on subjectAltName

I recently generated a UCC for

domain1.com
*.domain1.com
domain2.com
*.domain2.com

now when i visit http://domain1.com in Firefox i get:
domain1.com uses an invalid security certificate.

The certificate is not trusted because the issuer certificate is unknown.
The certificate is only valid for the following names:
  *.domain1.com , domain2.com , *.domain2.com

(Error code: sec_error_unknown_issuer)

It complaints that the SSL is

Issued by a not trusted authority - which is fine...
And its not valid for domain in question

Here is my SSL Cert in text form:
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 3 (0x3)
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=US, ST=Connecticut, L=Stamford, O=Example, Inc., CN=Example-CA/emailAddress=webmaster@domain1.com
        Validity
            Not Before: Oct 28 11:26:20 2010 GMT
            Not After : Oct 28 11:26:20 2011 GMT
        Subject: C=US, ST=Connecticut, L=Stamford, O=Example, Inc., CN=domain1.com/emailAddress=webmaster@domain1.com
        Subject Public Key Info:
                Public Key Algorithm: rsaEncryption
            RSA Public Key: (4096 bit)
                Modulus (4096 bit):
                    00:b8:bf:9a:73:a0:6e:b6:2d:98:97:74:03:fc:76:
                    44:36:1d:e8:e8:49:2c:02:01:45:77:24:fb:cc:37:
                    22:af:8c:41:2d:92:63:74:e3:08:81:59:49:2b:96:
                    22:bd:2e:f9:55:dd:d9:cb:7e:e8:bd:ce:15:24:87:
                    2d:9b:1a:9c:8e:bd:fe:20:99:cf:8c:29:d2:92:af:
                    5f:dc:7e:17:5e:25:e6:c2:bf:70:79:0f:e9:78:74:
                    a4:6c:15:4f:8b:c7:45:11:d0:4c:f0:05:85:cf:c0:
                    bc:37:e5:c7:45:fd:8e:05:37:c1:aa:50:ef:14:ab:
                    55:f9:7d:79:b7:1e:bd:83:bd:cf:59:25:e0:d9:99:
                    17:d7:00:46:8b:86:58:bf:66:1a:77:e0:a6:35:81:
                    45:51:0a:e7:86:f6:40:c7:73:a7:4a:b8:c4:66:5d:
                    dd:8b:9a:0f:8c:48:05:d5:bf:53:bc:e6:5b:60:3c:
                    50:21:a2:2c:e5:e1:15:eb:14:18:3d:f0:80:59:08:
                    74:f8:e7:d5:e9:7d:82:73:f2:f1:dc:e8:d9:7f:46:
                    d5:68:eb:c0:e2:6b:f1:6f:90:c3:af:66:d5:f3:24:
                    93:a1:9f:bd:a9:62:c9:0a:76:8e:b4:a1:28:4e:b7:
                    09:e3:90:99:44:4d:3e:4d:89:ec:7c:7f:ac:b5:77:
                    e3:8d:af:e3:da:09:98:51:09:bf:76:ac:d9:1a:34:
                    0c:4c:3c:43:eb:47:d6:b7:ed:d4:42:35:09:a0:b2:
                    98:3f:ad:b7:d1:49:4d:df:72:07:48:6c:3e:df:67:
                    6a:48:14:4b:0c:d4:48:37:a5:c8:f6:7b:4d:d3:01:
                    3f:32:e8:a9:ef:92:55:cb:24:25:9f:c0:98:53:d2:
                    0b:fa:30:3d:3d:c5:9d:90:cd:bf:c8:01:d3:7a:c2:
                    3a:78:b7:db:eb:c2:ee:de:bc:5c:c4:74:af:5a:23:
                    08:e5:8c:df:ec:0d:f1:b3:7a:86:88:99:17:e8:d9:
                    81:b2:3c:eb:40:d9:b3:09:82:5b:e0:fa:84:68:ed:
                    c6:2c:c9:59:93:c3:f8:80:70:67:1f:6c:f8:3c:25:
                    63:95:ee:de:e2:ba:92:34:b0:f8:a1:53:5b:22:d9:
                    f3:d3:4c:1a:91:12:e6:0d:af:e3:99:3a:29:d0:ba:
                    57:d3:08:3d:a1:2f:91:61:a2:86:f6:f8:33:61:dc:
                    da:39:82:03:25:f3:88:5a:8a:88:e3:be:5e:78:1b:
                    c2:74:a4:c8:0f:66:18:2a:1e:a0:a9:ac:1c:71:50:
                    81:b5:6e:d4:2a:c3:b6:bd:85:ea:ef:72:3d:76:08:
                    79:d5:59:6a:b4:f2:54:33:61:76:49:13:93:95:e5:
                    86:2a:c7
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                    OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                3F:40:13:7E:25:04:0A:B9:0F:5F:DE:5E:9D:55:94:10:EE:F2:2B:B0
            X509v3 Authority Key Identifier:
                keyid:8E:C4:D5:F3:69:12:A9:75:DA:0D:9B:59:11:C8:DE:53:67:C0:DA:1B

            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:*.domain1.com, DNS:domain2.com, DNS:*.domain2.com
    Signature Algorithm: sha1WithRSAEncryption
        20:cd:15:09:9a:0b:7b:90:bd:db:83:fd:21:15:9a:32:21:8e:
        98:42:28:63:8b:fe:9c:36:73:9e:2f:2c:87:af:a4:0d:01:06:
        f4:5e:c1:76:d9:3b:ab:85:90:87:8e:8a:63:a8:d8:49:82:98:
        a3:4b:4e:dc:fe:4f:af:6e:86:4c:64:55:74:ca:cd:7b:db:4a:
        b8:b0:ad:f5:75:c3:92:da:a7:2c:72:d0:dd:2e:0b:78:85:91:
        03:fd:51:40:df:58:02:c1:ab:c8:5d:09:4a:7c:15:e3:ec:30:
        13:ea:b3:26:bc:56:a2:66:a0:5d:d7:26:9c:f9:24:47:a7:55:
        15:5f:8a:d0:02:92:fd:f9:4d:40:74:7a:c1:a5:85:bc:83:ff:
        c5:d7:1d:97:48:e3:58:c6:c3:b9:ba:65:f7:ba:c8:db:86:13:
        32:48:42:fe:cf:07:58:47:3d:66:bd:87:c2:40:86:1b:3b:82:
        01:e1:57:7f:04:89:9c:45:2e:d9:7c:ae:cf:4f:87:50:0a:f0:
        ff:f6:b3:c1:ce:24:21:1c:2f:3c:62:80:a6:5d:3b:61:6c:b7:
        e4:22:c0:ed:a5:07:c5:a9:ad:e5:26:24:f2:d0:29:3e:b7:dc:
        b6:3a:2c:76:ee:a5:8e:ba:cf:bf:65:b3:40:93:9f:ad:82:1b:
        b2:d6:28:4c:2c:6b:3c:db:da:5f:73:20:3d:1b:59:13:93:de:
        cd:03:df:e8:fa:13:1f:9d:30:99:83:0b:12:60:63:65:64:d8:
        1e:3f:7e:4b:3a:fe:e4:19:db:55:f5:95:cc:77:f6:64:5b:53:
        4b:d0:e0:30:35:91:81:b8:65:2d:81:4e:1f:aa:c8:b3:d2:d8:
        7d:85:47:49:1d:a5:bc:65:16:a5:bb:3e:ea:12:f4:70:e7:11:
        59:52:d8:2b:5d:4e:14:5f:d3:ae:45:69:17:61:bc:43:dc:9a:
        03:c2:8b:79:f3:39:f4:a4:7f:f7:3c:c5:b7:9e:df:52:1b:41:
        8d:c4:5e:bf:5e:17:3e:c8:07:6f:35:47:a4:32:0f:8d:cc:ad:
        45:0e:72:a5:74:0d:08:64:cf:da:79:cb:e2:c5:73:78:ff:f6:
        fc:c8:b3:d2:88:ea:03:10:36:eb:d5:79:d6:97:99:17:cd:e3:
        17:cc:2a:27:0f:ff:41:84:8e:38:f0:b0:c2:7d:cb:b2:a1:40:
        af:74:98:fb:87:15:53:68:24:39:cb:8e:63:cf:c0:56:b3:7c:
        2f:39:5e:bd:6e:cf:5a:43:37:f6:20:db:34:65:48:8f:0e:49:
        6c:66:a5:a5:70:2f:09:d6:0f:ed:f8:86:a2:17:67:2b:fe:d3:
        aa:7b:56:7d:63:c3:17:a0

A:

You need to include domain1.com as a Subject Alternative Name. Most browsers will ignore the common name in the subject if there are Subject Alternative Names present. That is why Firefox thinks that the certificate is not valid for https://domain1.com


Q:

Iterating through directories with Python

I need to iterate through the subdirectories of a given directory and search for files. If I get a file I have to open it and change the content and replace it with my own lines.
I tried this:
import os

rootdir ='C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        f=open(file,'r')
        lines=f.readlines()
        f.close()
        f=open(file,'w')
        for line in lines:
            newline = "No you are not"
            f.write(newline)
        f.close()

but I am getting an error. What am I doing wrong?

A:

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:
import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.

Updated for Python3
import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

A:

Another way of returning all files in subdirectories is to use the pathlib module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):
from pathlib import Path

rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]

# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]

Since Python 3.5, the glob module also supports recursive file finding:
import os
from glob import iglob

rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob('**/*', recursive=True) if os.path.isfile(f)]

The file_list from either of the above approaches can be iterated over without the need for a nested loop:
for f in file_list:
    print(f) # Replace with desired operations

A:

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:
import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:
/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)
Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and
zero or more directories and subdirectories.
3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:
>>> import glob
>>> glob.glob('*.gif') ['card.gif']
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern),
which is the same as calling glob() with **/ added in front of the given relative pattern.


Q:

Hexagonal image in object

I have used a scrollView in my page in order to display maximum 10 Images. Images are displayed in a hexagonal shape but not in the shape i want. Now it looks like current hex shape
but i need to show like this- hex shape i need
I am posting my code below. Please anyone can guide me.
-(CAShapeLayer*)ChangeShape:(UIView*)view
{

CAShapeLayer *maskLayer = [CAShapeLayer layer];

maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.frame = view.bounds;

CGFloat width = view.frame.size.width;
CGFloat height = view.frame.size.height;
CGFloat hPadding = width * 1 / 8 / 2;

UIGraphicsBeginImageContext(view.frame.size);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(width/2, 0)];
[path addLineToPoint:CGPointMake(width - hPadding, height / 4)];
[path addLineToPoint:CGPointMake(width - hPadding, height * 3 / 4)];
[path addLineToPoint:CGPointMake(width / 2, height)];
[path addLineToPoint:CGPointMake(hPadding, height * 3 / 4)];
[path addLineToPoint:CGPointMake(hPadding, height / 4)];
[path closePath];
[path closePath];
[path fill];
[path stroke];

maskLayer.path = path.CGPath;

UIGraphicsEndImageContext();
return maskLayer;
}

A:

Change your ChangeShape function like this
-(CAShapeLayer*)ChangeShape:(UIView*)view{
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.fillRule = kCAFillRuleEvenOdd;
    maskLayer.frame = view.bounds;

    CGFloat width = view.frame.size.width;
    CGFloat height = view.frame.size.height;
    CGFloat hPadding = width * 1 / 8 / 2;

    UIGraphicsBeginImageContext(view.frame.size);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, height / 2)];
    [path addLineToPoint:CGPointMake(width / 4 , hPadding)];
    [path addLineToPoint:CGPointMake(width * 3 / 4, hPadding)];
    [path addLineToPoint:CGPointMake(width, height / 2)];
    [path addLineToPoint:CGPointMake(width * 3 / 4, height - hPadding)];
    [path addLineToPoint:CGPointMake(width / 4, height - hPadding)];
    [path closePath];
    [path fill];
    [path stroke];

    maskLayer.path = path.CGPath;

    UIGraphicsEndImageContext();
    return maskLayer;
}


Q:

How do you properly set the margin of a block-element, when within a block-element with scrollbars?

I have
 block that is used for displaying content.  I've setup the div so that if the content is to big, a vertical scrollbar should appear.
Now, I need to put table within this container div, and I need it to be as wide as the parent, with a margin of a couple pixels on each side.  However, when I apply a margin to the inner-table, the right-side is sizing beyond the edges of the parent div, with the scrollbars.

        How can I fix my margins?

.data_container {
    border-color: black;
    border-style: solid;
    border-width: 2px;
    background-color: white;
    margin: 50px !important;
    font-size: smaller;
}

Also, here is an example of what I'm seeing in JSFiddle.  This is a barebones example that demonstrates the problem.

A:

One option is to use CSS' calc():

.data_container {
  border-color: black;
  border-style: solid;
  border-width: 2px;
  background-color: white;
  margin: 50px !important;
  font-size: smaller;
  width: calc(100% - 100px);
}

      How can I fix my margins?


Q:

the did Update To location is not being called

I've just started working with maps and locations . I've added the required code to the info.plist as (right after <dict>) :
<key>NSLocationAlwaysUsageDescription</key>
    <string>Can we use your location?</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Can we use your location?</string>

However I cant get the function called and as a result I dont have any output
import UIKit
import CoreLocation

class ViewController: UIViewController , CLLocationManagerDelegate {

   var locationManeger = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManeger.delegate = self
        locationManeger.requestWhenInUseAuthorization()
        locationManeger.startUpdatingLocation()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {

    print("got the location ")

    }

}

A:

My dear Friend if You are testing in simulator. run your app and select simulator and select Debug tab from upside and in hardware select Location and in location select Apple instead of None
Debug->Location->Apple
its will call your method . but it will show apple as a location but if you want proper location you have to check in iphone


Q:

Error when backuping exchange 2010 using backup tool in windows server 2008 r2

It will come out the below error when backuping exchange 2010 using backup tool in windows server 2008 r2
Consistency check for component 'e8ed1165-a879-49f4-8865-99a99de6a2ff'\'Microsoft Exchange Server\Microsoft Information Store\servername' failed.
My company using exchange 2010 (two server installed with windows server 2008 R2).
There is an DAG between two exhange server.
I have sort and find some suggestion on exchange 2007 as per below ,but i not sure that it suit for exchange 2010.

Open Registry Editor and browse to the HKEY_LOCAL_MACHINE\Software\Microsoft\Exchange\Replay\Parameters registry key.

Add a new DWORD value named EnableVSSWriter and set the value to 0 (zero).
Restart the Microsoft Exchange Replication Service.*

Any suggestion? Thanks!

A:

Yes, that registry change applies to Exchange 2010 DAG members when using Windows Server Backup.
http://exchangeserverpro.com/event-id-2137-windows-server-backup-completed-warnings-exchange-2010-mailbox-server


Q:

Css height in percent not working

I have the following simple code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Live Feed</title>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

    I should be tall

But the div doesn't get displayed with height being 100%. Why?

A:

You need to set a 100% height on all your parent elements, in this case your body and html. This fiddle shows it working.

html, body { height: 100%; width: 100%; margin: 0; }
div { height: 100%; width: 100%; background: #F52887; }

A:

Make it 100% of the viewport height:
div {
  height: 100vh;
}

Works in all modern browsers and IE>=9, see here for more info.

A:

height: 100% works if you give a fixed size to the parent element.


Q:

What's the difference for object, string, symbol when sent with akka?

See following code, Op1, Op2, Op3 all can be acted as message when communicate with other actors.
My question is what is the difference, any suggested way to use? Something maybe like use Op1 is more efficiently or less bytes will be used to use one of them? I want to find a best practice.
package local

import akka.actor._

object Constant {
  case object Op1
  val Op2 = "msg"
  val Op3 = 'msg
}

object Local extends App {
  implicit val system = ActorSystem("LocalSystem")
  val localActor = system.actorOf(Props[LocalActor], name = "LocalActor")
  localActor ! Constant.Op1
  localActor ! Constant.Op2
  localActor ! Constant.Op3
}

class LocalActor extends Actor {
  def receive = {
    case Constant.Op1 =>
      println("1")
    case Constant.Op2 =>
      println("2")
    case Constant.Op3 =>
      println("3")
  }
}

A:

Well... the term "best practices" is very subjective. And the context of your problem statement will generally have an impact on which is the best practice for you. And for this reason you should focus more on why is this a best practice than what is the best practice.
Now lets discuss this in a generic context.
As you understand that Akka actors use messages to communicate with each other. And you must understand that whenever there is communication between two parties there exist a need of a protocol between them which enables them to communicate in a un-ambigous manner.
Also, we know that both the parties can as well decide to communicate in just english without any protocol, but that introduces the possibilities of misunderstanding each other.
Now this problem of having a possibility of ambiguity is kind of unwanted when we want to build reliable systems. Thats why we start to setup protocols between our actors.
object LaughProtocol {
  sealed trait LaughMessage

  case object Lol extends LaughMessage
  case object Rofl extends LaughMessage
  case object Lmao extend LaughMessage
}

class LaughActor extends Actor with ActorLogging{

  import LaughProtocol._

  override def receive = {
    case msg @ LaughMessage => handleLaugh(msg)
    case msg @ _ => log.info("unexpected message :: {}", msg)
  }

  def handleLaugh(msg: LaughMessage) = {
    case Lol => println("L O L")
    case Rofl => println("R O F L")
    case Lmao => println("L M A O")
  }

}

This brings us the simplicity of being able to be sure about the nature of the messages that we are going to handle. Also... for any other actor communicating with LaughActor, it clearly spells out the rules for communicating with LaughActor.
Now... you will say what was wrong with just defining these as Strings.
class LaughActor extends Actor with ActorLogging{

  override def receive = {
    case "Lol" => println("L O L")
    case "Rofl" => println("R O F L")
    case "Lmao" => println("L M A O")
    case msg @ _ => log.info("unexpected message :: {}", msg)
  }

}

You can argue that even in this case, any developer can look at the code of this actor and figure out the protocol. And while it is true that they can but when looking at real world code spanning dozens of files... it becomes very very difficult.
And not only that... you loose one of your most important helper in writing correct code which is called compiler. Just consider following lines taken from a potential user of LaughActor.
// case 1 - With sealed hierarchy of messages
laughActorRef ! LuaghProtocol.Lol

// case 2 - with strings,
laughActorRef ! "lol"

What if the developer committed a mistake and wrote following instead of above
    // case 1 - With sealed hierarchy of messages
laughActorRef ! LuaghProtocol.Loll

// case 2 - with strings,
laughActorRef ! "loll"

In the first case the compiler will immediately point out the error... but in the second case this error will pass un-noticed and may cause a lot of headache to debug when hidden in a code base of tens of thousands of lines.
But again... you can even avoid this issue by using only pre-defined strings, like following
object LaughProtocol {
  val Lol = "Lol"
  val Rofl = "Rofl"
  val Lmao = "Lmao"
}

class LaughActor extends Actor with ActorLogging{

  import LaughProtocol._

  override def receive = {
    case msg if msg.equals(LaughProtocol.Lol) => println("L O L")
    case msg if msg.equals(LaughProtocol.Rofl) => println("R O F L")
    case msg if msg.equals(LaughProtocol.Lmao) => println("L M A O")
    case msg @ _ => log.info("unexpected message :: {}", msg)
  }
}

But... consider a bigger application with dozens of actors written by a team of 5-6 developers.
Notice that... as of now developers are solely relying on the defined members LaughProtocol.Lmao etc... and they actually do not look at what values LaughProtocol.Lmao etc have.
Now... lets say another actor has a protocol like following,
object LoveProtocol {
  val LotsOfLove = "Lol"
}

Now... you should be able to notice the problem. Consider the case of any actor which is supposed to handle messages of both of these protocols. All it will ever receive is a String Lol and it will have no way of knowing whether it is a LaughProtocol.Lol or LoveProtocol.LotsOfLove.
So... now whenever a developer is adding any new message to any of the protocols he need to make sure that no other protocol is using the same String. And this is simply not an option for teams working on large code bases.
And these are just few of the reasons why people prefer things like sealed protocols in their code bases.


Q:

Watchkit notification scene mandatory?

i am a little bit confusing about Watchkit notification because the documentation say:

Apps are not required to do anything to support notifications. The system provides a default notification interface that displays the alert message from the notification. However, apps can customize the notification interface and include custom graphics, content, and branding.

My app receive remote notification, i want that Apple Watch notification, but without customization. In this case notification scene is mandatory inside the project or is necessary only if you want make a custom view?

A:

The notification interfaces are needed only if you wish to customize them. If you don't include them, the Watch OS will present the alerts using a default interface.


Q:

making a function that translates a point around another point

given an array of points my program should in theory, Find the two furthest points from each other. Then calculate the angle that those two points make with the x axis. Then in rotate all the points in the array around the averaged center of all the points by that angle. For some reason my translation function to rotate all the points around the center is not working it is giving me unexpected values. I am fairly sure the math I am using to do this is accurate since I tested the formula I am using using wolfram alpha and plotted the points on desmos. I am not sure what's wrong with my code because it keeps giving me unexpected output. Any help would greatly be appreciated.
This is the code to translate the array:
def translation(array,centerArray):
    array1=array
    maxDistance=0
    point1=[]
    point2=[]
    global angle
    for i in range(len(array1)):
        for idx in range(len(array1)):
            if(maxDistance<math.sqrt(((array1[i][0]-array1[idx][0])**2)+((array1[i][1]-array1[idx][1])**2)+((array1[i][2]-array1[idx][2])**2))):
                maxDistance=math.sqrt(((array1[i][0]-array1[idx][0])**2)+((array1[i][1]-array1[idx][1])**2)+((array1[i][2]-array1[idx][2])**2))
                point1 = array1[i]
                point2 = array1[idx]
    angle=math.atan2(point1[1]-point2[1],point1[0]-point2[0]) #gets the angle between two furthest points and xaxis

    for i in range(len(array1)): #this is the problem here
        array1[i][0]=((array[i][0]-centerArray[0])*math.cos(angle)-(array[i][1]-centerArray[1])*math.sin(angle))+centerArray[0] #rotate x cordiate around center of all points
        array1[i][1]=((array[i][1]-centerArray[1])*math.cos(angle)+(array[i][0]-centerArray[0])*math.sin(angle))+centerArray[1] #rotate y cordiate around center of all points

    return array1

This is the code I am using to test it. tortose is what I set turtle graphics name as
tortose.color("violet")
testarray=[[200,400,9],[200,-100,9]] #array of 2 3d points but don't worry about z axis it will not be used for in function translation
print("testsarray",testarray)
for i in range(len(testarray)): #graph points in testarray
    tortose.setposition(testarray[i][0],testarray[i][1])
    tortose.dot()
testcenter=findCenter(testarray) # array of 1 point in the center of all the points format center=[x,y,z] but again don't worry about z
print("center",testcenter)
translatedTest=translation(testarray,testcenter) # array of points after they have been translated same format and size of testarray

print("translatedarray",translatedTest) #should give the output [[-50,150,9]] as first point but instead give output of [-50,-99.999999997,9] not sure why
tortose.color("green")
for i in range(len(testarray)): #graphs rotated points
    tortose.setposition(translatedTest[i][0],translatedTest[i][1])
    tortose.dot()

print(angle*180/3.14) #checks to make sure angle is 90 degrees because it should be in this case this is working fine

tortose.color("red")
tortose.setposition(testcenter[0],testcenter[1])
tortose.dot()

find center code finds the center of all points in array don't worry about z axis since it is not used in translation:
def findCenter(array):
    sumX = 0
    sumY = 0
    sumZ = 0
    for i in range(len(array)):
        sumX += array[i][0]
        sumY += array[i][1]
        sumZ += array[i][2]
    centerX= sumX/len(array)
    centerY= sumY/len(array)
    centerZ= sumZ/len(array)
    #print(centerX)
    #print(centerY)
    #print(centerZ)
    centerArray=[centerX,centerY,centerZ]
    return centerArray

import math
import turtle
tortose = turtle.Turtle()
tortose.penup()

my expected output should be a point at (-50,150) but it is giving me a point at (-50,-99.99999999999997)

A:

This is a common mistake when doing in-place rotations:
array1[i][0]= ...
array1[i][1]= ... array[i][0] ...

First you update array1[i][0]. Then you update array1[i][1], but you use the new value when you should use the old value. Instead, temporarily store the old value:
x = array1[i][0]
array1[i][0]=((array[i][0]-centerArray[0])*math.cos(angle)-(array[i][1]-centerArray[1])*math.sin(angle))+centerArray[0] #rotate x cordiate around center of all points
array1[i][1]=((array[i][1]-centerArray[1])*math.cos(angle)+(x-centerArray[0])*math.sin(angle))+centerArray[1] #rotate y cordiate around center of all points


Q:

QTP: how to use operators in Discriptive Programming

how to use different operators in QTP for example
Window("text:=Calculator").WinButton("text:= =").Click
Window("text:=Calculator").WinButton("text:= +").Click

it doen't work for me when i run this i am getting error like this

Cannot identify the object "[ WinButton ]" (of class WinButton). Verify that this object's properties match an object currently displayed in your application.

A:

The problem (according to the error message) is in the identification not the action (operator as you call it)
The problem is that when you use descriptive programming the description is treated as a regular expression, the character + has special meaning in regular expressions (it means one or more of the preceding (in you case space). Try escaping the plus (with a backslash).
Window("text:=Calculator").WinButton("text:= \+").Click


Q:

Why does the coefficient value of the binary polynomial x ^ n-1 appear other than –1,1?

I factorize the binomial polynomial x ^ n-1 and observe the coefficients of the arguments.
I thought that the coefficients of the arguments of x ^ n-1 would all be -1,1, but in fact they did not.
For example, a factor of 2 appears in the coefficient of the argument of x ^ 105-1.

As the value of n increases, the coefficients of the arguments start to appear as well as 2, 3, 4, 5, ..., and so on.
The following figure shows the table of the formulas and the number of times the coefficients appear first, from n = 1 to n = 10000.

I wonder if this phenomenon is known to the cause and the rules.
Is there a mathematical reason for the n value where other coefficients than 1, -1 appear? Or is it an irregular phenomenon?
Thank you for letting me know about the research article, site or contents.

A:

The polynomial
$$x^n-1=\prod_{d\mid n}\Phi_d(x)$$
where $\Phi_d$ is the $d$-th cyclotomic polynomial. This is the polynomial whose zeroes are precisely the primitive $d$-th roots of unity.
Yes, $\Phi_{105}$ has a coefficient $\pm2$. It is known that arbitrarily
large coefficients do occur in the cyclotomic polynomials.


Q:

Use of transitive verbs and present continuous

I would like to use the transitive verb "implicate". My search on Google lead solely to the result, that it should be followed by a noun (David, downfall, herself, ...). However, can I use this transitive verb with a continuous form of a verb?
To put it simply: I would like to know whether I can use one of these options or both are wrong.

"This implicates to find a common language."
  "This implicates finding a common language."

A:

Continuous verb forms are to be + -ing form of verb.
A transitive verb is a verb that requires a direct object.
They exist together without issue.

I kicked the ball.
I am kicking the ball.

However, just because you see an -ing word does not mean it's continuous tense, a form of to be must precede it.

This implicates finding a common language.

Implicates is not a continuous tense here. The continuous form of this sentence would be This is implicating finding a common language.
So you are not really asking about present continuous tense.
What you are doing here is using a verb as an noun, and that noun is falling in the same place as an object.  When you do this, you may need to use the plain verb form, the full infinitive form "to X", or the -ing form of the verb.
The rules on which to choose are complex (for example, after want you would normally use the full infinitive - e.g. I want to go to the park.)  Look at this for further help.
In this situation you should use the -ing form of the verb as you've done in your second sentence.


Q:

Emacs switches to old buffers when a stale command is quit

I must be in the habit of leaving the mini-buffer in the middle of a command.  From there I will change buffers and continue working.  Later (sometimes much later) I'll notice that I had a command dangling incomplete in the mini-buffer.  If I go to cancel it with a C-g, Emacs will often swap buffers in my open windows to an earlier state.
I suppose this may be a feature, but in my flow of work I find it rather annoying.  Is there a way to stop this behavior or prevent it from happening, such as a warning that There is an incomplete command?

A:

I think that the answer to another question will help you solve this.  It can be an annoying behavior, but the solution limits some of the flexibility found in Emacs.
The answer is: How can I prevent the mini-buffer from displaying previous commands in Emacs? (I call it stop-using-minibuffer).


Q:

Help needed for old links to www.iphonesdkarticles.com

http://www.iphonesdkarticles.com is dead and archive.org doesn't have it due to a robots.txt.
But we have 198 1 post left with a dead link to iphonesdkarticles.com, from Jan 2009 to May 2013.
What to do?

A:

Every single link-only answer, regardless of whether or not the link is broken, should be flagged as "not an answer".
To add to this, any answer that doesn't incorporate the key parts from that now defunct site should be flagged as such as well.
This is why we flag these questions.  Now that the site's gone, their answer is worthless.


Q:

C#: DataTable conversion row-by-row

In an abstract class (C# 3), there is a virtual method named GetData which returns a DataTable. The algorithm of the method is as following:

Get SQL query string from the class.
Get DataTable from database using above query.
Do transformations on DataTable and return it.

In the 3rd point, I clone the original DataTable in order to change the Type of column (I can't do that on populated table and can't setup this at the 2nd point) and enumerate every row in which I copy and transform data from the original one. Transformations depends on the class, every one has private methods which transforms data on its own.
The question is: How to make a method in a base class which will be based on the following three params: column name which will be converted, Type of new column and action during the transformation. Two first are quite simple but I'm not sure about the third one. I thought about designing a new class which will store these three parameters, and the action will be stored as following delegate:
public delegate object Convert(object objectToConvert);

The conversion would look something like that:
int rowCounter = 0;

foreach(DataRow row in dt.Rows)
{
 foreach(var item in Params)
 {
  row[item.ColumnIndex] = item.Convert(originalDataTable.Rows[rowCounter].ItemArray[item.ColumnIndex]);
 }

 ++rowCounter;
}

For now, I have to override the method GetData() in every class I want to have a transformations which causes a large duplication of code. The point I want to achieve is to make a base class which will be based on params I mentioned above. Is the above solution good for this problem or is it any other way to do that?

A:

Okay, for now I have a following solution which does fully satisfy me:
Every convertor implements following interface:
public interface IConvertor
{
 object Convert(object item);
}

Params class is as following:
Type ColumnType { get; protected set; } // New type
string[] ColumnNames { get; protected set; }
IConvertor Convertor { get; protected set; }

Every object have its own Params array property. I've got one method for every derived class and all what I have to do is to set up parameters.


Q:

Robolectric ContentProvider testing

I have noticed that every now and then there is a question about using Robolectric for testing custom ContentProviders. However, there has never been a concrete and unambiguous answer on how to do it properly. I have stumbled upon 2 different approaches:

one saying you can simply instantiate an in-memory ContentProvider, which you can use to insert and query data (https://gist.github.com/anonymous/6139359)
the other saying to use the ShadowContentResolver to set mock cursor data (https://groups.google.com/d/msg/robolectric/r35mMirIkTs/xJJBNXl_RgwJ)

However, I'm getting a java.lang.InstantiationException with both approaches. There have been some SO posts saying that this is due to SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java) not being overriden in Robolectric (Android + Robolectric - RuntimeException / InstantiationException in queryBuilder.query() in ContentProvider).
I guess my question is - are there any preffered workarounds that make testing ContentProviders possible. Or are there any other approaches that are better then those 2 mentioned above.

A:

This is the Robolectric (v2.4) test that worked fine for me:
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;

import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowContentResolver;

import co.tomup.app.db.DbSchema;
import co.tomup.app.db.TomupContentProvider;
import co.tomup.app.db.model.CalendarDay;
import co.tomup.app.db.tables.CalendarDayTable;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class CalendarDayProviderTest {

    private ContentResolver mContentResolver;
    private ShadowContentResolver mShadowContentResolver;
    private TomupContentProvider mProvider;

    @Before
    public void setup() {
        mProvider = new TomupContentProvider();
        mContentResolver = Robolectric.application.getContentResolver();
        mShadowContentResolver = Robolectric.shadowOf(mContentResolver);
        mProvider.onCreate();
        ShadowContentResolver.registerProvider(DbSchema.AUTHORITY, mProvider);
    }

    @Test
    public void testInsertAndDelete() {
        // insert
        CalendarDay calendarDay = new CalendarDay();
        calendarDay.setId(1L);
        calendarDay.setDay(new LocalDate());
        calendarDay.setMoonPhase("new");
        calendarDay.setSunrise(1);
        calendarDay.setSunset(100);
        Uri insertionId = mContentResolver.insert(CalendarDayTable.CONTENT_URI,
                calendarDay.toSQLiteContentValues());
        Cursor cursorCheck = mShadowContentResolver.query(CalendarDayTable.CONTENT_URI,
                null, null, null, null);
        while (cursorCheck.moveToNext()) {
            CalendarDay calendarDayCheck = CalendarDay.fromSQLiteCursor(cursorCheck);
            assertEquals(calendarDay, calendarDayCheck);
        }
        assertTrue(cursorCheck.getCount() > 0);
        // delete
        mShadowContentResolver.delete(insertionId,
                null, null);
        cursorCheck = mShadowContentResolver.query(CalendarDayTable.CONTENT_URI,
                null, null, null, null);
        assertTrue(cursorCheck.getCount() == 0);
    }
}

A:

All you have to do, is set up ShadowContentResolver before test, so it will properly associate authority of your ContentProvider with ContentProvider itself. Here is an example:
ShadowContentResolver.registerProvider(
        "com.example.provider",    //authority of your provider
        contentProvider    //instance of your ContentProvider (you can just use default constructor)
);

The easiest way is to put this stuff into some @Before annotated set-up method. However, the more correct (and therefore better in long term) way is to put this into your TestApplication#onCreate method, so this configuration will be used by all tests in your application.


Q:

ASP.Net MVC and Webservices/Ajax - Which route to take?

I'm developing an ASP.Net mvc application which has a requirement to do some small, atomic actions without an entire page postback. The logical way of doing this is of course with an ajax call.
My question is - What would people suggest is the best way of achieving this?
As far as I am aware I can do it along the following lines:

WCF + ajax
Controller actions within the mvc application - Possibly returning as JSON result.
Webservices (seperate/combined project) + ajax

I have a requirement that the user be logged on when using the webservice/wcf/ajax, which is currently done via cookie/session id but as far as I am aware all the above methods allow this.
On the whole whichever method I end up using will be accessing the database via standardised accessible method calls, so I'm not tied into keeping everything within the same project/namespace.
Would love to hear peoples thoughts / experiences on this!

A:

I would recommend doing it as controller actions. Here's why: You may end up being able to make the same action return several different representations. For example, a GetPerson() action could be able to return Person data as XML, JSON, or HTML (and possibly other representations).
This is a common approach in Rails and also in ASPMVC.


Q:

How to remove a shadow root from an HTML element adorned with a Shadow DOM from a template?

I'm exploring imports, templates, shadow DOM and custom elements in Chrome Canary (33.0.1712.3). In a grid layout I have a particular content element (region of the display) that will display different web components or cloned light DOM fragments imported from files.
However, I'm unable to redisplay ordinary HTML DOM once a shadow DOM has been added because I don't know how to remove the shadow root. Once created, the shadow root remains and interferes with the rendering of ordinary DOM. (I've looked at various W3C specs such as intro to web components, shadow DOM, templates, Bidelman's articles on HTML5 Rocks, etc.) I've isolated the problem in a simple example below:
Click "show plain old div"; click "show shadowed template"; click "show plain old div". Inspect  in devtools after each click. After the third click, there is no output below the buttons and in devtools I am seeing:

  #document-fragment

Plain old div

What do I need to add to removeShadow() to remove the shadow root and fully reset the content element to its initial state?
removing_shadows.html
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>

  <template id="shadowedTemplateComponent">

template

  </template>

  <template id="plainDiv">

Plain old div

  </template>

  <input type="button" value="show plain old div" onclick="showPlainOldDiv()"/>
  <input type="button" value="show shadowed template" onclick="showShadowTemplate()"/>

A:

The spec of Shadow DOM moved from v0 to v1.
One of the changes is that in v1 there is no way to create shadow root on itself and the host element may contain only one shadow root.
So it seems like the answer of replacing the shadow root with a new blank shadow root is not valid anymore.
Solution paths:

if the host element self (div in your example) has no special value beside holding that Shadow DOM, one can just replace the host element as a whole
if one still likes to preserve the host, clearing the Shadow DOM with something like e.shadowRoot.innerHTML = '' might be sufficient

A:

You can't remove a shadow root once you add it.  However, you can replace it with a newer one.
As mentioned here, http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-301/, the newest shadow root "wins" and becomes the rendered root.
You can replace your shadow root with a new shadow root that only contains the <content> pseudo-element to insert everything from the light DOM back into the shadow DOM.  At that point, as far as I know it will be functionally equivalent to having no shadow DOM at all.


Q:

Proving by contradiction that if $a\in\mathbb Q,b\in \mathbb R\setminus \mathbb Q$ then $a+b\in \mathbb R \setminus \mathbb Q$

I'm trying to prove by contradiction that if $a\in\mathbb Q,b\in \mathbb R\setminus \mathbb Q$ then $a+b\in \mathbb R \setminus \mathbb Q$, I already proved it with contra position and a direct proof seems impossible.
Suppose $a\in\mathbb Q,b\in \mathbb R\setminus \mathbb Q$ show that $a+b\in \mathbb Q$.
So $a=\frac p q, p,q\in \mathbb Z,q\neq 0$, so we have $\frac p q+b=\frac {p+bq}q$ and now I'm basically back to square one since I can't assume that a sum and product of integers and irrationals isn't an integer.

A:

To put it simply, you only need to use that the sum of rationals is again a rational. If $a+b \in \Bbb Q$, you would get that $b = (a+b) - a$ would be a rational, contradiction.

A:

Or if this isn't correct (by contradiction) then let $f_a:\mathbb R \setminus \mathbb Q\to \mathbb Q$ with $f_a(b)=a+b$. Then $f_a$ is $1-1$ which is wrong because $\mathbb Q$ is countable.

A:

Your problem is a misunderstanding of the technique of proof by contradiction.
When performing a proof by contradiction, you make your usual assumptions (e.g., $a\in\mathbb Q, b\in\mathbb R\setminus \mathbb Q$) and you assume the logical negation of what you're trying to prove (e.g., $a+b\in\mathbb Q$).
Per your description, it looks like you made your usual assumptions, and then tried to prove the logical negation of what you were trying to prove; that is impossible to do.


Q:

magento set the value of an attribute

I have created a new attribute serial number for all the products. Now I don't know how to set its value when order is completed. I know where to change it but I don't have the function. Here is the code. The new attribute have the code "serial_number".
if($status == 'complete'){

    foreach ($this->getAllItems() as $item) {
      // Here I want to update the value, I am sure something like the following will work.
      $this->setAttribute($item, 'serial_number', '123');

}
}

Also what should be the settings for it in admin. I am changing the value when the status for the order is changed to complete.

A:

here's how you do it differently: (color = attribute name, red = attribute value_id)
Let's start assuming you already have $product available.
$attr = $product->getResource()->getAttribute('color');
if ($attr->usesSource()) {
$avid = $attr->getSource()->getOptionId('red');
$product->setData('color', $avid);
$product->save();
}

A:

You seem to be setting the attribute, but where is the code to save() the item to the db
if($status == 'complete'){
    foreach ($this->getAllItems() as $item) {
         $item->setSerialNumber('123');
         $item->save()
     }
}


Q:

Export HTML Table to Excel with ID or class tags in the table header

I have a table in HTML on my webpage, and when using JQuery to export it to Excel, it will not work if I have any id or class tags in the table header.
the JQuery i am using is
//wont work unless the table has no class or id
$("#btnExport").click(function (e) {
window.open('data:application/vnd.ms-excel,' + $("#tableForExcel").html());
e.preventDefault();
});

The table I am using is

Report Manager
Report Detail
Form

I would be grateful if you could help me \ show me how i should adjust my code to get this to export.

A:

I've solved the problem this way:
$("#btnExport").click(function (e) {
    window.open('data:application/vnd.ms-excel,' +'
' +$("#SearchTable").html()+ '
');
    e.preventDefault();
});

I hope it helps you.


Q:

Estimation of Location of First Acoustic Peak

This question is inspired by the page at NED and references it throughout the question.
On the linked page there is a method for calculating the location of the first acoustic peak of the CMB. It involves calculating the distance to the surface of last scattering.
The expression they have for calculating this is
$$d_{sls} = \frac{c}{H_0 \sqrt{\Omega_m} (1+z_{sls})}\int_{0}^{z_{sls}} [\Omega_m(1+z)^3+\Omega_\Lambda]^{-1/2} dz$$
Where $\Omega_m = .3$ is the current mass density, $\Omega_\Delta = .7$ is the current dark energy density, and $z_{sls} = 1100$ is the redshift at the surface of last scattering.
They then calculate the integral by estimating it as a binomial expansion. As a result, they calculate (and I verified) that
$$\int_{0}^{z_{sls}} [\Omega_m(1+z)^3+\Omega_\Lambda]^{-1/2} dz \approx 1.21$$
And as a result, they calculate $l \approx 200$.
However, if I plug this integral into Wolfram Alpha, I get
$$\int_{0}^{z_{sls}} [\Omega_m(1+z)^3+\Omega_\Lambda]^{-1/2} dz \approx 3.19$$
And as a result, I calculate $l \approx 500$.
Given that $l \approx 200$ has been measured by the Planck satellite, this is a huge discrepancy! I have two questions:

Is there something about Wolfram Alpha that would given a bad approximation to this integral? Is it possible that the binomial approximation method gives a more accurate result?
If not, then why is such a bad approximation used in the calculation and accepted as accurate?

Apologies if this is not clear. At the end of the day, I'm trying to understand this calculation better and anything that helps me do so would be appreciated.
Thank you!

A:

The webpage you linked to is remarkable, to say the least. It contains a whole chain of errors, producing a wrong result that the authors mistakenly interpret as accurate. Based on what I've seen on that page alone, I wouldn't trust anything else from that article.
So, first of all, Wolfram Alpha is correct, and I applaud you for checking their calculations. I should point out that
$$
d_{sls} = \frac{c}{H_0\,(1+z_L)}\int_0^{z_L}\left[\Omega_{m,0}(1+z)^3 + \Omega_{\Lambda,0}\right]^{-1/2}\,\text{d}z,
$$
so in your question you've put an extra $\sqrt{\Omega_{m,0}}$ in the denominator, which shouldn't be there.
Let's see where things go wrong:
The most glaring mistake is the step from (55) to (56):
$$
\begin{align}
d_{sls} &= \frac{2c}{7H_0(1+z_L)}\left[7\,\Omega_{m,0}^{-1/2} - 2\,\Omega^{\vphantom{1/2}}_{\Lambda,0}\,\Omega_{m,0}^{-3/2} + \mathcal{O}\left((1+z_L)^{-1/2}\right)\right]\\
&\approx \frac{2c}{7H_0(1+z_L)}\left[9\,\Omega_{m,0}^{-1/2} -2\,\Omega_{m,0}^{-3/2}\right] = \frac{2c\,\Omega_{m,0}^{-1/2}}{7H_0(1+z_L)}\left[9 -2\,\Omega_{m,0}^{-1}\right].
\end{align}
$$
So there's a $\Omega_{m,0}^{-1}$ term instead of $\Omega_{m,0}^3$. As a result, $d_{sls}/r_s \approx 60$ instead of $221$.
The second mistake is that (55) itself is wrong. The binomial expansion of the integrand in $d_{sls}$ is only accurate for large values of $z$, but the integration is taken over the entire range $[0,z_L]$, and depends crucially on the value of the primitive function in $z=0$. This is why this approximation is so different from the correct numerical calculation with Wolfram Alpha. If you insert the correct value, you should get $d_{sls}/r_s \approx 149$ (and not $300$, because of the $\sqrt{\Omega_{m,0}}$ you added).
But the problems don't stop there. The calculation of the sound horizon $r_s$ is also wrong. Equation (47) should be
$$
r_s = a_L\int_0^{t_L}\frac{c_s}{a(t)}\,\text{d}t.
$$
Using (49) and the convention $a_0 = 1$, this can be written as
$$
r_s = \frac{a_L}{H_0}\int_0^{a_L}\frac{c_s\,\text{d}a}{\sqrt{\Omega_{r,0}
+ \Omega_{m,0}\,a + \Omega_{k,0}\,a^2 + \Omega_{\Lambda,0}\,a^4}}.
$$
The authors then make the assumption that the speed of sound $c_s$ remains roughly constant and that the matter term is dominant, such that all other terms can be ignored. This then leads to
$$
r_s \approx \frac{c_s\,a_L}{H_0\sqrt{\Omega_{m,0}}}\int_0^{a_L}a^{-1/2}\,\text{d}a = \frac{2\,c_s}{H_0\sqrt{\Omega_{m,0}}}a_L^{3/2} = \frac{2\,c_s}{H_0\sqrt{\Omega_{m,0}}}(1+z_L)^{-3/2},
$$
so there is a factor $3$ wrong in (53). However, this is also a poor approximation, because the radiation term $\Omega_{r,0}$ is quite significant in the early universe. A better approximation is therefore
$$
\begin{align}
r_s &\approx \frac{c_s\,a_L}{H_0}\int_0^{a_L}\frac{\text{d}a}{\sqrt{\Omega_{r,0}
+ \Omega_{m,0}\,a}}\\
&= \frac{2\,c_s}{H_0\,\Omega_{m,0}}(1+z_L)^{-1}\left[\sqrt{\Omega_{r,0} + \Omega_{m,0}\,(1+z_L)^{-1}} - \sqrt{\Omega_{r,0}}\,\right].
\end{align}
$$
Using the value $\Omega_{r,0}\approx 9\times 10^{-5}$, this leads to $d_{sls}/r_s \approx 86$. A full calculation with non-constant $c_s$, which I won't derive here, gives $d_{sls}/r_s \approx 96$.
Finally, a first-order approximation to the position of the first acoustic peak is not given by $d_{sls}/r_s$, but by $\pi d_{sls}/r_s$, and we find  $\pi 96 \approx 300$. As you see, this is still not very close to the actual value of $\approx 220$. The reason for this is that the low-order acoustic peaks are significantly influenced by the propagation of the density fluctuations and by gravitational redshift effects in the early universe. The full treatment of these is very complex, and for specialists only (which I'm not, by the way).
I don't think I've ever seen a website that looks professional, yet is so wrong on so many levels. My advice would be to find a better course. For instance, Weinberg's cosmology textbook has everything you need, but it's no easy read.


Q:

Bootstrap responsiveness aligning to left instead of middle

Here's my html:

                Test Title

Currently there is no css for the gridrow,eventsrow,or gridcard and eventcard and event.
When I look at it on my Samsung Note8 everything looks great (its centered), however when I look at it on my Samsung Galaxy s8 it pushes to the left instead of centering.
What is the issue?

A:

your problem is that you use float left,  this will push your div element to the left and not in the middle. you can try to center your element with
text-align
.gridcard
{
text-align:center;
width:100%;
height:100%;
margin-bottom:0.5rem;
background-color:white;
}

i hope this will solve your problem


Q:

Why I'm getting null exception on the Load/Save buttons?

If I click on the "Save Conversations" or the "Load Conversations" button the variable _conversationTrigger is null.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomEditor(typeof(ConversationTrigger))]
public class ConversationTriggerEditor : Editor
{
    private ConversationTrigger _conversationTrigger;

    [SerializeField] private ReorderableList conversationsList;

    private SerializedProperty _conversations;

    private int _currentlySelectedConversationIndex = -1;
    private int newSize = 0;
    private Vector2 scrollPos;

    private readonly Dictionary<string, ReorderableList> _dialoguesListDict = new Dictionary<string, ReorderableList>();
    private readonly Dictionary<string, ReorderableList> _sentencesListDict = new Dictionary<string, ReorderableList>();

    public override void OnInspectorGUI()
    {
        if (GUILayout.Button("Edit Conversations"))
        {
            ConversationsEditorWindow myWindow = CreateInstance<ConversationsEditorWindow>();

            myWindow.minSize = new Vector2(1500, 900);
            myWindow.maxSize = new Vector2(1500, 900);
            myWindow.Init(serializedObject);

        }

        if (GUILayout.Button("Save Conversations"))
        {
            _conversationTrigger.SaveConversations();
        }

        if (GUILayout.Button("Load Conversations"))
        {
            Undo.RecordObject(_conversationTrigger, "Loaded conversations from JSON");
            _conversationTrigger.LoadConversations();
        }
    }
}

And the top of the ConversationsEdiotrWindow script the script is much longer. This is where I'm using the Init method to init the _conversationTrigger :
When using break point on the _conversationTrigger in the ConversationsEdiotrWindow it's fine but in the ConversationTriggerEditor script it's null.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

public class ConversationsEditorWindow : EditorWindow
{
    public SerializedObject conversation = null;

    private ConversationTrigger _conversationTrigger;

    [SerializeField] private ReorderableList conversationsList;

    private SerializedProperty _conversations;

    private int _currentlySelectedConversationIndex = -1;
    private int newSize = 0;
    private Vector2 scrollPos;

    private readonly Dictionary<string, ReorderableList> _dialoguesListDict = new Dictionary<string, ReorderableList>();
    private readonly Dictionary<string, ReorderableList> _sentencesListDict = new Dictionary<string, ReorderableList>();

    private SerializedObject itemcopy;
    private string searchString = "";

    public void Init(SerializedObject _item)
    {
        // Copy the Item targetObject to not lose reference when you
        // click another element on the project window.
        itemcopy = new SerializedObject(_item.targetObject);
        conversation = itemcopy;

        // Other things to initialize the window

        const int width = 1500;
        const int height = 900;

        var x = (Screen.currentResolution.width - width) / 2;
        var y = (Screen.currentResolution.height - height) / 2;

        var window = GetWindow<ConversationsEditorWindow>();
        window.position = new Rect(x, y, width, height);

        _conversationTrigger = (ConversationTrigger)_item.targetObject;
        _conversations = itemcopy.FindProperty("conversations");

A:

You have two different objects of type ConverstationTrigger in two different places. One is instantiated in ConverstationsEditorWindow while the other is null because there is no assignment in ConversationTriggerEditor.
By the looks of it, you want to use only one ConverstationTrigger. Perhaps there is a solution where you can inject the instance of ConverstationTrigger into the places you need it via the a constructor of some sort.


Q:

Update / save / display values in a table

I am relatively new to Angular and need to put together an application to update / save / display values. The code is working, but I wanted your input the make sure that I am doing this 'the angular way'.
JavaScript
var app = angular.module('store', []);

app.controller('TableController', ['$scope', '$log',function($scope, $log){
   $scope.family = familyMembers;

   $scope.SaveMember = function() {
       var saveMember = { name: $scope.name, age: $scope.age };
       if ($scope.editItem == -1) {
            $scope.family.push(saveMember);
            // insert in db here
       }
       else {
           $scope.family[$scope.editItem] = saveMember;
           $scope.editItem = -1;
           // update db here
       }
       Init();
   };

   $scope.DeleteMember = function(idx) {
       $scope.family.splice(idx,1);
       // delete from db here
   }

   $scope.EditMember = function(idx){
       $scope.name = $scope.family[idx].name;
       $scope.age = $scope.family[idx].age;
       $scope.editItem = idx;
       $scope.buttonText = 'Update';
   }

   function Init() {
        $scope.name = '';
        $scope.age = '';
        $scope.editItem = -1;
        $scope.buttonText = 'Add new';
   }

   Init();

}]);

var familyMembers = [
    { name: "Joe", age: 42}
    , { name: "Jane", age: 40}
    , { name: "Bob", age: 13}
];

HTML

        <link href="./css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Family Members:

                    {{p.name}}
                    {{p.age}}
                    X

Add member

            name

            <input type="text" ng-model="name">

            age

            <input type="number" ng-model="age">

            <input type="button" value="{{buttonText}}" ng-click="SaveMember()" />

A:

Yup, looks like The Angular Way™. A good rule of thumb for controllers is that 1) it exposes data, 2) it exposes functionality, 3) not tied to any specific template. There's a few things though.
var familyMembers = [
    { name: "Joe", age: 42}
    , { name: "Jane", age: 40}
    , { name: "Bob", age: 13}
];

Why is this outside the controller? Why not define it inside? If you want it defined separately from the controller, consider using a provider/service/factory to store it. Then pull that provider/service/factory into the controller as a dependency.
Init isn't really some initialization. It's resetting your form data. A better way to do this, instead of emptying the object values, is to create a function that returns a blank version of the object and replace the form data.
function createMember(){
  return { name: '', age: '' };
}

function resetForm(){
  $scope.formData = createMember();
}

// Assuming the form uses `$scope.formData` as the form object

As for saving, before you reset, you just copy the form data using angular.copy and pop it in the members array. This way, the object you put in the array isn't the same object referenced by the form data, which may still be subject to binding. Then you reset the form data.
function saveForm(){
  var newMember = angular.copy($scope.formData);
  members.push(newMember);
  resetForm();
}


Q:

How to make worker carry multiple resources?

I want to make a rather simple (?) change: I would like Probes (or other workers) to be able to carry multiple minerals at the same time. I would expect the probe to:

approach the mineral field
gather minerals
gather minerals again
... and again...
and then carry it back to the base

Originally I thought it is a simple data change of the worker:
I thought it could be simple as changing the behavior Carry Mineral Field Minerals->(Basic) Stats; Maximum Stack Count from 1 to 5.
Unfortunately, as soon as a probe gathers the minerals, it automatically returns.
After giving it more thought I figured there may be some built-in trigger, checking if the worker is already carrying minerals - and if that is so - issuing a "Return" order.
Since then I have been digging into available triggers, scripts, unpacking Liberty and Swarm mods, but so far - I could find nothing.
Any ideas? Pointers?
I am new to modding and I don't plan to do anything big. Just want to hack this for some experimentation...
I know how to increase gather time and how to make probe just carry more minerals in a single patch... but I want to specifically make the probe retrigger the gathering multiple times before it returns (and add some delay in between)
Also, I don't care what happens when mixing minerals with gas or any other resource.

A:

Following the idea of user1337 I came with the following idea:

When a worker is harvesting, remember which mineral field it did it from
When a worker finished harvesting, remove its cargo and repeat the harvesting order, for the same mineral field, again.
Have a "stack count" remembering how many times the above point occured. When a threshold is reached, allow the unit to return normally.
The amount of returned minerals should be multiplied by the amount of stack count.

The first point is to remember, in the unit, which mineral field it is gathering from. The information will be used later when returning. See the question/answer Probe returning: From which mineral field it gathered resources? and Custom variables/fields for units?
(Trigger) onStartGettingResources
Events
    TriggerAddEventUnitAbility(null, "ProbeHarvest", 0, c_abilHarvestStageHarvest, false)
    TriggerAddEventUnitAbility(null, "DroneHarvest", 0, c_abilHarvestStageHarvest, false)
    TriggerAddEventUnitAbility(null, "SCVHarvest", 0, c_abilHarvestStageHarvest, false)
Local Variables
    minerals <unit>
        EventUnitTargetUnit()
Actions
    StoreUnitWithUnit(EventUnit(), "miningFrom", minerals) //custom function for custom "fields" in a unit

The second trigger should occur when a worker finished harvesting. Experiments have shown it is best triggered by change of the unit behavior triggered when it started carrying minerals. Triggering it on ability stage ApproachDropOff causes short animation stuttering.
(Trigger) onProbeGetResources
Events
    TriggerAddEventUnitBehaviorChange(null, "CarryMineralFieldMinerals", c_unitBehaviorChangeActivate)
Conditions
    Comparison(UnitGetType(EventUnit()), ==, "Probe")
Actions
    GatherResourcesStack("ProbeHarvest", 0) //custom function, see below

.... //Similar triggers for SCV and Drone

(Global variable) g_gatherStackCount <constant int>
    4

(Action definition) GatherResourcesStack
Parameters
    gatherCommand <Ability Command - Unit>
Local Variables
    mineralPatch <unit>
        GetUnitWithUnit(EventUnit(), "miningFrom")
    stackCount <int>
        GetIntWithUnit(EventUnit(), "minigStackCount")
Actions
    SetVariable(stackCount, ArithmeticInt(stackCount, +, 1))
    IfThenElse()
        if
            Comparison(stackCount, <, g_gatherStackCount)
        then
            UnitSetPropertyFixed(EventUnit(), c_unitPropCarriedMinerals, 0.0)
            StoreIntWithUnit(EventUnit(), "miningStackCount", stackCount)
            UnitBehaviorRemove(EventUnit(), "CarryMineralFieldMinerals", 1)
            UnitIssueOrder(EventUnit(), OrderTargetingUnit(gatherCommand, mineralPatch), c_orderQueueReplace)
        else
            StoreIntWithUnit(EventUnit(), "miningStackCount", 0)
            UnitSetPropertyFixed(EventUnit(), c_unitPropCarriedMinerals,
                ArithmeticReal(
                    UnitGetPropertyFixed(EventUnit(), c_unitPropCarriedMinerals, c_unitPropCurrent),
                    *, g_gatherStackCount
                )
            )


Q:

How to specify the GCP Credential Location in application.properties file (for using the Pub/Sub in GCP)?

This seems straightforward to do that passing the Service Account key file (generated from the GCP console) by specifying the file location in the application.properties file. However, I tried all the following options:
1. spring.cloud.gcp.credentials.location=file:/home/my_user_id/mp6key.json
2. spring.cloud.gcp.credentials.location=file:src/main/resources/mp6key.json
3. spring.cloud.gcp.credentials.location=file:./main/resources/mp6key.json
4. spring.cloud.gcp.credentials.location=file:/src/main/resources/mp6key.json

It all ended up with the same error:
java.io.FileNotFoundException: /home/my_user_id/mp6key.json (No such file or directory)

Could anyone advise where I should put the key file and then how should I specify the path to the file properly?
The same programs run successfully in Ecplise with messages published and subscribed using the Pub/Sub processing from GCP (using the Project Id/Service Account key generated in GCP), but now stuck with the above issue after deployed to run on GCP.

A:

Have you tried to follow this quickstart? Please, try to follow it thoughtfully and explain if you get any error finishing the quickstart.
Anyway, before running your Java script, try running on the console the following (please modify with the exact path where you store your key:
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/mp6key.json"

How are you authenticating your credentials in your Java script?


Q:

Grails - How to change project's Grails version in Spring Tool Suite 3.5.1

In Spring Tool Suite 3.5.1.Release , how do I set a project-specific Grails version?
I have multiple versions of Grails configured in STS.
Older versions of STS had a section called Grails in the "Properties for project" window where a particular version of Grails could be selected.
After upgrading to 3.5.1.Release I no longer see this option.
Thanks!

A:

Since GGTS version 3.5.0 the Grails version GGTS uses now always follows the application.properties file in your project. So just change the grails version number in that file.
You may need to do some other things to actually upgrade your project to work with that newer version of Grails of course.


Q:

Ruby post title to slug

How should I convert a post title to a slug in Ruby?
The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow any other characters?).
So basically:

downcase all letters
convert spaces to hyphens
delete extraneous characters

A:

Is this Rails? (works in Sinatra)
string.parameterize

That's it. For even more sophisticated slugging, see ActsAsUrl. It can do the following:
"rock & roll".to_url => "rock-and-roll"
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"

A:

slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')

downcase makes it lowercase. The strip makes sure there is no leading or trailing whitespace. The first gsub replaces spaces with hyphens. The second gsub removes all non-alpha non-dash non-underscore characters (note that this set is very close to \W but includes the dash as well, which is why it's spelled out here).

A:

to_slug is a great Rails plugin that handles pretty much everything, including funky characters, but its implementation is very simple. Chuck it onto String and you'll be sorted. Here's the source condensed down:
String.class_eval do
  def to_slug
    value = self.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n, '').to_s
    value.gsub!(/[']+/, '')
    value.gsub!(/\W+/, ' ')
    value.strip!
    value.downcase!
    value.gsub!(' ', '-')
    value
  end
end


Q:

ValueError: zero length field name in format in Python2.6.6

I use this python shell to generate a string:
>>>':'.join("{:x}\n".format(random.randint(0, 2**16 - 1)) for i in range(4))

When I run this shell in Python2.7.5, everything goes okay. But it occurs ValueError: zero length field name in format when Python version is 2.6.6. What should I run this shell fine when Python version is 2.6.6?

A:

In Python versions 2.6 or earlier, you need to explicitly number the format fields:
':'.join("{0:x}\n".format(random.randint(0, 2**16 - 1)) for i in range(4))
#          ^

You can read about this in the docs:

Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.


Q:

JQuery adding support for different value names

I would like the below script to accept the value color in another language. How do I change the script to accept the field-value of '5f01264e722ae' and change it to the associated predetermined css value? i.e. input value is midnightblue and change it to css value blue.
Thank you for your help.

A:

Color like this

jQuery(document).ready(function($) {

    var fieldId = "5f0124e773aa8";
    var defaultText = "my name";

    if(!jQuery('input[data-field-id="'+fieldId+'"]').length)
        return;

    var $el = jQuery('
').html(defaultText);
    $el.appendTo(jQuery('.woocommerce-product-gallery--with-images'));

    jQuery(document).on('change keyup','input[data-field-id="'+fieldId+'"]',function(){
        var v = jQuery(this).val() || defaultText;
        jQuery('.sw_poster_text2').html(v);

    }).trigger('change');
    $("select[data-field-id='5f01264e722ae']").change(function() {
        var color = $(this).find('option:selected').data('wapf-label');
        if(color == 'midnightblue')
            color = 'blue';
        $(".sw_poster_text2").css("color", color);
    });
});

<form>
<input data-field-id="5f0124e773aa8" />
<select data-field-id="5f01264e722ae">
<option data-wapf-label="black">Black</option>
<option data-wapf-label="red">Red</option>
<option data-wapf-label="yellow">Yellow</option>
<option data-wapf-label="midnightblue">Midnight Blue</option>
</select>

</form>


Q:

PHP message on the same page

Hi I have something similar in my code;

<title></title>

<form method="post" action="processMaster.php">
<input type="submit" id="testOne" name="testOne" value="Process me">
</form>

the processMaster.php reads as follows;
<?php
echo "Boom!";
?>

Now that this works fine.
But my issue is once the "Boom!" appears, it appear in a separate page(or in a page where all the other elements of the page is not displayed.)
Is there a possibility/workaround that I can print the message on the same page where I can also see the Process me button too visible?

A:

processMaster.php should contain the following:

<title></title>

<form method="post" action="processMaster.php">
<input type="submit" id="testOne" name="testOne" value="Process me">
</form>
<?php
if($_POST['testOne'] != NULL){
  echo "Boom!"'
}
?>


Q:

Extract number (dash included) from string using regex in Python

Hello and thanks for helping.
String examples:
"Hello 43543"      ---> "43543"
"John Doe 434-234" ---> "434-234"
I need a regex to extract the examples on the right.

A:

I would do it following way:
import re
pattern = r'\d[0-9\-]*'
number1 = re.findall(pattern,'Hello 43543')
number2 = re.findall(pattern,'John Doe 434-234')
print(number1[0]) #43543
print(number2[0]) #434-234

My solution assumes that you are looking for any string starting with digit and with all other characters being digit or -, this mean it will also grab for example 4--- or 9-2-4--- and so on, however this might be not issue in your use case.
I want to note that before writing pattern, you should answer question: what it should match exactly? My pattern works as intended for examples you given, but keep in mind that this do NOT automatically mean it would give desired output with all data you might want to process using it.


Q:

Hourly, Daily, Monthly Helper+Model methods

I have a web portal, parsing the API, to a web URL, where it goes through JSON.
This data is configured using Charts and we are currently using flot.js
The code for the hourlyData is already there and gets plugged into the json charts.
I'm trying to recreate this for Monthly and Yearly.
The current code for hourlyData looks like this:
  List<dynamic> hourlyData = new List<dynamic>();
            DateTime hourIterator = StartDate.Value;
            while (hourIterator.Hour <= ddvm.CurrentHour)
            {
                if (ddvm.HourlyPaymentTotal != null && ddvm.HourlyPaymentTotal.Count() > 0 )
                {
                    HourlyPaymentTotalModel hour = ddvm.HourlyPaymentTotal.FirstOrDefault(hpt => hpt.DateTimeStamp == hourIterator);
                    if (hour == null) { hour = new HourlyPaymentTotalModel() { DateTimeStamp = hourIterator }; };
                    hourlyData.Add(new List<dynamic> {hourIterator.Hour,
                                                        hour.Amount,
                                                        new { tooltip = String.Format("{0} : {1}", hour.Count, hour.Amount.ToString("C")) } });
                }
                hourIterator = hourIterator.AddHours(1);
            }

            ddvm.GraphData.LineChart_HourlyTotal.Add(new
            {
                data = hourlyData,
                color = "#A1345E",
                label = "Total Amount Paid"
            });

How can I recreate hourlyData into  monthlyData and yearlyData?
Edit:
    public class HourlyPaymentTotalModel : ViewModelBase
    {
        public int Hour
        {
            get { return DateTimeStamp.Hour; }
            set { DateTimeStamp  = new DateTime(1, 1, 1, value, 0, 0); }
        }
        public string FormattedHour
        {
            get { return DateTimeStamp.ToShortTimeString().Replace(":00 ", ""); }
            set { DateTimeStamp = DateTime.Parse(value); }
        }
        public DateTime DateTimeStamp { get; set; }
        public decimal Amount { get; set; }
        public int Count { get; set; }
    }
}

This is from the API solution:
public IQueryable<PaymentSummary> GetHourlyPaymentTotals(DateTime startDate, DateTime endDate, string PaymentProcessor = null, string merchantID=null)
        {
            transactionRepository = GetTransactionRepository(PaymentProcessor);
            IQueryable<IPayment> allPayments = transactionRepository.GetAllPayments(startDate, endDate, merchantID);
            var retVal = from ap in allPayments
                         group ap by new
                         {
                             PaymentDateYear = ap.PaymentDate.Value.Year,
                             PaymentDateMonth = ap.PaymentDate.Value.Month,
                             PaymentDateDay = ap.PaymentDate.Value.Day,
                             PaymentDateHour = ap.PaymentDate.Value.Hour
                         }
                             into grp_ap
                             select (new
                             {
                                 PaymentDateString = grp_ap.Key.PaymentDateMonth.ToString() + "/" + grp_ap.Key.PaymentDateDay.ToString() + "/" + grp_ap.Key.PaymentDateYear.ToString() + " " + grp_ap.Key.PaymentDateHour + ":00",
                                 Amount = grp_ap.Sum(grp => grp.Amount),
                                 Count = grp_ap.Count()
                             });
            return (IQueryable<PaymentSummary>)retVal.ToList().Select(p => new PaymentSummary()
            {
                PaymentDate = (DateTime?)DateTime.Parse(p.PaymentDateString),
                Amount = p.Amount,
                Count = p.Count
            }).ToList().AsQueryable();
        }

Update:  I created more models based on the solution Mairaj Ahmad proposed.
This is using the dailyData model.
I'm still not sure why the <canvas> is showing a blank under my chart fields.
This is probably an error with the data or the flot.js options made to the specified charts.
var  area_chart_payment_by_day_options = {
        series: {
            lines: {
                show: true,
                fill: .5
            },
            points: { show: true }
        },
        grid: {
            borderWidth: 0,
            hoverable: true
        },
        tooltip: true,
        tooltipOpts: {
            content: "%x : $ %y"
        },
        xaxis: {
            //mode: "categories",
            tickDecimals: 0,
            min:1,
            max:31
        },
        yaxis: {
            tickFormatter: function (y) { return "$ " + y + " "; },
            tickDecimals:0
        }
    }

data function
 $(function () {
            var data = [];
            @Html.Raw("data = " + Json.Encode(Model.GraphData.LineChart_DailyTotal) + ";");   //TODO: LineChart_Daily
            $.plot($("#area_chart_payment_by_day"), area_chart_payment_by_day,

update function
$.plot($("#area_chart_payment_by_day"), area_chart_payment_by_day, area_chart_payment_by_day_options);

A:

You can create daily,monthly and yearly data by using the same logic. You just have to replace Hour with Day,Month or Year.
List<dynamic> dailyData = new List<dynamic>();
        DateTime dayIterator = StartDate.Value;
        while (dayIterator.Hour <= ddvm.CurrentDay)
        {
            if (ddvm.DailyPaymentTotal != null && ddvm.DailyPaymentTotal.Count() > 0 )
            {
                DailyPaymentTotalModel day = ddvm.DailyPaymentTotal.FirstOrDefault(hpt => hpt.DateTimeStamp == dayIterator);
                if (day == null) { hour = new DailyPaymentTotalModel() { DateTimeStamp = dayIterator }; };
                dailyData.Add(new List<dynamic> {dayIterator.Day,
                                                    day.Amount,
                                                    new { tooltip = String.Format("{0} : {1}", day.Count, day.Amount.ToString("C")) } });
            }
            dayIterator = dayIterator.AddDays(1);
        }

        ddvm.GraphData.LineChart_DailyTotal.Add(new
        {
            data = dailyData,
            color = "#A1345E",
            label = "Total Amount Paid"
        });

And this will be your DailyModel.
public class DailyPaymentTotalModel : ViewModelBase
{
    public int Day
    {
        get { return DateTimeStamp.Day; }
        set { DateTimeStamp  = new DateTime(1, 1, value, 0, 0, 0); }
    }

    public DateTime DateTimeStamp { get; set; }
    public decimal Amount { get; set; }
    public int Count { get; set; }
}

}
And you data fetching logic looks to be in this function you need to make changes in it accordingly to make it work with day,month,year
transactionRepository.GetAllPayments(startDate, endDate, merchantID);