问:
ILMerge assembly with spaces
I'm trying to use ILMerge to create a single executable to distribute and I'm having some difficulty because my application has spaces in the filename.  It appears that ILMerge uses a space a delimiter to specify multiple input assemblies.  This means there are assemblies that it can't find (because they don't exist obviously) but I'm been unable to find any combination of quotes and double-quotes to tell ILMerge to ignore the spaces.

Command Line Input:

```<code>/out:bin\Debug\My Application.exe /targetplatform:v4,"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5" "obj\Debug\My Application.exe" "C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Newtonsoft.Json.dll" "C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Renci.SshNet.dll" /log"
</code>```

Command Line Output:

```<code>The list of input assemblies is:
    My
    Application.exe
    obj\Debug\My Application.exe
    C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Newtonsoft.Json.dll
    C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Renci.SshNet.dll
Could not find the file 'My'.
An exception occurred during merging:
ILMerge.Merge: Could not find the file 'My'.
   at ILMerging.ILMerge.Merge()
   at ILMerging.ILMerge.Main(String[] args)
</code>```

Any help anybody can provide would be greatly appreciated.

答:
have you tried quoting it like the rest of the command line parameters with spaces?

i.e.: /out:"bin\Debug\My Application.exe" /targetplatform:v4,"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5" "obj\Debug\My Application.exe" "C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Newtonsoft.Json.dll" "C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Renci.SshNet.dll" /log"

Title: ILMerge assembly with spaces

Body:
I'm trying to use ILMerge to create a single executable to distribute and I'm having some difficulty because my application has spaces in the filename.  It appears that ILMerge uses a space a delimiter to specify multiple input assemblies.  This means there are assemblies that it can't find (because they don't exist obviously) but I'm been unable to find any combination of quotes and double-quotes to tell ILMerge to ignore the spaces.

Command Line Input:

/out:bin\Debug\My Application.exe /targetplatform:v4,"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5" "obj\Debug\My Application.exe" "C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Newtonsoft.Json.dll" "C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Renci.SshNet.dll" /log"

Command Line Output:

The list of input assemblies is:
    My
    Application.exe
    obj\Debug\My Application.exe
    C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Newtonsoft.Json.dll
    C:\Users\Username\source\repos\CompanyInternal\My Application\My Application\Renci.SshNet.dll
Could not find the file 'My'.
An exception occurred during merging:
ILMerge.Merge: Could not find the file 'My'.
   at ILMerging.ILMerge.Merge()
   at ILMerging.ILMerge.Main(String[] args)

Any help anybody can provide would be greatly appreciated.


来源: stackexchange

问:
How can I build my c# class library along with the reference?
I'm creating a basic class library that heavily wraps another DLL reference. I'm trying to build a DLL but it seems to not include the reference.

Is there a way I can build and package the my entire solution in a DLL along with the reference DLL?

答:
I figured this out. I use ilmerge by microsoft (https://www.microsoft.com/en-us/download/details.aspx?id=17630) to merge my DLLs into a single DLL file.

Just go thru the following and you'll have the merged DLL.

Step 1: Install ilmerge and put it on your system classpath
Step 2:

```<code>ilmerge /out:MergedDLLName.dll /closed DLL1.dll DLL2.dll DLL3.dll
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I figured this out. I use ilmerge by microsoft (https://www.microsoft.com/en-us/download/details.aspx?id=17630) to merge my DLLs into a single DLL file.

Just go thru the following and you'll have the merged DLL.

Step 1: Install ilmerge and put it on your system classpath
Step 2:

ilmerge /out:MergedDLLName.dll /closed DLL1.dll DLL2.dll DLL3.dll

Hope this helps.


问:
Auto.Arima with Daily Sales - Univariate Time Series Error
I'm working with a data set from 2017-01-01 to 2017-10-27, however, the auto.arima says it can only handle univariate time series, despite there being only daily data.

What am I missing?

Reproducible example:

```<code>set.seed(25)
datelist<-seq(as.Date("2016-01-01"),as.Date("2017-10-27"),by="day")
salesvals<-round(abs(rnorm(length(datelist)))*1000,digits=2)
salestbl<-data.frame(datelist,salesvals)

salesTS<-ts(salestbl,
            start=c(2016,as.numeric(format(salestbl$datelist, "%j"))),
            frequency=7)
fit <- auto.arima(salesTS)
</code>```

Error:

Error in auto.arima(salesTS) :
  auto.arima can only handle univariate time series

Overall, I know there's a weekly seasonality, hence the seven days. I know there's also a quarterly seasonality, but I can tackle that another time.

Overall I'm trying to get a forecast for 2017-12-31, using an arima forecast.

答:
The problem is that you are declaring the data.frame as time series wrong. Any way you dont need to do that just omit the ts part like this:

```<code>set.seed(25)
datelist<-seq(as.Date("2016-01-01"),as.Date("2017-10-27"),by="day")
salesvals<-round(abs(rnorm(length(datelist)))*1000,digits=2)
salestbl<-data.frame(datelist,salesvals)

fit <- auto.arima(salestbl[,2])
</code>```

just head(salesTS) and you will see why you get the error.

Body:
I'm working with a data set from 2017-01-01 to 2017-10-27, however, the auto.arima says it can only handle univariate time series, despite there being only daily data.

What am I missing?

Reproducible example:

set.seed(25)
datelist<-seq(as.Date("2016-01-01"),as.Date("2017-10-27"),by="day")
salesvals<-round(abs(rnorm(length(datelist)))*1000,digits=2)
salestbl<-data.frame(datelist,salesvals)

salesTS<-ts(salestbl,
            start=c(2016,as.numeric(format(salestbl$datelist, "%j"))),
            frequency=7)
fit <- auto.arima(salesTS)

Error:

Error in auto.arima(salesTS) :
  auto.arima can only handle univariate time series

Overall, I know there's a weekly seasonality, hence the seven days. I know there's also a quarterly seasonality, but I can tackle that another time.

Overall I'm trying to get a forecast for 2017-12-31, using an arima forecast.

Body:
The problem is that you are declaring the data.frame as time series wrong. Any way you dont need to do that just omit the ts part like this:

set.seed(25)
datelist<-seq(as.Date("2016-01-01"),as.Date("2017-10-27"),by="day")
salesvals<-round(abs(rnorm(length(datelist)))*1000,digits=2)
salestbl<-data.frame(datelist,salesvals)

fit <- auto.arima(salestbl[,2])

just head(salesTS) and you will see why you get the error.


问:
accessing an array in a component from the layout in yii2
I need to check the records in the notifications table at every page load of every controller.

So I wrote it in a component and the component is executed in the bootstraping process.

I need the notifications to be available in the layout so that i can show them in the notification menu.

below is what I have tried so far:

component:

```<code>namespace admin\components;

use Yii;
use yii\base\Component;
use admin\models\Notification;

class NotificationManager extends \yii\base\Component{
  public function init() {

    $notifications = Notification::find()->orderBy('id DESC')->asArray()->all();
    //echo "```"; print_r($notifications);exit;

    if(count($notifications)>0){
      foreach ($notifications as $notif) {
        if($notif['type'] == 'courier')
          $courier_notifications[] = $notif;
        elseif($notif['type'] == 'order')
          $order_notifications[] = $notif;
      }

      Yii::$app->view->params['courier_notifications'] = $courier_notifications;
      Yii::$app->view->params['order_notifications'] = $order_notifications;
    }
  }
}
```

<p>Layout:</p>

```$courier_notifications = $this->params['courier_notifications'];
```

I am not sure which part am I going wrong: in component or in the layout?
I appreciate your help.

答:
Im not sure why your component execution during bootstrap fails to add the value to params.But believe it to be an overkill.

You can rather move the logic to component method and access in layout whenever necessary

Component.

```<code>namespace admin\components;

use Yii;
use yii\base\Component;
use admin\models\Notification;

class NotificationManager extends Component{

  public function notifications($type = 'courier') {
     $notifications = Notification::find()
            ->where(['type' => $type])
            ->orderBy('id DESC')
            ->asArray()->all();
     return $notifications;
  }
}
</code>```

Add the component class under Components section in your config file

```<code>'notificationManager ' => [
        'class' => 'admin\components\NotificationManager'
 ]
</code>```

Layout

```<code>$courier_notifications = yii::$app->notificationManager->notifications('courier');
</code>```

Body:
I need to check the records in the notifications table at every page load of every controller.

So I wrote it in a component and the component is executed in the bootstraping process.

I need the notifications to be available in the layout so that i can show them in the notification menu.

below is what I have tried so far:

component:

namespace admin\components;

use Yii;
use yii\base\Component;
use admin\models\Notification;

class NotificationManager extends \yii\base\Component{
  public function init() {

    $notifications = Notification::find()->orderBy('id DESC')->asArray()->all();
    //echo "
"; print_r($notifications);exit;

    if(count($notifications)>0){
      foreach ($notifications as $notif) {
        if($notif['type'] == 'courier')
          $courier_notifications[] = $notif;
        elseif($notif['type'] == 'order')
          $order_notifications[] = $notif;
      }

      Yii::$app->view->params['courier_notifications'] = $courier_notifications;
      Yii::$app->view->params['order_notifications'] = $order_notifications;
    }
  }
}

Layout:

$courier_notifications = $this->params['courier_notifications'];

I am not sure which part am I going wrong: in component or in the layout?
I appreciate your help.

Body:
Im not sure why your component execution during bootstrap fails to add the value to params.But believe it to be an overkill.

You can rather move the logic to component method and access in layout whenever necessary

Component.

namespace admin\components;

use Yii;
use yii\base\Component;
use admin\models\Notification;

class NotificationManager extends Component{

  public function notifications($type = 'courier') {
     $notifications = Notification::find()
            ->where(['type' => $type])
            ->orderBy('id DESC')
            ->asArray()->all();
     return $notifications;
  }
}

Add the component class under Components section in your config file

'notificationManager ' => [
        'class' => 'admin\components\NotificationManager'
 ]

Layout

$courier_notifications = yii::$app->notificationManager->notifications('courier');


问:
Shared module with angular d'ont work
In fact I have 2 modules in my application apart from the main module:
- A module called Global.module: which contains sharable modules;
- And the other module called Pages.modules which contains my pages;
I want the modules in the global.module to be visible by pages.modules;
The problem I encountered that with the page module fails to retrieve the existing modules in Global.module see my source code; I also try exports: [NgaModule.forRoot ()] on modules to share but it seems that exports does not support ModuleWithProviders

Global.module

```<code>export const MODULES=[ BrowserModule,
  BrowserModule,
  FormsModule,
  HttpModule,
  NavbarModule,
  FooterModule,
  SidebarModule,
  RouterModule,
  LbdModule,ModalModule, BrowserAnimationsModule, ToastModule,NgbModule,
  FroalaEditorModule,
  FroalaViewModule,
  AceEditorModule,UiSwitchModule,TooltipModule,ChartsModule]
  export const SERVICES=[
    RouteGuard,BsModalService,LynkService,SharedService,Data,{provide: ToastOptions, useClass: CustomOption}, {
      provide: Http,
      useFactory: interceptorFactory,
      deps: [XHRBackend, RequestOptions, ServerUrlInterceptorService]
    } ,ServerUrlInterceptorService
  ]
@NgModule({
  exports: [
    ...MODULES
  ]

})
export class GlobalModule {
  static forRoot(): ModuleWithProviders {
    return <ModuleWithProviders> {
      ngModule: GlobalModule,
      providers: [
        ...SERVICES
      ],
    };
  }
}
</code>```

Pages.module

```<code>@NgModule({
  imports: [CommonModule, routing,FormsModule,GlobalModule],
  declarations: [
    HomeComponent,
    DefaultComponent,
  ],
})
export class PagesModule {
}
</code>```

App.module

```<code>@NgModule({
  imports: [
....
,GlobalModule.forRoot()],
  declarations: [
    ...
  ],
})
export class AppModule {
}
</code>```

答:
You can not export modules, which you didn't import before.

You will have to add
imports: [ ... MODULES ]
to your GlobalModule.

Title: Shared module with angular d'ont work

Body:
In fact I have 2 modules in my application apart from the main module:
- A module called Global.module: which contains sharable modules;
- And the other module called Pages.modules which contains my pages;
I want the modules in the global.module to be visible by pages.modules;
The problem I encountered that with the page module fails to retrieve the existing modules in Global.module see my source code; I also try exports: [NgaModule.forRoot ()] on modules to share but it seems that exports does not support ModuleWithProviders

Global.module

export const MODULES=[ BrowserModule,
  BrowserModule,
  FormsModule,
  HttpModule,
  NavbarModule,
  FooterModule,
  SidebarModule,
  RouterModule,
  LbdModule,ModalModule, BrowserAnimationsModule, ToastModule,NgbModule,
  FroalaEditorModule,
  FroalaViewModule,
  AceEditorModule,UiSwitchModule,TooltipModule,ChartsModule]
  export const SERVICES=[
    RouteGuard,BsModalService,LynkService,SharedService,Data,{provide: ToastOptions, useClass: CustomOption}, {
      provide: Http,
      useFactory: interceptorFactory,
      deps: [XHRBackend, RequestOptions, ServerUrlInterceptorService]
    } ,ServerUrlInterceptorService
  ]
@NgModule({
  exports: [
    ...MODULES
  ]

})
export class GlobalModule {
  static forRoot(): ModuleWithProviders {
    return <ModuleWithProviders> {
      ngModule: GlobalModule,
      providers: [
        ...SERVICES
      ],
    };
  }
}

Pages.module

@NgModule({
  imports: [CommonModule, routing,FormsModule,GlobalModule],
  declarations: [
    HomeComponent,
    DefaultComponent,
  ],
})
export class PagesModule {
}

App.module

@NgModule({
  imports: [
....
,GlobalModule.forRoot()],
  declarations: [
    ...
  ],
})
export class AppModule {
}


问:
Google Play app is incompatible with my phone
I have just published Android (React-Native) app on Google Play. It says:

```<code>Requires Android
5.0 and up
</code>```

I did install the apk before on my Nexus 5 (Android 6.0 M). It worked just fine so I published it to Google Play. When I open Play from my browser I can't install the app on my Nexus from there (See Fido LGE Nexus 5):

I noticed, I can't find the app in Google Play when I try to search from Nexus:

Is it because it is not indexed yet or because it's incompatible?

Why would it be incompatible if I tested same apk on this phone prior publishing?

UPDATE:

feedback from support:

Your app has an unsupported framework version: 17, 18, 19, and 20 in APK version 1 (Production)

Your app has an incompatible screen: normal, 480 for Android Versions 17, 28, 19, 20, 21, 22, 23, 24 and 25 in APK version 1 (Production)

Your app is missing device feature: android.hardware.faketouch, android.hardware.location, android.hardware.screen.portrait for Android Versions 17, 18, 20 for APK version 1 (Production)

答: The same thing happened to me, I corrected it by setting minSdkVersion=whatever is minSdk required by your app in build.gradle of app. I tried everything in play console, nothing worked except this, and the strange thing was, same app with same source code worked just fine in Alpha version! Maybe some bug in play console. Just manually set the minSdkVersion manually, it is deprecated, but works.</p>

Body:
I have just published Android (React-Native) app on Google Play. It says:

Requires Android
5.0 and up

I did install the apk before on my Nexus 5 (Android 6.0 M). It worked just fine so I published it to Google Play. When I open Play from my browser I can't install the app on my Nexus from there (See Fido LGE Nexus 5):

I noticed, I can't find the app in Google Play when I try to search from Nexus:

Is it because it is not indexed yet or because it's incompatible?

Why would it be incompatible if I tested same apk on this phone prior publishing?

UPDATE:

feedback from support:

Your app has an unsupported framework version: 17, 18, 19, and 20 in APK version 1 (Production)

Your app has an incompatible screen: normal, 480 for Android Versions 17, 28, 19, 20, 21, 22, 23, 24 and 25 in APK version 1 (Production)

Your app is missing device feature: android.hardware.faketouch, android.hardware.location, android.hardware.screen.portrait for Android Versions 17, 18, 20 for APK version 1 (Production)


问:
Android ExifInterface throw FileNotFoundException
I'm trying to rotate a bitmap in Android and show the oriented bitmap in a ImageView.

```<code>uri = Uri.parse(path)
try {
    Bitmap myBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
    Bitmap orientedBitmap = ExifUtil.rotateBitmap(path, myBitmap);
    imageView.setImageBitmap(orientedBitmap);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

and using a ExifUtil from https://gist.github.com/9re/1990019 i try to rotate it

```<code>public class ExifUtil {
    public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
        try {
            int orientation = getExifOrientation(src);

            if (orientation == ExifInterface.ORIENTATION_NORMAL) {
                return bitmap;
            }

            Matrix matrix = new Matrix();
            switch (orientation) {
                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                    matrix.setScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    matrix.setRotate(180);
                    break;
                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_TRANSPOSE:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    matrix.setRotate(90);
                    break;
                case ExifInterface.ORIENTATION_TRANSVERSE:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    matrix.setRotate(-90);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return oriented;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    private static int getExifOrientation(String src) throws IOException {
        int orientation = ExifInterface.ORIENTATION_UNDEFINED;
        Log.e("src", src);
        try {
            ExifInterface exif = new ExifInterface(src);
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, orientation);
        } catch (SecurityException | IllegalArgumentException e) {
            e.printStackTrace();
        }

        return orientation;
    }
}
</code>```

and it give me this log

```<code>11-17 17:03:20.265 3962-3962/it.package.path E/src: file:///storage/emulated/0/DCIM/image20171117_170310.jpg
11-17 17:03:30.781 3962-3962/it.package.path W/System.err: java.io.FileNotFoundException: file:/storage/emulated/0/DCIM/image20171117_170310.jpg (No such file or directory)
11-17 17:03:30.784 3962-3962/it.package.path W/System.err:     at java.io.FileInputStream.open(Native Method)
11-17 17:03:30.786 3962-3962/it.package.path W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:146)
11-17 17:03:30.787 3962-3962/it.package.path W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:99)
11-17 17:03:30.789 3962-3962/it.package.path W/System.err:     at android.media.ExifInterface.<init>(ExifInterface.java:1106)
11-17 17:03:30.791 3962-3962/it.package.path W/System.err:     at it.package.path.ExifUtil.getExifOrientation(ExifUtil.java:68)
11-17 17:03:30.794 3962-3962/it.package.path W/System.err:     at it.package.path.ExifUtil.rotateBitmap(ExifUtil.java:13)
11-17 17:03:30.795 3962-3962/it.package.path W/System.err:     at it.package.path.PreviewFragment.onCreateView(PreviewFragment.java:57)
11-17 17:03:30.797 3962-3962/it.package.path W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2352)
11-17 17:03:30.799 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
11-17 17:03:30.800 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
11-17 17:03:30.801 3962-3962/it.package.path W/System.err:     at android.app.BackStackRecord.run(BackStackRecord.java:815)
11-17 17:03:30.802 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1582)
11-17 17:03:30.804 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
11-17 17:03:30.806 3962-3962/it.package.path W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
11-17 17:03:30.808 3962-3962/it.package.path W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-17 17:03:30.809 3962-3962/it.package.path W/System.err:     at android.os.Looper.loop(Looper.java:154)
11-17 17:03:30.811 3962-3962/it.package.path W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6692)
11-17 17:03:30.813 3962-3962/it.package.path W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
11-17 17:03:30.815 3962-3962/it.package.path W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
11-17 17:03:30.816 3962-3962/it.package.path W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

Why does ExifInterface exif = new ExifInterface(src);` throw FileNotFoundException on a filepath with two missing slashes?

答:
Remove "file://" from that path so you end up with a real file system path</p>

```<code>/storage/emulated/0/DCIM/image20171117_170310.jpg
</code>```

Body:
I'm trying to rotate a bitmap in Android and show the oriented bitmap in a ImageView.

uri = Uri.parse(path)
try {
    Bitmap myBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
    Bitmap orientedBitmap = ExifUtil.rotateBitmap(path, myBitmap);
    imageView.setImageBitmap(orientedBitmap);
} catch (IOException e) {
    e.printStackTrace();
}

and using a ExifUtil from https://gist.github.com/9re/1990019 i try to rotate it

public class ExifUtil {
    public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
        try {
            int orientation = getExifOrientation(src);

            if (orientation == ExifInterface.ORIENTATION_NORMAL) {
                return bitmap;
            }

            Matrix matrix = new Matrix();
            switch (orientation) {
                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                    matrix.setScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    matrix.setRotate(180);
                    break;
                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_TRANSPOSE:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    matrix.setRotate(90);
                    break;
                case ExifInterface.ORIENTATION_TRANSVERSE:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    matrix.setRotate(-90);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return oriented;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    private static int getExifOrientation(String src) throws IOException {
        int orientation = ExifInterface.ORIENTATION_UNDEFINED;
        Log.e("src", src);
        try {
            ExifInterface exif = new ExifInterface(src);
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, orientation);
        } catch (SecurityException | IllegalArgumentException e) {
            e.printStackTrace();
        }

        return orientation;
    }
}

and it give me this log

11-17 17:03:20.265 3962-3962/it.package.path E/src: file:///storage/emulated/0/DCIM/image20171117_170310.jpg
11-17 17:03:30.781 3962-3962/it.package.path W/System.err: java.io.FileNotFoundException: file:/storage/emulated/0/DCIM/image20171117_170310.jpg (No such file or directory)
11-17 17:03:30.784 3962-3962/it.package.path W/System.err:     at java.io.FileInputStream.open(Native Method)
11-17 17:03:30.786 3962-3962/it.package.path W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:146)
11-17 17:03:30.787 3962-3962/it.package.path W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:99)
11-17 17:03:30.789 3962-3962/it.package.path W/System.err:     at android.media.ExifInterface.<init>(ExifInterface.java:1106)
11-17 17:03:30.791 3962-3962/it.package.path W/System.err:     at it.package.path.ExifUtil.getExifOrientation(ExifUtil.java:68)
11-17 17:03:30.794 3962-3962/it.package.path W/System.err:     at it.package.path.ExifUtil.rotateBitmap(ExifUtil.java:13)
11-17 17:03:30.795 3962-3962/it.package.path W/System.err:     at it.package.path.PreviewFragment.onCreateView(PreviewFragment.java:57)
11-17 17:03:30.797 3962-3962/it.package.path W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2352)
11-17 17:03:30.799 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
11-17 17:03:30.800 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
11-17 17:03:30.801 3962-3962/it.package.path W/System.err:     at android.app.BackStackRecord.run(BackStackRecord.java:815)
11-17 17:03:30.802 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1582)
11-17 17:03:30.804 3962-3962/it.package.path W/System.err:     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
11-17 17:03:30.806 3962-3962/it.package.path W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
11-17 17:03:30.808 3962-3962/it.package.path W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-17 17:03:30.809 3962-3962/it.package.path W/System.err:     at android.os.Looper.loop(Looper.java:154)
11-17 17:03:30.811 3962-3962/it.package.path W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6692)
11-17 17:03:30.813 3962-3962/it.package.path W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
11-17 17:03:30.815 3962-3962/it.package.path W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
11-17 17:03:30.816 3962-3962/it.package.path W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

Why does ExifInterface exif = new ExifInterface(src);` throw FileNotFoundException on a filepath with two missing slashes?

Body:
Remove "file://" from that path so you end up with a real file system path

/storage/emulated/0/DCIM/image20171117_170310.jpg


问:
AngularJS - bring back element to DOM after ng-if
I have got into problem when the code tried to reach an element in the DOM which was taken off before by ng-if

Code for that view looks like:

```<code><div class="col-md-9" id="map-container" ng-if="searchCount<=5000">
    <div class="col-md-12" id="map_canvas" >
    </div>
</div>
<div class="cener-btn-container"  ng-if="searchCount>5000"></div>
</code>```

and a controller part which effect that looks like

```<code>    $scope.searchCount = $scope.searchList.length;
    $log.debug("Ready to load map");
    $scope.loadMap();

     $scope.loadMap=function(){
        var latlng = new google.maps.LatLng(39.774769, -101.414795)
        $scope.customList=[];
        var map_options = {
            center: latlng,
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            zoomControl: true
        };

        google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
        ...
        $log.debug("Map lodaded");

    }
</code>```

After reaching searchCount more then 5000 results and refining search query to lower amount it throws an error

```<code>TypeError: Cannot read property 'firstChild' of null
    at Object._.ug (js?sensor=false:85)
    at new zg (js?sensor=false:87)
    at r.$scope.loadMap (controller.js:208)
    at controller.js:151
    at angular-resource.js:643
    at angular.js:14792
    at r.$eval (angular.js:16052)
    at r.$digest (angular.js:15870)
    at r.$apply (angular.js:16160)
    at g (angular.js:10589)
</code>```

and line 208 is

google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);

when map_canvas was taken by ng-if from the DOM before as there were more than 5000 results.

My question is how I can get map_canvas back before loadMap() is executed?

答:
Problem was that there is no way to know if angular is done with the digest loop, ensuring that all elements have been rendered.

To solve this issue, there were two options

Wrap a callback function in a directive. include that directive in ng-if. and make that expression true only when u want your callback to be executed. Something like

Call a callback function inside, setTimeOut(function(){ ... }, 0); as browsers by default keep all events in a queue, therefore, when digest loop is running, your callback function will enter the queue and get executed as soon digest loop is over.

In my case preferred solution was with setTimeout, allowing me to do things that are not a part of the map on a page or restricted to being inside the ng-if.

Body:
I have got into problem when the code tried to reach an element in the DOM which was taken off before by ng-if

Code for that view looks like:

<div class="col-md-9" id="map-container" ng-if="searchCount<=5000">

5000">

and a controller part which effect that looks like

    $scope.searchCount = $scope.searchList.length;
    $log.debug("Ready to load map");
    $scope.loadMap();

     $scope.loadMap=function(){
        var latlng = new google.maps.LatLng(39.774769, -101.414795)
        $scope.customList=[];
        var map_options = {
            center: latlng,
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            zoomControl: true
        };

        google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
        ...
        $log.debug("Map lodaded");

    }

After reaching searchCount more then 5000 results and refining search query to lower amount it throws an error

TypeError: Cannot read property 'firstChild' of null
    at Object._.ug (js?sensor=false:85)
    at new zg (js?sensor=false:87)
    at r.$scope.loadMap (controller.js:208)
    at controller.js:151
    at angular-resource.js:643
    at angular.js:14792
    at r.$eval (angular.js:16052)
    at r.$digest (angular.js:15870)
    at r.$apply (angular.js:16160)
    at g (angular.js:10589)

and line 208 is

google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);

when map_canvas was taken by ng-if from the DOM before as there were more than 5000 results.

My question is how I can get map_canvas back before loadMap() is executed?

Body:
Problem was that there is no way to know if angular is done with the digest loop, ensuring that all elements have been rendered.

To solve this issue, there were two options

Wrap a callback function in a directive. include that directive in ng-if. and make that expression true only when u want your callback to be executed. Something like

<div ng-if="sectionActivated">
    <div ng-init="callBack()"></div>
</div>

Call a callback function inside, setTimeOut(function(){ ... }, 0); as browsers by default keep all events in a queue, therefore, when digest loop is running, your callback function will enter the queue and get executed as soon digest loop is over.

In my case preferred solution was with setTimeout, allowing me to do things that are not a part of the map on a page or restricted to being inside the ng-if.


问:
Nunit add a custom attribute
I have taken the code example from this link to implement a new Nunit attribute to 'Repeat a test when failing'. I have added this code as a class in my solution.

I then call this new class along side the [Test] attribute:

[Test, RepeatOnFailureAttribute(2)]

But the test does not repeat when failing. I think I need to add this attribute to the Nunit list of attributes. I see the shipped list of attribute's in the XML file nunit.framework, here I have added a new item:

.member. name="T:NUnit.Framework.RepeatOnFailureAttribute"

But I do not understand how adding this new item into the XML file can be called when we only have the nunit.framework.dll reference assigned to my project.

Any help would be greatly appreciated here folks.
Thanks in advance.

答:
Please see this example of custom attribute :

Passing dynamically generated value to NUnit Custom Attribute

If you have created your custom attribute in similar fashion, then I believe you can confirm Failure in "AfterTest". Then If the test has failed you may return a value for the test to be repeated.

Title: Nunit add a custom attribute


问:
python 3, headless RaspPi, locale de_DE not possible for python-evdev
After the main problem is solved try to read from multiple HID inputs I open here a new question for the following (and different) problem:

I installed minibian on a RaspPi. The entire system is running on 'de_DE', in details:

```<code>root@ddpi:~# locale
LANG=de_DE.UTF-8
LANGUAGE=
LC_CTYPE="de_DE.UTF-8"
LC_NUMERIC="de_DE.UTF-8"
LC_TIME="de_DE.UTF-8"
LC_COLLATE="de_DE.UTF-8"
LC_MONETARY="de_DE.UTF-8"
LC_MESSAGES="de_DE.UTF-8"
LC_PAPER="de_DE.UTF-8"
LC_NAME="de_DE.UTF-8"
LC_ADDRESS="de_DE.UTF-8"
LC_TELEPHONE="de_DE.UTF-8"
LC_MEASUREMENT="de_DE.UTF-8"
LC_IDENTIFICATION="de_DE.UTF-8"
LC_ALL=
</code>```

and

```<code>root@ddpi:~# grep -v ^# /etc/locale.gen
de_DE.UTF-8 UTF-8
</code>```

and also python locale.getdefaultlocale() says 'de_DE','utf-8'.

There is no X running (because it's not installed):
ps -aux | grep X says 1297 0.0 0.1 4212 1828 pts/0 S+ 10:13 0:00 grep X and systemctl get-default says multi-user.target.

But there is the following problem: I have a German keyboard connected, which writes german as expected in console, but is recognized as english from evdev. I am using these scripts, read input from usb keyboard in linux in combination with reading events from multiple devices which works as expected, except the language. My Y keystroke is recognized as KEY_Z, my Z keystroke as KEY_Y, my ß as KEY_MINUS and so on. But everything, so far I can see, is set to de_DE.

This script (the evdev part only)

```<code>from evdev import InputDevice, categorize, ecodes
dev = InputDevice('/dev/input/event0')

print(dev)
#device /dev/input/event1, name "Dell Dell USB Keyboard", phys "usb-0000:00:12.1-2/input0"

for event in dev.read_loop():
    if event.type == ecodes.EV_KEY:
        print(categorize(event))
</code>```

says

```<code>key event at 1510568613.966220, 44 (KEY_Z), down
key event at 1510568614.039341, 44 (KEY_Z), up
key event at 1510568614.926334, 21 (KEY_Y), down
key event at 1510568614.998331, 21 (KEY_Y), up
key event at 1510568615.799577, 12 (KEY_MINUS), down
key event at 1510568615.863569, 12 (KEY_MINUS), up
</code>```

for yzß keystrokes.

What's wrong here ?

答:
So. According my own suggestion to create a german keyboard mapping here are my two scripts, which are still DEV VERSIONS, not yet in production, but work correctly on console output.
The first one I named hidraw_survey.py because it is wondering all the time, if new HIDs are connected or unplugged. Both events cause a pkill -f and restart of the second script read_hidraw_scanner.py, which handles the keyboard events of all connected HIDs at once.
As there are the following:

```<code>device /dev/input/event4, name "OPTO-E Barcode Device", phys "usb-3f980000.usb-1.5.4/input0"
device /dev/input/event0, name "CHICONY HP Basic USB Keyboard", phys "usb-3f980000.usb-1.5.1/input0"
device /dev/input/event1, name "Sycreader USB Reader", phys "usb-3f980000.usb-1.5.2/input0"
device /dev/input/event2, name "HID 04d9:1203", phys "usb-3f980000.usb-1.5.3/input0"
device /dev/input/event3, name "HID 04d9:1203", phys "usb-3f980000.usb-1.5.3/input1"
</code>```

Why the numerical keypad (last on list) is counted twice... no idea, but the input events are processed correctly.

Both scripts try to find out and guess the numbers of the input event connections between 0 and 9 and skip these numbers, on which the tests are not successful. The language specific mapping itself is realized by LANG = locale.getdefaultlocale()[0].split('_')[0].upper() which delivers me DE.

The first script hidraw_survey.py:

```<code>import sys
import os
from pathlib import Path
import time

logfile = '/ddpos/log/hidraw_scanner.txt'

f = open(logfile, 'a')
f.write('hidraw_scanner started: '+time.strftime("%d.%m.%Y %H:%M:%S")+'\n')
f.close()

def try_kill_script(script):
    try:
        os.system('pkill -f '+script)
    except OSError:
        return False
    else:
        return True

old = ''
new = ''
while 1:
    out = ''
    for i in range(10):
        hidrawfile = '/dev/hidraw'+str(i)
        hidrawpath = Path(hidrawfile)
        if hidrawpath.exists():
            out += str(i)
            #print (out)
    new = out
    if new != old:
        print ('change registered')
        f = open(logfile, 'a')
        f.write('USB changed to: '+out+'\n')
        f.close()
        try_kill_script('read_hidraw_scanner.py')
        os.system('python3 /ddpos/test/read_hidraw_scanner.py &')
    old = out
</code>```

The 2nd script read_hidraw_scanner.py:

```<code>import os
import sys
from evdev import InputDevice, list_devices, ecodes, categorize
from select import select
from pathlib import Path
import locale

LANG = locale.getdefaultlocale()[0].split('_')[0].upper()

CODE_MAP_CHAR = {
    'DE': {
        'KEY_A': "a",
        'KEY_B': "b",
        'KEY_C': "c",
        'KEY_D': "d",
        'KEY_E': "e",
        'KEY_F': "f",
        'KEY_G': "g",
        'KEY_H': "h",
        'KEY_I': "i",
        'KEY_J': "j",
        'KEY_K': "k",
        'KEY_L': "l",
        'KEY_M': "m",
        'KEY_N': "n",
        'KEY_O': "o",
        'KEY_P': "p",
        'KEY_Q': "q",
        'KEY_R': "r",
        'KEY_S': "s",
        'KEY_T': "t",
        'KEY_U': "u",
        'KEY_V': "v",
        'KEY_W': "w",
        'KEY_X': "x",
        'KEY_Y': "z",
        'KEY_Z': "y",
        'SHIFT_KEY_A': "A",
        'SHIFT_KEY_B': "B",
        'SHIFT_KEY_C': "C",
        'SHIFT_KEY_D': "D",
        'SHIFT_KEY_E': "E",
        'SHIFT_KEY_F': "F",
        'SHIFT_KEY_G': "G",
        'SHIFT_KEY_H': "H",
        'SHIFT_KEY_I': "I",
        'SHIFT_KEY_J': "J",
        'SHIFT_KEY_K': "K",
        'SHIFT_KEY_L': "L",
        'SHIFT_KEY_M': "M",
        'SHIFT_KEY_N': "N",
        'SHIFT_KEY_O': "O",
        'SHIFT_KEY_P': "P",
        'SHIFT_KEY_Q': "Q",
        'SHIFT_KEY_R': "R",
        'SHIFT_KEY_S': "S",
        'SHIFT_KEY_T': "T",
        'SHIFT_KEY_U': "U",
        'SHIFT_KEY_V': "V",
        'SHIFT_KEY_W': "W",
        'SHIFT_KEY_X': "X",
        'SHIFT_KEY_Y': "Z",
        'SHIFT_KEY_Z': "Y",

        'SHIFT_KEY_GRAVE':'°',
        'SHIFT_KEY_1': "!",
        'SHIFT_KEY_2': "\"",
        'SHIFT_KEY_3': "§",
        'SHIFT_KEY_4': "$",
        'SHIFT_KEY_5': "%",
        'SHIFT_KEY_6': "&",
        'SHIFT_KEY_7': "/",
        'SHIFT_KEY_8': "(",
        'SHIFT_KEY_9': ")",
        'SHIFT_KEY_0': "=",
        'SHIFT_KEY_EQUAL': "`",
        'SHIFT_KEY_RIGHTBRACE':'*',
        'SHIFT_KEY_BACKSLASH':'\'',
        'SHIFT_KEY_COMMA':';',
        'SHIFT_KEY_DOT':':',
        'SHIFT_KEY_SLASH':'_',

        'ALTGR_KEY_Q': "@",
        'ALTGR_KEY_MINUS': "\\",
        'ALTGR_KEY_7': "{",
        'ALTGR_KEY_0': "}",
        'ALTGR_KEY_8': "[",
        'ALTGR_KEY_9': "]",
        'ALTGR_KEY_RIGHTBRACE':'~',

        'KEY_NUMERIC_STAR': "*",

        'KEY_GRAVE':'^',
        'KEY_LEFTBRACE':'Ü',
        'KEY_RIGHTBRACE':'+',
        'KEY_SEMICOLON':'Ö',
        'KEY_APOSTROPHE':'Ä',
        'KEY_BACKSLASH':'#',
        'KEY_102ND':'<',
        'KEY_COMMA':',',
        'KEY_DOT':'.',
        'KEY_SLASH':'-',
        'KEY_KPSLASH':'/',
        'KEY_KPASTERISK':'*',
        'KEY_KPMINUS':'-',
        'KEY_KPPLUS':'+',
        'KEY_KPDOT':'.',
        'KEY_SPACE': " ",
        'KEY_EQUAL': "´",
        'KEY_TAB': "\t",

        'KEY_MINUS': "ß",
        'KEY_SPACE': " ",

        'KEY_NUMERIC_1': "1",
        'KEY_NUMERIC_2': "2",
        'KEY_NUMERIC_3': "3",
        'KEY_NUMERIC_4': "4",
        'KEY_NUMERIC_5': "5",
        'KEY_NUMERIC_6': "6",
        'KEY_NUMERIC_7': "7",
        'KEY_NUMERIC_8': "8",
        'KEY_NUMERIC_9': "9",
        'KEY_NUMERIC_0': "0",
        'KEY_KP1': "1",
        'KEY_KP2': "2",
        'KEY_KP3': "3",
        'KEY_KP4': "4",
        'KEY_KP5': "5",
        'KEY_KP6': "6",
        'KEY_KP7': "7",
        'KEY_KP8': "8",
        'KEY_KP9': "9",
        'KEY_KP0': "0",
        'KEY_1': "1",
        'KEY_2': "2",
        'KEY_3': "3",
        'KEY_4': "4",
        'KEY_5': "5",
        'KEY_6': "6",
        'KEY_7': "7",
        'KEY_8': "8",
        'KEY_9': "9",
        'KEY_0': "0"
    },
     'EN': {
        'KEY_A': "A",
        'KEY_B': "B",
        'KEY_C': "C",
        'KEY_D': "D",
        'KEY_E': "E",
        'KEY_F': "F",
        'KEY_G': "G",
        'KEY_H': "H",
        'KEY_I': "I",
        'KEY_J': "J",
        'KEY_K': "K",
        'KEY_L': "L",
        'KEY_M': "M",
        'KEY_N': "N",
        'KEY_O': "O",
        'KEY_P': "P",
        'KEY_Q': "Q",
        'KEY_R': "R",
        'KEY_S': "S",
        'KEY_T': "T",
        'KEY_U': "U",
        'KEY_V': "V",
        'KEY_W': "W",
        'KEY_X': "X",
        'KEY_Y': "Y",
        'KEY_Z': "Z",
        'KEY_GRAVE':'`',
        'KEY_MINUS': "-",
        'KEY_SPACE': " ",
        'KEY_BACKSLASH': "\\",
        'KEY_GRAVE': "`",
        'KEY_NUMERIC_STAR': "*",
        'KEY_LEFTBRACE': "[",
        'KEY_RIGHTBRACE': "]",
        'KEY_COMMA': ",",
        'KEY_EQUAL': "=",
        'KEY_SEMICOLON': ";",
        'KEY_APOSTROPHE': "'",
        'KEY_TAB': "\t",
        'KEY_DOT': ".",
        'KEY_SLASH': "/",
        'KEY_NUMERIC_1': "1",
        'KEY_NUMERIC_2': "2",
        'KEY_NUMERIC_3': "3",
        'KEY_NUMERIC_4': "4",
        'KEY_NUMERIC_5': "5",
        'KEY_NUMERIC_6': "6",
        'KEY_NUMERIC_7': "7",
        'KEY_NUMERIC_8': "8",
        'KEY_NUMERIC_9': "9",
        'KEY_NUMERIC_0': "0",
        'KEY_KP1': "1",
        'KEY_KP2': "2",
        'KEY_KP3': "3",
        'KEY_KP4': "4",
        'KEY_KP5': "5",
        'KEY_KP6': "6",
        'KEY_KP7': "7",
        'KEY_KP8': "8",
        'KEY_KP9': "9",
        'KEY_KP0': "0",
        'KEY_1': "1",
        'KEY_2': "2",
        'KEY_3': "3",
        'KEY_4': "4",
        'KEY_5': "5",
        'KEY_6': "6",
        'KEY_7': "7",
        'KEY_8': "8",
        'KEY_9': "9",
        'KEY_0': "0"
    }
}

def parse_key_to_char(val):
    return CODE_MAP_CHAR[LANG][val] if val in CODE_MAP_CHAR[LANG] else ""

def try_kill_script(script):
    try:
        os.system('pkill -f '+script)
    except OSError:
        return False
    else:
        return True

founddev = []
for i in range(10):
    trydev = '/dev/input/event'+str(i)
    if Path(trydev).exists():
        founddev.append(trydev)

devices = map(InputDevice, founddev)
devices = {dev.fd: dev for dev in devices}

for dev in devices.values():
    print(dev)

chars = ''
prefix = ''

while 1:

    r, w, x = select(devices, [], [])
    for fd in r:
        try:
            for event in devices[fd].read():
                if event.type == ecodes.EV_KEY:
                    e = categorize(event)
                    if e.keystate == e.key_down:
                        if e.keycode == 'KEY_LEFTSHIFT' or e.keycode == 'KEY_RIGHTSHIFT':
                            prefix = 'SHIFT_'
                        elif e.keycode == 'KEY_LEFTALT':
                            prefix = 'ALT_'
                        elif e.keycode == 'KEY_RIGHTALT':
                            prefix = 'ALTGR_'
                            print ('prefix='+prefix)
                        elif e.keycode == 'KEY_ESC':
                            chars = ''
                        elif e.keycode == 'KEY_BACKSPACE':
                            chars = chars[:-1]
                        elif e.keycode == 'KEY_ENTER' or e.keycode == 'KEY_KPENTER':
                            sys.stdout.write(chars+'\n')
                            sys.stdout.flush()
                            chars = ''
                        else:
                            #print (ecodes.EV_LED) # which outputs 17 forever
                            print (prefix + e.keycode)
                            chars += parse_key_to_char(prefix + e.keycode)
                    elif e.keystate == e.key_up:
                        #sys.stdout.write(parse_key_to_char(e.keycode))
                        #sys.stdout.flush()
                        #print ("'"+e.keycode+"':'"+parse_key_to_char(e.keycode)+"',")
                        if e.keycode == 'KEY_LEFTSHIFT' or e.keycode == 'KEY_RIGHTSHIFT':
                            prefix = ''
                        elif e.keycode == 'KEY_LEFTALT':
                            prefix = ''
                        elif e.keycode == 'KEY_RIGHTALT':
                            prefix = ''
        except:
            try_kill_script('read_hidraw_scanner.py')
</code>```

Both scripts are full of dents and wrinkles made by a python newbie like me, but I think with a bit of improvement and simplifications it's a really nice toy to tell the RaspPi something like config settings or password inputs or whatever (in my case a barcode scanner with alternative manual input in case of not readable barcode and a RFID reader for waiter/waitress authentification in restaurants)

The mapping covers all german keyboard keys including SHIFT and ALTGR (right ALT), not yet ALT (left ALT). But it doesn't work with accents like è or é or ñ, nor CAPSLOCK. Improvements are welcome.

UPDATE
The output looks like that at the moment.
One after the other, a scanned numeric barcode, an alphanumeric barcode, a keyboard input and the RDFID reader at last.

```<code>KEY_0
KEY_4
KEY_0
KEY_1
KEY_3
KEY_6
KEY_0
KEY_0
KEY_0
KEY_0
KEY_4
KEY_8
KEY_6
KEY_0
KEY_9
KEY_5
0401360000486095
KEY_2
SHIFT_KEY_B
KEY_5
KEY_6
KEY_6
KEY_9
SHIFT_KEY_C
SHIFT_KEY_F
KEY_4
SHIFT_KEY_A
KEY_2
KEY_1
SHIFT_KEY_C
KEY_1
SHIFT_KEY_B
KEY_7
2B5669CF4A21C1B7
KEY_M
KEY_Z
KEY_N
KEY_A
KEY_M
KEY_E
ALTGR_KEY_Q
KEY_E
KEY_M
KEY_A
KEY_I
KEY_L
KEY_DOT
KEY_C
KEY_O
KEY_M
myname@email.com
KEY_0
KEY_0
KEY_0
KEY_5
KEY_6
KEY_1
KEY_1
KEY_4
KEY_9
KEY_6
0005611496
</code>```

Body:
After the main problem is solved try to read from multiple HID inputs I open here a new question for the following (and different) problem:

I installed minibian on a RaspPi. The entire system is running on 'de_DE', in details:

root@ddpi:~# locale
LANG=de_DE.UTF-8
LANGUAGE=
LC_CTYPE="de_DE.UTF-8"
LC_NUMERIC="de_DE.UTF-8"
LC_TIME="de_DE.UTF-8"
LC_COLLATE="de_DE.UTF-8"
LC_MONETARY="de_DE.UTF-8"
LC_MESSAGES="de_DE.UTF-8"
LC_PAPER="de_DE.UTF-8"
LC_NAME="de_DE.UTF-8"
LC_ADDRESS="de_DE.UTF-8"
LC_TELEPHONE="de_DE.UTF-8"
LC_MEASUREMENT="de_DE.UTF-8"
LC_IDENTIFICATION="de_DE.UTF-8"
LC_ALL=

and

root@ddpi:~# grep -v ^# /etc/locale.gen
de_DE.UTF-8 UTF-8

and also python locale.getdefaultlocale() says 'de_DE','utf-8'.

There is no X running (because it's not installed):
ps -aux | grep X says 1297 0.0 0.1 4212 1828 pts/0 S+ 10:13 0:00 grep X and systemctl get-default says multi-user.target.

But there is the following problem: I have a German keyboard connected, which writes german as expected in console, but is recognized as english from evdev. I am using these scripts, read input from usb keyboard in linux in combination with reading events from multiple devices which works as expected, except the language. My Y keystroke is recognized as KEY_Z, my Z keystroke as KEY_Y, my ß as KEY_MINUS and so on. But everything, so far I can see, is set to de_DE.

This script (the evdev part only)

from evdev import InputDevice, categorize, ecodes
dev = InputDevice('/dev/input/event0')

print(dev)
#device /dev/input/event1, name "Dell Dell USB Keyboard", phys "usb-0000:00:12.1-2/input0"

for event in dev.read_loop():
    if event.type == ecodes.EV_KEY:
        print(categorize(event))

says

key event at 1510568613.966220, 44 (KEY_Z), down
key event at 1510568614.039341, 44 (KEY_Z), up
key event at 1510568614.926334, 21 (KEY_Y), down
key event at 1510568614.998331, 21 (KEY_Y), up
key event at 1510568615.799577, 12 (KEY_MINUS), down
key event at 1510568615.863569, 12 (KEY_MINUS), up

for yzß keystrokes.

What's wrong here ?

Body:
So. According my own suggestion to create a german keyboard mapping here are my two scripts, which are still DEV VERSIONS, not yet in production, but work correctly on console output.
The first one I named hidraw_survey.py because it is wondering all the time, if new HIDs are connected or unplugged. Both events cause a pkill -f and restart of the second script read_hidraw_scanner.py, which handles the keyboard events of all connected HIDs at once.
As there are the following:

device /dev/input/event4, name "OPTO-E Barcode Device", phys "usb-3f980000.usb-1.5.4/input0"
device /dev/input/event0, name "CHICONY HP Basic USB Keyboard", phys "usb-3f980000.usb-1.5.1/input0"
device /dev/input/event1, name "Sycreader USB Reader", phys "usb-3f980000.usb-1.5.2/input0"
device /dev/input/event2, name "HID 04d9:1203", phys "usb-3f980000.usb-1.5.3/input0"
device /dev/input/event3, name "HID 04d9:1203", phys "usb-3f980000.usb-1.5.3/input1"

Why the numerical keypad (last on list) is counted twice... no idea, but the input events are processed correctly.

Both scripts try to find out and guess the numbers of the input event connections between 0 and 9 and skip these numbers, on which the tests are not successful. The language specific mapping itself is realized by LANG = locale.getdefaultlocale()[0].split('_')[0].upper() which delivers me DE.

The first script hidraw_survey.py:

import sys
import os
from pathlib import Path
import time

logfile = '/ddpos/log/hidraw_scanner.txt'

f = open(logfile, 'a')
f.write('hidraw_scanner started: '+time.strftime("%d.%m.%Y %H:%M:%S")+'\n')
f.close()

def try_kill_script(script):
    try:
        os.system('pkill -f '+script)
    except OSError:
        return False
    else:
        return True

old = ''
new = ''
while 1:
    out = ''
    for i in range(10):
        hidrawfile = '/dev/hidraw'+str(i)
        hidrawpath = Path(hidrawfile)
        if hidrawpath.exists():
            out += str(i)
            #print (out)
    new = out
    if new != old:
        print ('change registered')
        f = open(logfile, 'a')
        f.write('USB changed to: '+out+'\n')
        f.close()
        try_kill_script('read_hidraw_scanner.py')
        os.system('python3 /ddpos/test/read_hidraw_scanner.py &')
    old = out

The 2nd script read_hidraw_scanner.py:

import os
import sys
from evdev import InputDevice, list_devices, ecodes, categorize
from select import select
from pathlib import Path
import locale

LANG = locale.getdefaultlocale()[0].split('_')[0].upper()

CODE_MAP_CHAR = {
    'DE': {
        'KEY_A': "a",
        'KEY_B': "b",
        'KEY_C': "c",
        'KEY_D': "d",
        'KEY_E': "e",
        'KEY_F': "f",
        'KEY_G': "g",
        'KEY_H': "h",
        'KEY_I': "i",
        'KEY_J': "j",
        'KEY_K': "k",
        'KEY_L': "l",
        'KEY_M': "m",
        'KEY_N': "n",
        'KEY_O': "o",
        'KEY_P': "p",
        'KEY_Q': "q",
        'KEY_R': "r",
        'KEY_S': "s",
        'KEY_T': "t",
        'KEY_U': "u",
        'KEY_V': "v",
        'KEY_W': "w",
        'KEY_X': "x",
        'KEY_Y': "z",
        'KEY_Z': "y",
        'SHIFT_KEY_A': "A",
        'SHIFT_KEY_B': "B",
        'SHIFT_KEY_C': "C",
        'SHIFT_KEY_D': "D",
        'SHIFT_KEY_E': "E",
        'SHIFT_KEY_F': "F",
        'SHIFT_KEY_G': "G",
        'SHIFT_KEY_H': "H",
        'SHIFT_KEY_I': "I",
        'SHIFT_KEY_J': "J",
        'SHIFT_KEY_K': "K",
        'SHIFT_KEY_L': "L",
        'SHIFT_KEY_M': "M",
        'SHIFT_KEY_N': "N",
        'SHIFT_KEY_O': "O",
        'SHIFT_KEY_P': "P",
        'SHIFT_KEY_Q': "Q",
        'SHIFT_KEY_R': "R",
        'SHIFT_KEY_S': "S",
        'SHIFT_KEY_T': "T",
        'SHIFT_KEY_U': "U",
        'SHIFT_KEY_V': "V",
        'SHIFT_KEY_W': "W",
        'SHIFT_KEY_X': "X",
        'SHIFT_KEY_Y': "Z",
        'SHIFT_KEY_Z': "Y",

        'SHIFT_KEY_GRAVE':'°',
        'SHIFT_KEY_1': "!",
        'SHIFT_KEY_2': "\"",
        'SHIFT_KEY_3': "§",
        'SHIFT_KEY_4': "$",
        'SHIFT_KEY_5': "%",
        'SHIFT_KEY_6': "&",
        'SHIFT_KEY_7': "/",
        'SHIFT_KEY_8': "(",
        'SHIFT_KEY_9': ")",
        'SHIFT_KEY_0': "=",
        'SHIFT_KEY_EQUAL': "`",
        'SHIFT_KEY_RIGHTBRACE':'*',
        'SHIFT_KEY_BACKSLASH':'\'',
        'SHIFT_KEY_COMMA':';',
        'SHIFT_KEY_DOT':':',
        'SHIFT_KEY_SLASH':'_',

        'ALTGR_KEY_Q': "@",
        'ALTGR_KEY_MINUS': "\\",
        'ALTGR_KEY_7': "{",
        'ALTGR_KEY_0': "}",
        'ALTGR_KEY_8': "[",
        'ALTGR_KEY_9': "]",
        'ALTGR_KEY_RIGHTBRACE':'~',

        'KEY_NUMERIC_STAR': "*",

        'KEY_GRAVE':'^',
        'KEY_LEFTBRACE':'Ü',
        'KEY_RIGHTBRACE':'+',
        'KEY_SEMICOLON':'Ö',
        'KEY_APOSTROPHE':'Ä',
        'KEY_BACKSLASH':'#',
        'KEY_102ND':'<',
        'KEY_COMMA':',',
        'KEY_DOT':'.',
        'KEY_SLASH':'-',
        'KEY_KPSLASH':'/',
        'KEY_KPASTERISK':'*',
        'KEY_KPMINUS':'-',
        'KEY_KPPLUS':'+',
        'KEY_KPDOT':'.',
        'KEY_SPACE': " ",
        'KEY_EQUAL': "´",
        'KEY_TAB': "\t",

        'KEY_MINUS': "ß",
        'KEY_SPACE': " ",

        'KEY_NUMERIC_1': "1",
        'KEY_NUMERIC_2': "2",
        'KEY_NUMERIC_3': "3",
        'KEY_NUMERIC_4': "4",
        'KEY_NUMERIC_5': "5",
        'KEY_NUMERIC_6': "6",
        'KEY_NUMERIC_7': "7",
        'KEY_NUMERIC_8': "8",
        'KEY_NUMERIC_9': "9",
        'KEY_NUMERIC_0': "0",
        'KEY_KP1': "1",
        'KEY_KP2': "2",
        'KEY_KP3': "3",
        'KEY_KP4': "4",
        'KEY_KP5': "5",
        'KEY_KP6': "6",
        'KEY_KP7': "7",
        'KEY_KP8': "8",
        'KEY_KP9': "9",
        'KEY_KP0': "0",
        'KEY_1': "1",
        'KEY_2': "2",
        'KEY_3': "3",
        'KEY_4': "4",
        'KEY_5': "5",
        'KEY_6': "6",
        'KEY_7': "7",
        'KEY_8': "8",
        'KEY_9': "9",
        'KEY_0': "0"
    },
     'EN': {
        'KEY_A': "A",
        'KEY_B': "B",
        'KEY_C': "C",
        'KEY_D': "D",
        'KEY_E': "E",
        'KEY_F': "F",
        'KEY_G': "G",
        'KEY_H': "H",
        'KEY_I': "I",
        'KEY_J': "J",
        'KEY_K': "K",
        'KEY_L': "L",
        'KEY_M': "M",
        'KEY_N': "N",
        'KEY_O': "O",
        'KEY_P': "P",
        'KEY_Q': "Q",
        'KEY_R': "R",
        'KEY_S': "S",
        'KEY_T': "T",
        'KEY_U': "U",
        'KEY_V': "V",
        'KEY_W': "W",
        'KEY_X': "X",
        'KEY_Y': "Y",
        'KEY_Z': "Z",
        'KEY_GRAVE':'`',
        'KEY_MINUS': "-",
        'KEY_SPACE': " ",
        'KEY_BACKSLASH': "\\",
        'KEY_GRAVE': "`",
        'KEY_NUMERIC_STAR': "*",
        'KEY_LEFTBRACE': "[",
        'KEY_RIGHTBRACE': "]",
        'KEY_COMMA': ",",
        'KEY_EQUAL': "=",
        'KEY_SEMICOLON': ";",
        'KEY_APOSTROPHE': "'",
        'KEY_TAB': "\t",
        'KEY_DOT': ".",
        'KEY_SLASH': "/",
        'KEY_NUMERIC_1': "1",
        'KEY_NUMERIC_2': "2",
        'KEY_NUMERIC_3': "3",
        'KEY_NUMERIC_4': "4",
        'KEY_NUMERIC_5': "5",
        'KEY_NUMERIC_6': "6",
        'KEY_NUMERIC_7': "7",
        'KEY_NUMERIC_8': "8",
        'KEY_NUMERIC_9': "9",
        'KEY_NUMERIC_0': "0",
        'KEY_KP1': "1",
        'KEY_KP2': "2",
        'KEY_KP3': "3",
        'KEY_KP4': "4",
        'KEY_KP5': "5",
        'KEY_KP6': "6",
        'KEY_KP7': "7",
        'KEY_KP8': "8",
        'KEY_KP9': "9",
        'KEY_KP0': "0",
        'KEY_1': "1",
        'KEY_2': "2",
        'KEY_3': "3",
        'KEY_4': "4",
        'KEY_5': "5",
        'KEY_6': "6",
        'KEY_7': "7",
        'KEY_8': "8",
        'KEY_9': "9",
        'KEY_0': "0"
    }
}

def parse_key_to_char(val):
    return CODE_MAP_CHAR[LANG][val] if val in CODE_MAP_CHAR[LANG] else ""

def try_kill_script(script):
    try:
        os.system('pkill -f '+script)
    except OSError:
        return False
    else:
        return True

founddev = []
for i in range(10):
    trydev = '/dev/input/event'+str(i)
    if Path(trydev).exists():
        founddev.append(trydev)

devices = map(InputDevice, founddev)
devices = {dev.fd: dev for dev in devices}

for dev in devices.values():
    print(dev)

chars = ''
prefix = ''

while 1:

    r, w, x = select(devices, [], [])
    for fd in r:
        try:
            for event in devices[fd].read():
                if event.type == ecodes.EV_KEY:
                    e = categorize(event)
                    if e.keystate == e.key_down:
                        if e.keycode == 'KEY_LEFTSHIFT' or e.keycode == 'KEY_RIGHTSHIFT':
                            prefix = 'SHIFT_'
                        elif e.keycode == 'KEY_LEFTALT':
                            prefix = 'ALT_'
                        elif e.keycode == 'KEY_RIGHTALT':
                            prefix = 'ALTGR_'
                            print ('prefix='+prefix)
                        elif e.keycode == 'KEY_ESC':
                            chars = ''
                        elif e.keycode == 'KEY_BACKSPACE':
                            chars = chars[:-1]
                        elif e.keycode == 'KEY_ENTER' or e.keycode == 'KEY_KPENTER':
                            sys.stdout.write(chars+'\n')
                            sys.stdout.flush()
                            chars = ''
                        else:
                            #print (ecodes.EV_LED) # which outputs 17 forever
                            print (prefix + e.keycode)
                            chars += parse_key_to_char(prefix + e.keycode)
                    elif e.keystate == e.key_up:
                        #sys.stdout.write(parse_key_to_char(e.keycode))
                        #sys.stdout.flush()
                        #print ("'"+e.keycode+"':'"+parse_key_to_char(e.keycode)+"',")
                        if e.keycode == 'KEY_LEFTSHIFT' or e.keycode == 'KEY_RIGHTSHIFT':
                            prefix = ''
                        elif e.keycode == 'KEY_LEFTALT':
                            prefix = ''
                        elif e.keycode == 'KEY_RIGHTALT':
                            prefix = ''
        except:
            try_kill_script('read_hidraw_scanner.py')

Both scripts are full of dents and wrinkles made by a python newbie like me, but I think with a bit of improvement and simplifications it's a really nice toy to tell the RaspPi something like config settings or password inputs or whatever (in my case a barcode scanner with alternative manual input in case of not readable barcode and a RFID reader for waiter/waitress authentification in restaurants)

The mapping covers all german keyboard keys including SHIFT and ALTGR (right ALT), not yet ALT (left ALT). But it doesn't work with accents like è or é or ñ, nor CAPSLOCK. Improvements are welcome.

UPDATE
The output looks like that at the moment.
One after the other, a scanned numeric barcode, an alphanumeric barcode, a keyboard input and the RDFID reader at last.

KEY_0
KEY_4
KEY_0
KEY_1
KEY_3
KEY_6
KEY_0
KEY_0
KEY_0
KEY_0
KEY_4
KEY_8
KEY_6
KEY_0
KEY_9
KEY_5
0401360000486095
KEY_2
SHIFT_KEY_B
KEY_5
KEY_6
KEY_6
KEY_9
SHIFT_KEY_C
SHIFT_KEY_F
KEY_4
SHIFT_KEY_A
KEY_2
KEY_1
SHIFT_KEY_C
KEY_1
SHIFT_KEY_B
KEY_7
2B5669CF4A21C1B7
KEY_M
KEY_Z
KEY_N
KEY_A
KEY_M
KEY_E
ALTGR_KEY_Q
KEY_E
KEY_M
KEY_A
KEY_I
KEY_L
KEY_DOT
KEY_C
KEY_O
KEY_M
myname@email.com
KEY_0
KEY_0
KEY_0
KEY_5
KEY_6
KEY_1
KEY_1
KEY_4
KEY_9
KEY_6
0005611496


问:
Template type deduction for member variables and function arguments
Consider the following implementation of a template class:

```<code>template<class T>
class MyClass
{
public:
    void setVar1(const T& v1)
    {
        var1 = v1;
    }
    void setVar2(const T1& v2)
    {
        var2 = v2;
    }

    T var1;
    T1 var2;
};
</code>```

If the template parameter T is a fundamental type (like float, double, or long double) I would like to have T1 = T.

If the template parameter T is std::complex<float>, I would like to have T=std::complex<float> and T1 = float. Similarly for std::complex<double> and std::complex<long double>.

Deducing the type of the variable is discussed at Template type derivation

However, the additional member functions prevents usage of their solution in this context.

答:
Based on Bo Personns comment and the answer provided at https://stackoverflow.com/questions/47334675/template-type-derivation

I got the following working example.

The content of my .h file is as follows.

```<code>#include <iostream>
#include <complex>
#include <typeinfo>

template <typename T>
class MyClass
 {

 template <typename T0>
struct myTypeTraits
 { using type = T0; };

template <typename T0>
struct myTypeTraits<std::complex<T0>>
 { using type = T0; };

public:

   using T0 = typename myTypeTraits<T>::type;

   void setVar1(const T0& v);

   void setVar2(const T& v);

T getVar2() const;

   void print() const;

   T0 var1;
   T  var2;
 };
</code>```

The .cpp file contains the following lines of code.

```<code>template <class T>
void MyClass<T>::setVar1(const T0& v)
{
    var1 = v;
}

template <class T>
void MyClass<T>::setVar2(const T& v)
{
    var2 = v;
}

template <class T>
T MyClass<T>::getVar2() const
{
    return var2;
}

template <typename T>
void MyClass<T>::print() const
{
    std::cout<<"var1: "<<var1<<std::endl;
    std::cout<<"var2: "<<var2<<std::endl;

}

int main()
{

    MyClass<float> tmp;

    MyClass<std::complex<float> > tmp1;

    tmp.print();
    tmp1.print();
    return 0;
}
</code>```

The above code works as intended.

However, I have another related question posted at Template type deduction in function return type

Body:
Consider the following implementation of a template class:

template<class T>
class MyClass
{
public:
    void setVar1(const T& v1)
    {
        var1 = v1;
    }
    void setVar2(const T1& v2)
    {
        var2 = v2;
    }

    T var1;
    T1 var2;
};

If the template parameter T is a fundamental type (like float, double, or long double) I would like to have T1 = T.

If the template parameter T is std::complex<float>, I would like to have T=std::complex<float> and T1 = float. Similarly for std::complex<double> and std::complex<long double>.

Deducing the type of the variable is discussed at Template type derivation

However, the additional member functions prevents usage of their solution in this context.

Body:
Based on Bo Personns comment and the answer provided at https://stackoverflow.com/questions/47334675/template-type-derivation

I got the following working example.

The content of my .h file is as follows.

#include <iostream>
#include <complex>
#include <typeinfo>

template <typename T>
class MyClass
 {

 template <typename T0>
struct myTypeTraits
 { using type = T0; };

template <typename T0>
struct myTypeTraits<std::complex<T0>>
 { using type = T0; };

public:

   using T0 = typename myTypeTraits<T>::type;

   void setVar1(const T0& v);

   void setVar2(const T& v);

T getVar2() const;

   void print() const;

   T0 var1;
   T  var2;
 };

The .cpp file contains the following lines of code.

template <class T>
void MyClass<T>::setVar1(const T0& v)
{
    var1 = v;
}

template <class T>
void MyClass<T>::setVar2(const T& v)
{
    var2 = v;
}

template <class T>
T MyClass<T>::getVar2() const
{
    return var2;
}

template <typename T>
void MyClass<T>::print() const
{
    std::cout<<"var1: "<<var1<<std::endl;
    std::cout<<"var2: "<<var2<<std::endl;

}

int main()
{

    MyClass<float> tmp;

    MyClass<std::complex<float> > tmp1;

    tmp.print();
    tmp1.print();
    return 0;
}

The above code works as intended.

However, I have another related question posted at Template type deduction in function return type


问:
How to execute external windows software command line in php exec()?
I download a copy software name fastcopy, and it gives a command line to execute copy files.
The command :

A basic format is as follows.

fastcopy.exe [/options] file1 file2
  ... [/to=dest_dir]

Please use space character(' ') as
  separator(not semicolon). If filename
  contains space character, please
  enclose with dobule quotation marks.
  Ex) fastopy.exe C:\Windows "C:\Program
  Files" /to="D:\Backup Folder\"

Supported options are as follows.
  (Please don't put space characters
  before and behind "=")

/cmd=(noexist_only|diff|update|sync|force_copy|move|delete)
  ... Specify operation mode. (By
  default, diff mode is used. If delete
  mode is specified, then "/to=" option
  isn't used.)

So, my original code to execute the fastcopy.exe was:

```<code>// fastcopy the software folder
$cmd = 'D:\\fastcopy\\fastcopy.exe d:\\files.rar /to="e:\\"';
exec( $cmd,$result)
</code>```

but it seem didn't work.

So, How to execute it??

fastcopy web page

link to direct download only 300kb

Thank you very much!!

答: Probably because you're using double-backslashes when you shouldn't be. Single quotes strings don't need your backslashes escaping unless it's the very last character in the string.</p>

ContentLicense: CC BY-SA 2.5

Body:
I download a copy software name fastcopy, and it gives a command line to execute copy files.
The command :

A basic format is as follows.

fastcopy.exe [/options] file1 file2
  ... [/to=dest_dir]

Please use space character(' ') as
  separator(not semicolon). If filename
  contains space character, please
  enclose with dobule quotation marks.
  Ex) fastopy.exe C:\Windows "C:\Program
  Files" /to="D:\Backup Folder\"

Supported options are as follows.
  (Please don't put space characters
  before and behind "=")

/cmd=(noexist_only|diff|update|sync|force_copy|move|delete)
  ... Specify operation mode. (By
  default, diff mode is used. If delete
  mode is specified, then "/to=" option
  isn't used.)

So, my original code to execute the fastcopy.exe was:

// fastcopy the software folder
$cmd = 'D:\\fastcopy\\fastcopy.exe d:\\files.rar /to="e:\\"';
exec( $cmd,$result)

but it seem didn't work.

So, How to execute it??

fastcopy web page

link to direct download only 300kb

Thank you very much!!


问:
Unique count, array to string
There is my input
{"Names":"Name1, Name2","Country":"TheCountry"}

What i have been trying to do is count how many time a certain name appears not only in one input but also using all previous events. For that i have looked into Metrics but i cannot figure out how i might be able to do that. The first problem i have meet is that Names is a string and not an array.

I do not see how i might convert Names into an array and give it to metric. Is there any other solution ?

答:
First of all, please check logstash configuration and add the following  split filter to your logstash.yml file. Your comma separated names will be split while ingesting the data:

```<code>filter {
 split {
   field => "Names"
   terminator => ","
   target => "NamesArray"
 }
}
</code>```

And you can change your mapping. To add a new field to your type mapping like below:

```<code>{
  "properties": {
    ...
    "NamesArray": {
      "type": "keyword"
    }
    ...
  }
}
</code>```

You should use keyword type for NamesArray to get correct metrics about the separated words with the blank character.

Title: Unique count, array to string

Body:
First of all, please check logstash configuration and add the following  split filter to your logstash.yml file. Your comma separated names will be split while ingesting the data:

filter {
 split {
   field => "Names"
   terminator => ","
   target => "NamesArray"
 }
}

And you can change your mapping. To add a new field to your type mapping like below:

{
  "properties": {
    ...
    "NamesArray": {
      "type": "keyword"
    }
    ...
  }
}

You should use keyword type for NamesArray to get correct metrics about the separated words with the blank character.


问:
How to add materialize to angular 2 project?
I am moving from  angular 1.5 to angular 2 for this project while setting up new app i came to this issue so i am adding this library to app.
https://www.npmjs.com/package/angular2-materialize but this one throws error this library is not compatible. I want to use angular materialize that supports angular 2. Any better source or how to implement using above library.

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { StreamComponent } from './stream/stream.component';
import { StreamService } from './stream.service';
import { routing } from './app.routes';
import { MaterializeModule } from "angular2-materialize";
const ROUTES = [
  {
    path: '',
    redirectTo: 'app',
    pathMatch: 'full'
  },
  {
    path: 'stream',
    component: StreamComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
    StreamComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    MaterializeModule
  ],
  providers: [StreamService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

ERROR

```<code>angular-material.js:13 Uncaught TypeError: Cannot read property 'module' of undefined
    at angular-material.js:13
    at angular-material.js:14
    at angular-material.js:36390
(anonymous) @ angular-material.js:13
(anonymous) @ angular-material.js:14
(anonymous) @ angular-material.js:36390
index.js:4 Uncaught ZoneAwareError {__zone_symbol__error: Error: Couldn't find Materialize object on window. It is created by the materialize-css library. Ple…, …}
</code>```

答:
To import materialize you need to add import statement in your code

```<code>import { MaterializeModule } from "angular2-materialize";
</code>```

and after declare it in imports

```<code>@NgModule({
  imports: [
  //...
    MaterializeModule,
  ],
  //...
})
</code>```

I guess in your case problem with import, try to declare MaterializeModule before routing. If it does not help pls provide error message

Body:
I am moving from  angular 1.5 to angular 2 for this project while setting up new app i came to this issue so i am adding this library to app.
https://www.npmjs.com/package/angular2-materialize but this one throws error this library is not compatible. I want to use angular materialize that supports angular 2. Any better source or how to implement using above library.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { StreamComponent } from './stream/stream.component';
import { StreamService } from './stream.service';
import { routing } from './app.routes';
import { MaterializeModule } from "angular2-materialize";
const ROUTES = [
  {
    path: '',
    redirectTo: 'app',
    pathMatch: 'full'
  },
  {
    path: 'stream',
    component: StreamComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
    StreamComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    MaterializeModule
  ],
  providers: [StreamService],
  bootstrap: [AppComponent]
})
export class AppModule { }

ERROR

angular-material.js:13 Uncaught TypeError: Cannot read property 'module' of undefined
    at angular-material.js:13
    at angular-material.js:14
    at angular-material.js:36390
(anonymous) @ angular-material.js:13
(anonymous) @ angular-material.js:14
(anonymous) @ angular-material.js:36390
index.js:4 Uncaught ZoneAwareError {__zone_symbol__error: Error: Couldn't find Materialize object on window. It is created by the materialize-css library. Ple…, …}

Body:
To import materialize you need to add import statement in your code

import { MaterializeModule } from "angular2-materialize";

and after declare it in imports

@NgModule({
  imports: [
  //...
    MaterializeModule,
  ],
  //...
})

I guess in your case problem with import, try to declare MaterializeModule before routing. If it does not help pls provide error message


问:
Cakephp how to find id by value
How can i write this syntax in CakePHP:

Example:

```<code>$userID = "SELECT user_id FROM customers WHERE phone = '88888888' ";
</code>```

like:

```<code>$user = $this->Customer->find('first', array('conditions' => array(
             'Customer.user_id WHERE phone' => '88888888')));
</code>```

I would like to find user_id where the phone number have a specific value

答:
What you're trying to do is really basic, you should read the documentation for the find() function.

```<code>$user = $this->Customer->find('first',  array(
    // You specify which field(s) you want
    'fields' => array('user_id'),
    // You add the condition(s)
    'conditions' => array('Customer.phone' => '88888888'),
));
</code>```

Title: Cakephp how to find id by value

Body:
How can i write this syntax in CakePHP:

Example:

$userID = "SELECT user_id FROM customers WHERE phone = '88888888' ";

like:

$user = $this->Customer->find('first', array('conditions' => array(
             'Customer.user_id WHERE phone' => '88888888')));

I would like to find user_id where the phone number have a specific value

Body:
What you're trying to do is really basic, you should read the documentation for the find() function.

$user = $this->Customer->find('first',  array(
    // You specify which field(s) you want
    'fields' => array('user_id'),
    // You add the condition(s)
    'conditions' => array('Customer.phone' => '88888888'),
));


问:
Is it best-practice to commit the `vendor` directory?
I am using dep to handle my Go dependencies. Is it best practice to also commit the vendor directory into version control? Or is best practice to always execute dep ensure after checking out a repository?

答: I don’t commit for well available sources. Because on this case many commit messages are bloated with changes in vendors. When I want update then I do it and then commit updated Gopkg.*.

ContentLicense: CC BY-SA 4.0


问:
Returning an object of the same class from an overloaded method operation "plus" rather than struct?
I have a MATLAB class that has a simple overloaded plus function, and I can't get it to return an object. I want the function to add each field value together and output an object of the same class, with the field values being sums of the two inputs. When I add the two objects together, I get a struct, not an object. I am new to classes and am likely doing this wrong; any help would be great.

The code is as follows:

```<code>classdef Molar
    properties
        A = 0;
        B = 0;
        C = 0;
    end
    methods
        function M = Molar(val)
           M.A = val;
           M.B = val+1;
           M.C = val+2;
        end
        function M = plus(M1,M2)
            M.A = M1.A + M2.A;
            M.B = M1.B + M2.B;
            M.C = M1.C + M2.C;
        end

    end
end
</code>```

When it runs and I do:

```<code>>> x = Molar(2)
x =
  Molar with properties:

    A: 2
    B: 3
    C: 4
>> y = Molar(3)
y =
  Molar with properties:

    A: 3
    B: 4
    C: 5
</code>```

Then I get a struct when I do the + operation. How can I get this to return another Molar object?

```<code>>> x+y
ans =
  struct with fields:

    A: 5
    B: 7
    C: 9
</code>```

I wonder if it has to do with needing to use the constructor method differently?
 Any help in this regard would be appreciated.

答:
The first parameter should be the returned value:</p>

```<code>function M = plus(M,M2)
    M.A = M.A + M2.A;
    M.B = M.B + M2.B;
    M.C = M.C + M2.C;
end
</code>```

Body:
I have a MATLAB class that has a simple overloaded plus function, and I can't get it to return an object. I want the function to add each field value together and output an object of the same class, with the field values being sums of the two inputs. When I add the two objects together, I get a struct, not an object. I am new to classes and am likely doing this wrong; any help would be great.

The code is as follows:

classdef Molar
    properties
        A = 0;
        B = 0;
        C = 0;
    end
    methods
        function M = Molar(val)
           M.A = val;
           M.B = val+1;
           M.C = val+2;
        end
        function M = plus(M1,M2)
            M.A = M1.A + M2.A;
            M.B = M1.B + M2.B;
            M.C = M1.C + M2.C;
        end

    end
end

When it runs and I do:

>> x = Molar(2)
x =
  Molar with properties:

    A: 2
    B: 3
    C: 4
>> y = Molar(3)
y =
  Molar with properties:

    A: 3
    B: 4
    C: 5

Then I get a struct when I do the + operation. How can I get this to return another Molar object?

>> x+y
ans =
  struct with fields:

    A: 5
    B: 7
    C: 9

I wonder if it has to do with needing to use the constructor method differently?
 Any help in this regard would be appreciated.

Body:
The first parameter should be the returned value:

function M = plus(M,M2)
    M.A = M.A + M2.A;
    M.B = M.B + M2.B;
    M.C = M.C + M2.C;
end


问:
How to match decimal numbers starting with '!' in C++
How do I match all the decimal numbers starting with "!" (bang) in the given string? I have written the following code but it fails with an assert

```<code>#include<iostream>
#include<regex>

int main()
{
    std::string s1("{!112,2,3}");
    std::regex e(R"(\!\d+)", std::regex::grep);

    std::cout << s1 << std::endl;

    std::sregex_iterator iter(s1.begin(), s1.end(), e);
    std::sregex_iterator end;

    while(iter != end)
    {
        std::cout << "size: " << iter->size() << std::endl;

        for(unsigned i = 0; i < iter->size(); ++i)
        {
            std::cout << "the " << i + 1 << "th match" << ": " << (*iter)[i] << std::endl;
        }
        ++iter;
    }
}
</code>```

assert

```<code>terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted (core dumped)
</code>```

答:
First, make sure you are using the latest GCC compiler.

Then use R"(!(\d+))" pattern that matches an exclamation mark and then captures one or more digits Iinto Group 1.

Then just grab (*iter)[1] that holds your values while iterating the matches.

See the C++ demo:

```<code>#include<iostream>
#include<regex>
int main() {
   std::string s1("{!112,2,3} {!346,765,8}");
   std::regex e(R"(!(\d+))");
   std::cout << s1 << std::endl;
   std::sregex_iterator iter(s1.begin(), s1.end(), e); std::sregex_iterator end;
   while(iter != end) {
       std::cout << "Value: " << (*iter)[1] << std::endl;
       ++iter;
    }
}
</code>```

Output:

```<code>{!112,2,3} {!346,765,8}
Value: 112
Value: 346
</code>```

Body:
How do I match all the decimal numbers starting with "!" (bang) in the given string? I have written the following code but it fails with an assert

#include<iostream>
#include<regex>

int main()
{
    std::string s1("{!112,2,3}");
    std::regex e(R"(\!\d+)", std::regex::grep);

    std::cout << s1 << std::endl;

    std::sregex_iterator iter(s1.begin(), s1.end(), e);
    std::sregex_iterator end;

    while(iter != end)
    {
        std::cout << "size: " << iter->size() << std::endl;

        for(unsigned i = 0; i < iter->size(); ++i)
        {
            std::cout << "the " << i + 1 << "th match" << ": " << (*iter)[i] << std::endl;
        }
        ++iter;
    }
}

assert

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted (core dumped)

Body:
First, make sure you are using the latest GCC compiler.

Then use R"(!(\d+))" pattern that matches an exclamation mark and then captures one or more digits Iinto Group 1.

Then just grab (*iter)[1] that holds your values while iterating the matches.

See the C++ demo:

#include<iostream>
#include<regex>
int main() {
   std::string s1("{!112,2,3} {!346,765,8}");
   std::regex e(R"(!(\d+))");
   std::cout << s1 << std::endl;
   std::sregex_iterator iter(s1.begin(), s1.end(), e); std::sregex_iterator end;
   while(iter != end) {
       std::cout << "Value: " << (*iter)[1] << std::endl;
       ++iter;
    }
}

Output:

{!112,2,3} {!346,765,8}
Value: 112
Value: 346


问:
Download all files in a path on Jupyter notebook server
As a user in a class that runs Jupyter notebooks for assignments, I have access to the assignments via the web interface. I assume the assignments are stored somewhere in my personal space on the server, and so I should be able to download them. How can I download all files that are in my personal user space? (e.g., wget)

Here's the path structure:

https://urltoserver/user/username

There are several directories: assignments, data, etc.

https://urltoserver/user/username/assignments

https://urltoserver/user/username/data

...

I want to download all the folders (recursively). Just enough that I can launch whatever I see online locally. If there are some forbidden folders, then ok, skip those and download the rest.

Please specify the command exactly as I couldn't figure it out myself (I tried wget)

答:
Try running this as separate cell in one of your notebooks:

```<code>!tar chvfz notebook.tar.gz *
</code>```

If you want to cover more folders up the tree, write ../ before the * for every step up the directory. The file notebook.tar.gz will be saved in the same folder as your notebook.

Body:
Try running this as separate cell in one of your notebooks:

!tar chvfz notebook.tar.gz *

If you want to cover more folders up the tree, write ../ before the * for every step up the directory. The file notebook.tar.gz will be saved in the same folder as your notebook.


问:
How to combine values of objects with common key in JavaScript?
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

```<code>let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];
</code>```

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

```<code>let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]
</code>```

答:
Here's my two cents.

const sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },

  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },

  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

function mergeDatas(currentObject, rounded_counts) {
  return rounded_counts.map(x => {
    if (currentObject.data.some(y => y[0] === Object.keys(x)[0])) {
      const miniArray = currentObject.data.find(y =>
      y[0] === Object.keys(x)[0]);

      miniArray[1] += x[Object.keys(x)[0]];

      return miniArray;
    }

    return x;
  })
}

const result = sourceData.reduce((tmp, x) => {
  if (tmp.some(t => t.name === x.metric)) {
    const currentObject = tmp.find(y => y.name === x.metric);

    mergeDatas(currentObject, x.rounded_counts);

    return tmp;
  }

  tmp.push({
    name: x.metric,
    data: x.rounded_counts.map(y => {
      const key = Object.keys(y)[0];

      return [key, y[key]];
    }),
  });

  return tmp;
}, []);

console.log(result);```

Body:
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]


问:
How to call a method after so many seconds?
In my project I would like to be able to call a method after 3 minutes have passed. There is no "main loop" to speak of so I cannot use a stopwatch and constantly check if 3 minutes have passed. The only other solution I can think of is a Timer object with an interval of 3 minutes but that seems rather messy because it will only be called once after the 3 minute delay.

Thanks for reading.

Edit: Forgot to mention. This is for a server application so I cannot pause the execution of the thread because other stuff will have to be handled in the meantime. Also, this timer mechanism will not be alone. There may be hundreds of even thousands of concurrent timers at a time.

答:
After trying out several options, the method was not self-triggering. Hence, I used Javascript to solve the same problem as shown below.</p>

```<code><script>
function Timer() {
    $.ajax({
        url: "@Url.Action("Timer", "Exam")",//Method to call. Timer Method in Exam Controller
        type: 'GET', // <-- make a async request by GET
    dataType: 'html', // <-- to expect an html response
    cache: false,
    async: true
    });
}
setInterval(function () { Timer(); }, 5000);//Triggers method Timer() after 5 seconds
</script>
</code>```

Body:
After trying out several options, the method was not self-triggering. Hence, I used Javascript to solve the same problem as shown below.

<script>
function Timer() {
    $.ajax({
        url: "@Url.Action("Timer", "Exam")",//Method to call. Timer Method in Exam Controller
        type: 'GET', // <-- make a async request by GET
    dataType: 'html', // <-- to expect an html response
    cache: false,
    async: true
    });
}
setInterval(function () { Timer(); }, 5000);//Triggers method Timer() after 5 seconds
</script>


问:
How to select one element from each column of a matrix to from a new vector?
I have a M×N matrix A, and a M×1 index vector ind. I want to get a N×1 vector c where c(i) = A(ind(i),i) for i=1,2,...,N.

For example, let

```<code>A = hilb(5);
ind = [2,3,1,4,2]';
</code>```

How can I get vector c?

答:
That's what sub2ind does:

```<code>c = A(sub2ind(size(A), ind(:).', 1:numel(ind)));
</code>```

You can also do it manually to increase speed a little:

```<code>c = A((0:numel(ind)-1) * size(A,1) + ind(:).');
</code>```

To understand how this works, read on linear indexing.

Body:
I have a M×N matrix A, and a M×1 index vector ind. I want to get a N×1 vector c where c(i) = A(ind(i),i) for i=1,2,...,N.

For example, let

A = hilb(5);
ind = [2,3,1,4,2]';

How can I get vector c?

Body:
That's what sub2ind does:

c = A(sub2ind(size(A), ind(:).', 1:numel(ind)));

You can also do it manually to increase speed a little:

c = A((0:numel(ind)-1) * size(A,1) + ind(:).');

To understand how this works, read on linear indexing.


问:
binary '+=': no global operator found when trying to add a object to an array of objects
I am trying to add a Complex number, represented in Complex class to an array of complex.

```<code> #pragma once

    class Complex
    {

    private:
        int re, im;

public:
    Complex() {};
    Complex(int a, int b) { re = a; im = b; }
    Complex(const Complex &);
    Complex& operator=(const Complex &);

    //operators overloading
    bool operator==(Complex);

    //member function
    void print();
};

class Multime
{
private:
    Complex *array;
    static int nrElem;
    int dim;

public:
    Multime();
    Multime(int a) { dim = a; nrElem = 0; array = new Complex[dim]; }
    ~Multime();

    //Operators overloading
    Multime& operator += (Complex b);
    Multime& operator =(const Multime &);

    //member function
    void print();
};
</code>```

Functions.cpp

```<code>#include <iostream>
#include "Multime.h"

using namespace std;

Complex::Complex(const Complex &a)
{
    re = a.re;
    im = a.im;
}

Complex& Complex::operator= (const Complex&a)
{
    re = a.re;
    im = a.im;
    return *this;
}

void Complex::print()
{
    cout << re << "+" << im << "i" << endl;
}

bool Complex::operator==(const Complex a)
{
    return (re == a.re && im == a.im);
}
//Multime
//

Multime::Multime()
{
    dim = 0;
    nrElem = 0;
    array = nullptr;
}

Multime::~Multime()
{
    if (nullptr != array)
    {
        delete[] array;
    }
}

void Multime::print()
{
    for (int i = 0; i < nrElem; ++i)
    {
        array[i].print();
    }
    cout << endl;
}

Multime& Multime::operator +=(Complex a)
{
    int g = 0;
    if (nrElem < dim)
    {
        for (int i = 0; i < nrElem; ++i)
        {
            if (array[i] == a)
            {
                g = 1;
            }
        }
    }
    if (!g) //Element not found, can insert
    {
        array[nrElem++] = a;
    }
    return *this;
}

Multime& Multime::operator =(const Multime & a)
{
    dim = a.dim;
    array = new Complex[dim];
    for (int i = 0; i < nrElem; ++i)
    {
        array[i] = a.array[i];
    }
    return *this;
}
</code>```

In main I wrote the initialization for the static int Multime::nrElem = 0; after preprocessor directivesand and in main(void):

```<code>Multime a[50];
    Complex f(2, 5), b(1, 3), c(5, 4);
    a+=f;
</code>```

but I get the error: binary '+=': no global operator found.I don't wanna use a friend function for +. I tried to create separate functions for + and = but the error is still there.

LE. The problem was in main a it's an array of Multime. Correct one, using initialization constructor: Multime a(50);

答:
```<code>a+=f;
</code>```

is not valid since a is an array of Multime, not an object of type Multime.

If you want to use the operator+= on one object, you could use

```<code>a[0] += f;
</code>```

If you want to use it for all the objects in the array, use a loop.

```<code>for ( auto& item : a )
{
   item += f;
}
</code>```

Body:
I am trying to add a Complex number, represented in Complex class to an array of complex.

 #pragma once

    class Complex
    {

    private:
        int re, im;

public:
    Complex() {};
    Complex(int a, int b) { re = a; im = b; }
    Complex(const Complex &);
    Complex& operator=(const Complex &);

    //operators overloading
    bool operator==(Complex);

    //member function
    void print();
};

class Multime
{
private:
    Complex *array;
    static int nrElem;
    int dim;

public:
    Multime();
    Multime(int a) { dim = a; nrElem = 0; array = new Complex[dim]; }
    ~Multime();

    //Operators overloading
    Multime& operator += (Complex b);
    Multime& operator =(const Multime &);

    //member function
    void print();
};

Functions.cpp

#include <iostream>
#include "Multime.h"

using namespace std;

Complex::Complex(const Complex &a)
{
    re = a.re;
    im = a.im;
}

Complex& Complex::operator= (const Complex&a)
{
    re = a.re;
    im = a.im;
    return *this;
}

void Complex::print()
{
    cout << re << "+" << im << "i" << endl;
}

bool Complex::operator==(const Complex a)
{
    return (re == a.re && im == a.im);
}
//Multime
//

Multime::Multime()
{
    dim = 0;
    nrElem = 0;
    array = nullptr;
}

Multime::~Multime()
{
    if (nullptr != array)
    {
        delete[] array;
    }
}

void Multime::print()
{
    for (int i = 0; i < nrElem; ++i)
    {
        array[i].print();
    }
    cout << endl;
}

Multime& Multime::operator +=(Complex a)
{
    int g = 0;
    if (nrElem < dim)
    {
        for (int i = 0; i < nrElem; ++i)
        {
            if (array[i] == a)
            {
                g = 1;
            }
        }
    }
    if (!g) //Element not found, can insert
    {
        array[nrElem++] = a;
    }
    return *this;
}

Multime& Multime::operator =(const Multime & a)
{
    dim = a.dim;
    array = new Complex[dim];
    for (int i = 0; i < nrElem; ++i)
    {
        array[i] = a.array[i];
    }
    return *this;
}

In main I wrote the initialization for the static int Multime::nrElem = 0; after preprocessor directivesand and in main(void):

Multime a[50];
    Complex f(2, 5), b(1, 3), c(5, 4);
    a+=f;

but I get the error: binary '+=': no global operator found.I don't wanna use a friend function for +. I tried to create separate functions for + and = but the error is still there.

LE. The problem was in main a it's an array of Multime. Correct one, using initialization constructor: Multime a(50);

Body:
a+=f;

is not valid since a is an array of Multime, not an object of type Multime.

If you want to use the operator+= on one object, you could use

a[0] += f;

If you want to use it for all the objects in the array, use a loop.

for ( auto& item : a )
{
   item += f;
}


问:
Master Page changes not reflected for other logged in users in sharepoint online 2013?
I have created a master page using sharepoint designer 2013. I am able to edit the page.But whenever any changes are made they are only reflected on the view of administrators site. Changes are not reflected/visible to other user who logs into the site
How to reflet the changes throughout ? </p>

答: You need to "publish" and "approve" your changes. I'm not sure if Sharepoint Designer allows you to do this. You can do it in Site Settings -> Web Designer Galleries/Master pages and page layouts. Select your master page, then publish, then approve it (use corresponding toolbar options for these). </p>