Sunday 26 January 2020

No component factory found for [object Object]. Did you add it to @NgModule.entryComponents?

I understand that this will probably be marked as a duplicate as it has been asked many times on various forums i.e.
Error: No component factory found for [object Object]
https://mdbootstrap.com/support/angular/no-component-factory-found-for-modalbackdropcomponent/
https://github.com/akveo/ngx-admin/issues/2139
And many more.
The problem is that none of the answers online helped me resolve my issue and hence why I'm submitting another question.
When the user clicks on the Edit button below I'm wanting a modal containing a form to pop up to allow the user to edit the fields.
Media Messsage Table (Edit Button highlighted in yellow)
From my research, I sort understand what cause this and I think its to do with calling a component that is missing from the entryConponents parameter in the app.module.ts file. I have had this issue before but instead of [object] [object] at the end it was a specific component name. With this one it was easy to fix because I knew exactly which component was missing from the entryCompoents.
Please see below my media.component.ts. For the experienced angular programmers, I am aware that jquery is the absolute worst thing to use with angular but as DataTables is jquery based it was a last resort.
 import { Component, OnInit } from '@angular/core';
 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
 import { Media } from '../../../classes/media';
 import { MediaService } from '../../../services/media/media.service';
 import { MediaEdit } from '../../../classes/media-edit';
 import { MediaModalComponent } from '../media-modal/media-modal.component';
 import * as $ from 'jquery';
 import 'datatables.net';
 import 'datatables.net-bs4';

 @Component({
   selector: 'app-media',
   templateUrl: './media.component.html',
   styleUrls: ['./media.component.css'],
   providers: [
     MediaService, 
     MediaModalComponent,
     NgbModal
   ],
   entryComponents: [MediaModalComponent]
 })
 export class MediaComponent implements OnInit {

   media$: Array<Media> = []; 
   media: Media;
   mediaEdit: MediaEdit;
   dtOptions: any = {}

   constructor(
     private MediaService: MediaService,
     private modalService: NgbModal,
     private MediaModal: MediaModalComponent
   ) { }

    open(code,desc,type,message) {  
     this.modalService.open(
       this.MediaModal,
       {
         size: 'xl',
         windowClass: 'custom-class'
       });

       this.MediaModal.mediaForm.patchValue({
        code: code,
        desc: desc,
        type: type,
        message: message
       });

    }

   ngOnInit() {
     this.getMediaData();
     this.dtOptions = {
       select: true,  
       colReorder: {
         order: [1, 0, 2],
         fixedColumnsRight: 2
     }
   }
   }

   getMediaData(){
     return this.MediaService.getMedia()
       .subscribe(data => this.processMedia(data));
   }

   processMedia(rawData){
     /* get the number of users from the temp-table returned */
     const numRecs = rawData.ttMedia[0].mm_count;

     for(let i = 0; i < numRecs; i++) {
       this.media = rawData.ttMedia[i];
       this.media$.push(this.media);

     }
   }



   editMedia(){
       $('#mediaTable tbody').on('click', 'tr', (element) => {

           let data = $('#mediaTable').DataTable().row( element.currentTarget ).data();
           let code = data[0];
           let desc = data[1];
           let type = "";
           if(data[3] = "yes") {
             type = "SMS";
           } else if(data[4] = "yes") {
             type = "Email";
           }

           let message = data[5];
           this.open(code,desc,type,message);


         }
         );

   }



 }
Please see below my media-modal.component.ts. This the ts file that contains the content for the modal.
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DbField } from '../../../classes/db-field';
import { DbFieldsService } from '../../../services/dbFields/db-fields.service';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-media-modal',
  templateUrl: './media-modal.component.html',
  styleUrls: ['./media-modal.component.css'],
  providers: [
    DbFieldsService
  ]
})

export class MediaModalComponent implements OnInit {

  mediaForm: FormGroup;
  dbFields$: Array<DbField> = [];
  dbField: DbField;
  loaded:string = "";


  constructor(
    private fb: FormBuilder,
    public activeModal: NgbActiveModal,
    private DbFieldsService: DbFieldsService
  ) {

    this.mediaForm = this.fb.group({
      type: ['', Validators.required],
      code: ['', Validators.required],
      description: ['', Validators.required],
      file: ['', Validators.required],
      dbFieldValue: ['', Validators.required],
      message: ['', Validators.required]
    });

   }

   getDbFields(){
     return this.DbFieldsService.getFields()
        .subscribe(data => this.processFields(data));
   }

   processFields(rawData){
     const numRecs = rawData.ttFields[0].mmf_count;

     for(let i = 0; i < numRecs; i++) {
       this.dbField = rawData.ttFields[i];
       this.dbFields$.push(this.dbField);

     }
     this.loaded = "true";

   }

   addField(){

     let newMessage = this.mediaForm.value.message + String.fromCharCode(171) + 
     this.mediaForm.value.dbFieldValue + String.fromCharCode(187);
     let test = this.mediaForm.value.description + " " + this.mediaForm.value.description;

  this.mediaForm.patchValue({
      message: newMessage
  });

  }

  ngOnInit() {
    this.getDbFields();
  }

}
Please see below my app.module.ts file which apparently is missing a component from entryComponents...
/* Standard Modules */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

/* Navigation Modules */import { AppRoutingModule } from './app-routing.module';
import { RouterModule, Routes } from '@angular/router';

/* other features/styles */
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { DataTablesModule } from 'angular-datatables';
import { NgbModule, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';


/* SyncFusion Modules */
import { SidebarModule } from '@syncfusion/ej2-angular-navigations';

/* components/services within the app */
import { LoginComponent } from './views/login/login.component';
import { NavbarComponent } from './views/navbar/navbar.component';
import { NewuserComponent } from './views/newuser/newuser.component';
import { HomeComponent } from './views/home/home.component';
import { AdminComponent } from './views/admin/admin.component';
import { ClientComponent } from './views/staff-views/client/client.component';
import { PortalComponent } from './views/portal/portal.component';
import { StaffComponent } from './views/staff/staff.component';
import { AppointmentsComponent } from './views/staff-views/appointments/appointments.component';
import { SettingsComponent } from './views/staff-views/settings/settings.component';
import { LoginService } from './services/login/login.service';
import { ClientService } from './services/clients/client.service';
import { ConstantsService } from './services/constants/constants.service';
import { FunctionsService } from './services/functions/functions.service';
import { ValUserService } from './services/valUser/val-user.service';
import { MediaComponent } from './views/staff-views/media/media.component';
import { DbFieldsService } from './services/dbFields/db-fields.service';
import { MediaService } from './services/media/media.service';
import { MediaModalComponent } from './views/staff-views/media-modal/media-modal.component';



@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    NavbarComponent,
    NewuserComponent,
    HomeComponent,
    AdminComponent,
    ClientComponent,
    PortalComponent,
    StaffComponent,
    AppointmentsComponent,
    SettingsComponent,
    MediaComponent,
    MediaModalComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    SidebarModule,
    DataTablesModule,
    NgbModule
  ],

  providers: [
    LoginService,
    ClientService,
    ConstantsService,
    FunctionsService,
    ValUserService,
    DbFieldsService,
    MediaService,
    NgbActiveModal,
    MediaModalComponent

  ],
  bootstrap: [AppComponent],
  entryComponents: [
    MediaModalComponent,
  ]
})
export class AppModule { }
Finally, last thing to say is that I'm fairly new to angular and I'm sort of learning and developing this product at the same time.
Any help/advice would be much appreciated and thanks in advance for your comments and suggestions.


from No component factory found for [object Object]. Did you add it to @NgModule.entryComponents?

Saturday 25 January 2020

Using Webpack to minify jQuery files & update references into HTML?

I've approx 10 individual pages, with library references & custom jQuery codes included in each HTML files separately.

  1. Can Webpack be used for minifying Javascript files.
  2. Transform references of .js files into .min.js in all my HTMLs during build?

All search references w.r.t webpack points out to ES6 modules which are kick-started using index.js, I've got none :-(



from Using Webpack to minify jQuery files & update references into HTML?

How to use MediaRecorder as MediaSource

As an exercise in learning WebRTC I am trying to to show the local webcam and side by side with a delayed playback of the webcam. In order to achieve this I am trying to pass recorded blobs to a BufferSource and use the corresponding MediaSource as source for a video element.

// the ondataavailable callback for the MediaRecorder
async function handleDataAvailable(event) {
  // console.log("handleDataAvailable", event);
  if (event.data && event.data.size > 0) {
    recordedBlobs.push(event.data);
  }

  if (recordedBlobs.length > 5) {
    if (recordedBlobs.length === 5)
      console.log("buffered enough for delayed playback");
    if (!updatingBuffer) {
      updatingBuffer = true;
      const bufferedBlob = recordedBlobs.shift();
      const bufferedAsArrayBuffer = await bufferedBlob.arrayBuffer();
      if (!sourceBuffer.updating) {
        console.log("appending to buffer");
        sourceBuffer.appendBuffer(bufferedAsArrayBuffer);
      } else {
        console.warn("Buffer still updating... ");
        recordedBlobs.unshift(bufferedBlob);
      }
    }
  }
}
// connecting the media source to the video element
recordedVideo.src = null;
recordedVideo.srcObject = null;
recordedVideo.src = window.URL.createObjectURL(mediaSource);
recordedVideo.controls = true;
try {
  await recordedVideo.play();
} catch (e) {
  console.error(`Play failed: ${e}`);
}

All code: https://jsfiddle.net/43rm7258/1/

When I run this in Chromium 78 I get an NotSupportedError: Failed to load because no supported source was found. from the play element of the video element.

I have no clue what I am doing wrong or how to proceed at this point.

This is about something similar, but does not help me: MediaSource randomly stops video

This example was my starting point: https://webrtc.github.io/samples/src/content/getusermedia/record/



from How to use MediaRecorder as MediaSource

How to use nox with poetry?

I want to use nox in my project managed with poetry.

What is not going well is that installing dev dependency in nox session.

I have the noxfile.py as shown below:

import nox
from nox.sessions import Session
from pathlib import Path

__dir__ = Path(__file__).parent.absolute()


@nox.session(python=PYTHON)
def test(session: Session):
    session.install(str(__dir__))  # I want to use dev dependency here
    session.run("pytest")

How can I install dev dependency in nox session?



from How to use nox with poetry?

How to get an Audio Stream from Media Recorder in android

I want to make streaming audio recorder in android. I am not sure how to fetch audio stream and how to set buffer size of audio stream.

Below is my media recorder class

public class MyMediaRecorder {

    final MediaRecorder recorder = new MediaRecorder();
    final File path;

    /**
     * Creates a new audio recording at the given path (relative to root of SD
     * card).
     */
    public MyMediaRecorder(File path) {
        this.path = path;
    }



    /**
     * Starts a new recording.
     */
    public void start() throws IOException {
        String state = android.os.Environment.getExternalStorageState();
        if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
            throw new IOException("SD Card is not mounted.  It is " + state
                    + ".");
        }

        // make sure the directory we plan to store the recording in exists


        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(path.getAbsolutePath());
        recorder.prepare();
        recorder.start();
    }

    /**
     * Stops a recording that has been previously started.
     */
    public void stop() throws IOException {
        recorder.stop();
        recorder.release();
    }
}

on start of recording i need to fetch a buffer size and sent it to server parallely record audio. Should I use Audio Record and Audio track instaed of Media Recorder ? Please suggest what should i do



from How to get an Audio Stream from Media Recorder in android

turn video frames to streaming video

The server is sending video frame. I would like to use them in order to do a streaming. I wonder how I could assemble the frames to create a streaming video. So far, I could display the frames as pictures. Below is my angular code

component angular

 getVideo() {
    interval(250).switchMap(() => this.appService.getPictures())
      .subscribe(data => {
        const file = new Blob([data], {type:'image/png'});
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(file));
      })
  }

template html

<img div="test" [src]="url" width="400px" height="300px"/>

I am trying to change the picture using the frame rate of the camera. But my picture is not updated and it freezes my browser due to the high number of http requests.

What I want to achieve is to buffer the frame in order to use the video tag instead of the img tag the same way I would connect to a live streaming send by a server using the video tag with src set to the url of the server.

Github link: https://github.com/kedevked/frameProcessing



from turn video frames to streaming video

Python logging - filter log messages for all loggers

I have a project where the underlying tools are logging, and I'm also logging (with different logger instances).

However, sometimes the logger I don't have access to exposes information which I'd like to strip out of the log (or replace with a placeholder).

Is there a way I can use a filter to do that for all python loggers in a project?

Here is my logging configuration in Django:

LOGGING_CONFIG = None
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "my_formatter": {
            "format": "[%(asctime)s] %(message)s",
            "datefmt": "%d/%b/%Y %H:%M:%S",
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "my_formatter",
        },
    },
    "loggers": {
        "my_logger": {
            "handlers": ["console"],
            "level": "DEBUG"
        },
    },
}

logging.config.dictConfig(LOGGING)

Really, my end goal is just to prevent certain things from popping up in logs by replacing them – if there's some other way to do that, feel free to share it.

Thanks!



from Python logging - filter log messages for all loggers

How to replace spaces in URL having path parameter, with a hyphen or an underscore

I am sorry if this Q makes no sense , but is there a way to replace spaces with hyphen in URL's(only) having used path parameter to build it ?

My scenario is as :

I have a view method as below:

from app.service import *

@app.route('/myapp/<search_url>',methods=['GET','POST'])
def search_func(search_url):
    print(search_url) // This prints 'hi-martin king' and i need to pass 'hi-martin king' to below with preserving space
    search_q = search(search_url) 
    return render_template('wordsearch.html',data=search_q['data'])
  • here search_url I am passing from template

I have the search function which takes search_url as argument(def search(search_url): .....) and does all operations (for ref) which i have imported from service above.

Now when I run , i have the sample URL as,

....myapp/hi-martin%20king

Here I am preserving space to perform query in database (In db it is stored as martin king), but I don't want to show the same in URL instead replace it with a hyphen

I have other way that changing all the values in database (removing spaces but this is tmk not a appropriate solution)

expected o/p:

....myapp/hi-martin-king  (or with an underscore) ....myapp/hi-martin_king 

Here how can i preserve spaces to pass it as argument to the function and at the same time I want to replace only in URL ? Is this possible ?

Any help is appreciated ....TIA



from How to replace spaces in URL having path parameter, with a hyphen or an underscore

Why Google authentication token refresh keeps failing recently in Azure Mobile Apps SDK for Android

I have an android app implementing the azure mobile SDK (com. microsoft. azure: azure-mobile-android:3.5.1@aar) In my app I use the Google authentication method with refresh tokens (as described in Azure Mobile Apps documentation). The authentication had been working fine for nearly 2 years. For the last 10 days(no changes have been made), my users can no more refresh their auth tokens if the last refresh was made 60 minutes or more ago. The refresh succeeds only if it is called sooner than 1 hour. If the refresh fails, as it frequently does, I must force the user to sign-in again using the Google consent screen in order to get a new token. This was not happening before, as the tokens could be refreshed even days after the last refresh. What could be wrong? My Azure Service Plan is type D1: Shared.
The users see this error message in their android device, if the refreshUser() method is called more than 1 hour after the last refresh:
Google authentication refresh failed.Refresh failed with a 401 Unauthorized error. Credentials are no longer valid.
In the Log Stream (in portal.azure) I see the following message:
HTTP Error 401.83 - Unauthorized You do not have permission to view this directory or page.Most likely causes:The authenticated user does not have access to a resource needed to process the request.Things you can try:Create a tracing rule to track failed requests for this HTTP status code.
This is my authenticate method:
private void authenticate() {
// Sign in using the Google provider.
HashMap parameters = new HashMap<>();
parameters.put("access_type", "offline");
parameters.put("prompt", "consent");
mClient.login(MobileServiceAuthenticationProvider.Google, url_scheme_of_your_app, GOOGLE_LOGIN_REQUEST_CODE, parameters); 
}
This is my refresh token method following the Mobile Apps documentation:
private void refreshToken(){mClient.refreshUser(new UserAuthenticationCallback() {
    @Override
    public void onCompleted(MobileServiceUser user, Exception exception, ServiceFilterResponse response) {
    if (user != null && exception == null) {
    /*refresh succeeded*/
    } else { 
    /*refresh failed*/
    String message = "+"%s authentication refresh failed.Error: %s", "Google",exception.getMessage())";}}}); }
Authentication settings in Azure portal: enter image description here


from Why Google authentication token refresh keeps failing recently in Azure Mobile Apps SDK for Android

Friday 24 January 2020

How to move a photo/video to an album with Flutter on mobile (iOS and Android)?

Using Flutter on mobile (iOS and Android), how can I move media to an album?

I tried to combine gallery_saver and photo_manager on iOS:

  1. I read a media AssetEntity from Recents
  2. Saved the AssetEntity file under an album with GallerySaver.saveImage. At this point Recents showed the same media twice, makes sense.
  3. Attempted to delete with PhotoManager.editor.deleteWithIds the original AssetEntity file, and it showed a native popup asking the user if it's ok to delete the media. Bad user experience...

Is there a way to change AssetEntity album, without creating a new file?



from How to move a photo/video to an album with Flutter on mobile (iOS and Android)?

Difference between accessing variable inside a function by passing as argument and global variable?

What is the difference of accessing variables inside the function by as argument and without argument?

var a = 1;
var b = 2;

function x() {
    var c = a + b;
    console.log(c)
}

function y(a, b) {
    var c = a + b;
    console.log(c)
}


from Difference between accessing variable inside a function by passing as argument and global variable?

Animation-list does not work with custom drawables

I have an animation list that is working fine, however it's using from the google default vector drawables:

enter image description here

As you can see these are the default vector drawables provided by google. It's the wifi drawable at different stages defined by the colors 0%, 33%, 66%, 99%. But as soon as I use custom drawables with photoshopped colors the animation-list longer works:

enter image description here

The above doesn't create an animation at all. All my java code is the same, the first picture is all imported .SVG second image is also all imported .SVG. How come the second one with custom images doesn't work?



from Animation-list does not work with custom drawables

Laravel: how to sort by related model with pagination & filter

It's been three days that I block on my configuration. I can not sort by model reported, I tried many methods but nothing conclusive, for example, sortBy / sortByDesc, join table but no solution

I want to perform paging, sorting, and server-side filters. Filters can be multiple. Everything works except sort by the related model I get the URL: http://127.0.0.1:8000/api/user/list?page=1&limit=30&sort=user__created_at&direction=desc&search__user__name=James&search__group__name=Client

the query search__model__col allows me to chain several searches on several models or columns

Here is my code :

    public static function pagination(Request $request, $model, $relation, $modelStringify)
    {
        $modelSortBy = explode('__', $request->query('sort'))[0]; // user
        $tableSortBy = explode('__', $request->query('sort'))[1]; // created_at
        $query       = $request->query(); // ['page' => 1, 'limit' => 30...]
        $direction   = $request->query('direction'); // desc
        try {

            $model = $model->with($relation);

            //TODO : orderBy relationship
            if ($modelSortBy === $modelStringify): // modelStringify = 'user'
                $model->orderBy($tableSortBy, $direction);
            else:
                 // sort server side here 
            endif;

            foreach (array_keys($query) as $q) {
                if (strpos($q, 'search__') === 0) {
                    $modelSearchBy = explode('__', $q)[1]; // ['user', 'group']
                    $tableSearchBy = explode('__', $q)[2]; // ['name', 'name']
                    $valueSearchBy = $query[$q];
                    if ($modelSearchBy === $modelStringify):
                        $model->where($tableSearchBy, 'like', $valueSearchBy . '%');
                    else:
                        $model->whereHas($modelSearchBy, function (Builder $q) use ($valueSearchBy, $tableSearchBy) {
                            $q->where($tableSearchBy, 'like', $valueSearchBy . '%'); // $valueSearchBy = ['James', 'Client']
                        });
                    endif;
                }
            }
            return $model;
        } catch (Exception $e) {
            return response()->json(['message' => $e], 400);
        }
    }

Here is an example for user belongsTo group :

return response()->json([
    'items' => Utils::pagination($request, new User(), [
        'group',
    ], 'user')->paginate($limit)->toArray()
]);

How can I introduce the sort by the related model in this configuration?

For example, for sorted by group name, I get the URL &sort=group__name

Thank you



from Laravel: how to sort by related model with pagination & filter

How do I get an secondary list item from ThreadPoolExecutor while sending requests?

Using the python documentation on ThreadPoolExecutor there is this request function:

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

And if the URL list was adjusted as such:

URLS = [['http://www.foxnews.com/','American'],
        ['http://www.cnn.com/','American'],
        ['http://europe.wsj.com/', 'European'],
        ['http://www.bbc.co.uk/', 'Eurpoean']
        ['http://some-made-up-domain.com/','Unknown']]

You can easily pull the URL by indexing the list:

future_to_url = {executor.submit(load_url, url, 60): url[0] for url in URLS}

What I'm struggling with is how would I go about extracting the region from this list (index 1) to be included in as_completed result so the print is something like:

print('%r %r page is %d bytes' % (region, url, len(data))


from How do I get an secondary list item from ThreadPoolExecutor while sending requests?

how to display modal window in nativescript-vue

I have a nativescript-vue app where I call a vue file to populate a grid, and when selected, return that value. That all works beautifully the first time (thanks to this work).

Here is how I call it from the parent window:

 this.$showModal(MyListView, { props: { apropValue : this.apropValue }, fullscreen: true }
                        ).then(data => this.myvalue = data);

In the MyListView.vue file I load a GridLayout that displays properly and returns the selected value as desired.

<ListView for="item in items" class="list-group"  @itemTap="onItemListTap">
...
 onItemListTap(args) {               
    this.$modal.close(args.item);
 }

So far so good, but I am seeing a weird behavior when I run it on my iOS device. The first time, this works great. But next time I call it I see this in the console and do not see the modal:

CONSOLE ERROR file:///node_modules/tns-core-modules/trace/trace.js:178:30: ViewHierarchy: Parent is already presenting view controller. Close the current modal page before showing another one!

I cannot find any example of how to close a current modal page since I am already closing it. Interestingly, even after I close the app, rebuild and restart on my device it shows that error again and doesn't show the modal.

Can anyone see what I am doing wrong?



from how to display modal window in nativescript-vue

Uploading a file in an array of object using Retrofit 2

I use Retrofit2 and I need to upload various files using file in an array of objects Media like this :

{
   "state" = "done",
   "medias" = [
     {
      "file" = THE_FILE1
     },
     {
      "file" = THE_FILE2
     },
     {
      "file" = THE_FILE3
     }
   ]
}

This is the function of my Interface :

@Multipart
@POST("api/exercice/{id}")
fun submitExercice(
    @Path("id") id: Int,
    @Header("Authorization") token: String,
    @Body data: AnswerExercice
): Call<Void>

And this is my object Media :

    data class AnswerExercice(
    val state: String = "done",
    val medias: List<Media>
) : Serializable {
    data class Media(
        @Part val file: MultipartBody.Part
    ) : Serializable
}

But I have this error :

@Body parameters cannot be used with form or multi-part encoding. (parameter #3)

What am i not doing well?



from Uploading a file in an array of object using Retrofit 2

turn video frames to streaming video

The server is sending video frame. I would like to use them in order to do a streaming. I wonder how I could assemble the frames to create a streaming video. So far, I could display the frames as pictures. Below is my angular code

component angular

 getVideo() {
    interval(250).switchMap(() => this.appService.getPictures())
      .subscribe(data => {
        const file = new Blob([data], {type:'image/png'});
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(file));
      })
  }

template html

<img div="test" [src]="url" width="400px" height="300px"/>

I am trying to change the picture using the frame rate of the camera. But my picture is not updated and it freezes my browser due to the high number of http requests.

What I want to achieve is to buffer the frame in order to use the video tag instead of the img tag the same way I would connect to a live streaming send by a server using the video tag with src set to the url of the server.

Github link: https://github.com/kedevked/frameProcessing



from turn video frames to streaming video

Mock out imported Lazy React component

Here's my lazy component:

const LazyBones = React.lazy(() => import('@graveyard/Bones')
  .then(module => ({default: module.BonesComponent}))
export default LazyBones

I'm importing it like this:

import Bones from './LazyBones'

export default () => (
<Suspense fallback={<p>Loading bones</p>}>
  <Bones />
</Suspense>
)

And in my test I have this kind of thing:

import * as LazyBones from './LazyBones';

describe('<BoneYard />', function() {
  let Bones;
  let wrapper;
  beforeEach(function() {
    Bones = sinon.stub(LazyBones, 'default');
    Bones.returns(() => (<div />));
    wrapper = shallow(<BoneYard />);
  });
  afterEach(function() {
    Bones.restore();
  });

  it('renders bones', function() {
    console.log(wrapper)
    expect(wrapper.exists(Bones)).to.equal(true);
  })

})

What I expect is for the test to pass, and the console.log to print out:

<Suspense fallback=>
  <Bones />
</Suspense>

But instead of <Bones /> I get <lazy /> and it fails the test.

How can I mock out the imported Lazy React component, so that my simplistic test passes?



from Mock out imported Lazy React component

Create a simple cylinder using command-line FreeCAD

I would like to create a simple pillar in FreeCAD using python and the export it as .stl file enter image description here What have I done so far?
  1. Recorded a macro of me creating a cylinder (Part) and exporting it as an stl file. der
  2. I copy and paste the text from the macro into a python file, which I named "pillar.py"
Here is the code:
# -*- coding: utf-8 -*-

+++++++++++++++++++++++++++++++++++++++++++++++++
import FreeCAD
import Part
import Mesh


App.ActiveDocument.addObject("Part::Cylinder","Cylinder")
App.ActiveDocument.ActiveObject.Label = "Cylinder"
App.ActiveDocument.recompute()

__objs__=[]
__objs__.append(FreeCAD.getDocument("Unnamed").getObject("Cylinder"))
Mesh.export(__objs__,u"C:/Users/totyped/Desktop/pillar_2.stl")

del __objs__
+++++++++++++++++++++++++++++++++++++++++++++++++
  1. I closed the GUI and open the terminal, and I type:
    "C:\Program Files\FreeCAD 0.18\bin\FreeCADCmd.exe" "C:\Users\totyped\Documents\pillar.py"
Source: https://forum.freecadweb.org/viewtopic.php?t=23869
The result: It just shows this on the terminal, but does not create any stl file.
enter image description here
It also does not give any warning or error message...
Any help to make this work, would be highly appreciated.
IMPORTANT: SO, I noticed that it will work, if I put the script file into the same directory as FreeCADmd.exe. Why ? I have no clue...
EDIT: So, as suggested by @sliptonic I tried to change the script file to:
import FreeCAD
import Part
import Mesh

App.newDocument("Unnamed")
App.ActiveDocument.addObject("Part::Cylinder","Cylinder")
App.ActiveDocument.ActiveObject.Label = "Cylinder"
App.ActiveDocument.recompute()

__objs__=[]
__objs__.append(FreeCAD.getDocument("Unnamed").getObject("Cylinder"))
Mesh.export(__objs__,u"pillar_2.stl")

del __objs__
but I still did not get any cylinder. Maybe the log file can help? Here it is:
Msg: FreeCAD 0.18, Libs: 0.18R4 (GitTag)
(c) Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2019
  #####                 ####  ###   ####  
  #                    #      # #   #   # 
  #     ##  #### ####  #     #   #  #   # 
  ####  # # #  # #  #  #     #####  #   # 
  #     #   #### ####  #    #     # #   # 
  #     #   #    #     #    #     # #   #  ##  ##  ##
  #     #   #### ####   ### #     # ####   ##  ##  ##

Log: Time = Wed Jan 22 10:17:07 2020
Log: AppDataSkipVendor = true
Log: AppHomePath = C:/Program Files/FreeCAD 0.18/
Log: AppTempPath = C:\Users\Henry\AppData\Local\Temp\
Log: BinPath = C:/Program Files/FreeCAD 0.18/bin\
Log: BuildRepositoryURL = git://github.com/FreeCAD/FreeCAD.git releases/FreeCAD-0-18
Log: BuildRevision = 4 (GitTag)
Log: BuildRevisionBranch = releases/FreeCAD-0-18
Log: BuildRevisionDate = 2019/10/22 16:53:35
Log: BuildRevisionHash = 980bf9060e28555fecd9e3462f68ca74007b70f8
Log: BuildVersionMajor = 0
Log: BuildVersionMinor = 18
Log: CopyrightInfo = (c) Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2019
  #####                 ####  ###   ####  
  #                    #      # #   #   # 
  #     ##  #### ####  #     #   #  #   # 
  ####  # # #  # #  #  #     #####  #   # 
  #     #   #### ####  #    #     # #   # 
  #     #   #    #     #    #     # #   #  ##  ##  ##
  #     #   #### ####   ### #     # ####   ##  ##  ##


Log: Debug = 0
Log: DocPath = C:/Program Files/FreeCAD 0.18/doc\
Log: ExeName = FreeCAD
Log: ExeVendor = FreeCAD
Log: ExeVersion = 0.18
Log: LoggingFile = 1
Log: LoggingFileName = C:\Users\Henry\AppData\Roaming\FreeCAD\FreeCAD.log
Log: OpenFile0 = pillar.py
Log: OpenFileCount = 1
Log: PATH = C:\Program Files\FreeCAD 0.18\bin\Library\bin;C:\Users\Henry\Anaconda3;C:\Users\Henry\Anaconda3\Library\mingw-w64\bin;C:\Users\Henry\Anaconda3\Library\usr\bin;C:\Users\Henry\Anaconda3\Library\bin;C:\Users\Henry\Anaconda3\Scripts;C:\Users\Henry\Anaconda3\bin;C:\Users\Henry\Anaconda3\condabin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\MATLAB\R2019a\bin;C:\Program Files\NVIDIA Corporation\NVIDIA NGX;C:\Program Files\MATLAB\MATLAB Runtime\v94\runtime\win64;C:\Program Files (x86)\Wolfram Research\WolframScript;C:\Program Files (x86)\QuickTime\QTSystem;C:\Users\Henry\AppData\Local\Microsoft\WindowsApps;C:\Users\Henry\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64
Log: PythonSearchPath = C:\Program Files\FreeCAD 0.18\bin\python36.zip;C:\Program Files\FreeCAD 0.18\bin\DLLs;C:\Program Files\FreeCAD 0.18\bin\lib;C:\Program Files\FreeCAD 0.18\bin
Log: RunMode = Exit
Log: SystemParameter = C:\Users\Henry\AppData\Roaming\FreeCAD\system.cfg
Log: UserAppData = C:\Users\Henry\AppData\Roaming\FreeCAD\
Log: UserHomePath = C:\Users\Henry\Documents
Log: UserParameter = C:\Users\Henry\AppData\Roaming\FreeCAD\user.cfg
Log: Verbose = 
Log: Create Application
Log: Run App init script
Log: Init: starting App::FreeCADInit.py
Log: Init:   Searching for modules...
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\AddonManager... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Arch... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Complete... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Draft... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Drawing... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Fem... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Idf... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Image... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Import... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Inspection... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Material... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Measure... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Mesh... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\MeshPart... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\OpenSCAD... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Part... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\PartDesign... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Path... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Plot(Init.py not found)... ignore
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Points... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Raytracing... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Robot... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Ship(Init.py not found)... ignore
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Show(Init.py not found)... ignore
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Sketcher... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Spreadsheet... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Start... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Surface... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\TechDraw... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Test... done
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Tux(Init.py not found)... ignore
Log: Init:      Initializing C:\Program Files\FreeCAD 0.18\Mod\Web... done
Log: Using C:\Program Files\FreeCAD 0.18\Mod as module path!
Log: System path after init:
Log:    C:\Program Files\FreeCAD 0.18\bin
Log:    C:\Program Files\FreeCAD 0.18\Mod\AddonManager
Log:    C:\Program Files\FreeCAD 0.18\Mod\Arch
Log:    C:\Program Files\FreeCAD 0.18\Mod\Complete
Log:    C:\Program Files\FreeCAD 0.18\Mod\Draft
Log:    C:\Program Files\FreeCAD 0.18\Mod\Drawing
Log:    C:\Program Files\FreeCAD 0.18\Mod\Fem
Log:    C:\Program Files\FreeCAD 0.18\Mod\Idf
Log:    C:\Program Files\FreeCAD 0.18\Mod\Image
Log:    C:\Program Files\FreeCAD 0.18\Mod\Import
Log:    C:\Program Files\FreeCAD 0.18\Mod\Inspection
Log:    C:\Program Files\FreeCAD 0.18\Mod\Material
Log:    C:\Program Files\FreeCAD 0.18\Mod\Measure
Log:    C:\Program Files\FreeCAD 0.18\Mod\Mesh
Log:    C:\Program Files\FreeCAD 0.18\Mod\MeshPart
Log:    C:\Program Files\FreeCAD 0.18\Mod\OpenSCAD
Log:    C:\Program Files\FreeCAD 0.18\Mod\Part
Log:    C:\Program Files\FreeCAD 0.18\Mod\PartDesign
Log:    C:\Program Files\FreeCAD 0.18\Mod\Path
Log:    C:\Program Files\FreeCAD 0.18\Mod\Plot
Log:    C:\Program Files\FreeCAD 0.18\Mod\Points
Log:    C:\Program Files\FreeCAD 0.18\Mod\Raytracing
Log:    C:\Program Files\FreeCAD 0.18\Mod\Robot
Log:    C:\Program Files\FreeCAD 0.18\Mod\Ship
Log:    C:\Program Files\FreeCAD 0.18\Mod\Show
Log:    C:\Program Files\FreeCAD 0.18\Mod\Sketcher
Log:    C:\Program Files\FreeCAD 0.18\Mod\Spreadsheet
Log:    C:\Program Files\FreeCAD 0.18\Mod\Start
Log:    C:\Program Files\FreeCAD 0.18\Mod\Surface
Log:    C:\Program Files\FreeCAD 0.18\Mod\TechDraw
Log:    C:\Program Files\FreeCAD 0.18\Mod\Test
Log:    C:\Program Files\FreeCAD 0.18\Mod\Tux
Log:    C:\Program Files\FreeCAD 0.18\Mod\Web
Log:    C:\Program Files\FreeCAD 0.18\bin\Library\bin
Log:    C:\Users\Henry\Anaconda3
Log:    C:\Users\Henry\Anaconda3\Library\mingw-w64\bin
Log:    C:\Users\Henry\Anaconda3\Library\usr\bin
Log:    C:\Users\Henry\Anaconda3\Library\bin
Log:    C:\Users\Henry\Anaconda3\Scripts
Log:    C:\Users\Henry\Anaconda3\bin
Log:    C:\Users\Henry\Anaconda3\condabin
Log:    C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin
Log:    C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp
Log:    C:\WINDOWS\system32
Log:    C:\WINDOWS
Log:    C:\WINDOWS\System32\Wbem
Log:    C:\WINDOWS\System32\WindowsPowerShell\v1.0
Log:    C:\WINDOWS\System32\OpenSSH
Log:    C:\Program Files\MATLAB\R2019a\bin
Log:    C:\Program Files\NVIDIA Corporation\NVIDIA NGX
Log:    C:\Program Files\MATLAB\MATLAB Runtime\v94\runtime\win64
Log:    C:\Program Files (x86)\Wolfram Research\WolframScript
Log:    C:\Program Files (x86)\QuickTime\QTSystem
Log:    C:\Users\Henry\AppData\Local\Microsoft\WindowsApps
Log:    C:\Users\Henry\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64
Log: Init: App::FreeCADInit.py done
Log: Init: Processing command line files
Log: Init:     Processing file: pillar.py
Log: Exiting on purpose
Log: FreeCAD terminating...
Log: Saving system parameter...
Log: Saving system parameter...done
Log: Saving user parameter...
Log: Saving user parameter...done
It's weird because if I run is as a macro from within the FreeCAD GUI it works and creates the .stl cylinder


from Create a simple cylinder using command-line FreeCAD

Inject per-component style tags dynamically with Rollup and scss

I am building a React component library whose source code takes this general structure:

- src
  - common.scss (contains things like re-usable css variables)
  - components
    - button
      - index.js
      - button.scss
    - dialog
      - index.js
      - dialog.scss

My components are responsible for importing their own per-component styles (using scss), so for example, button/index.js has this line:

import "./button.scss";

So far, in my application I have been consuming my library directly from source like this:

// app.js
import "mylib/src/common.scss" // load global styles
import Button from 'mylib/src/components/button/index.js'
import Dialog from 'mylib/src/components/dialog/index.js'

// ...application code...

When my application uses webpack, along with style-loader, the per-component css is appended as style tags in head dynamically when the component is first used. This is a nice performance win since the per-component styling doesn't need to be parsed by the browser until it's actually needed.

Now though, I want to distribute my library using Rollup, so application consumers would do something like this:

import { Button, Dialog } from 'mylib'
import "mylib/common.css" // load global styles

// ...application code...

When I use rollup-plugin-scss it just bundles the per-component styles all together, not dynamically adding them as before.

Is there a technique I can incorporate into my Rollup build so that my per-component styles are dynamically added as style tags in the head tag as they are used?



from Inject per-component style tags dynamically with Rollup and scss

Proper use cases for Android UserManager.isUserAGoat()?

I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method:

public boolean isUserAGoat()

Used to determine whether the user making this call is subject to teleportations.

Returns whether the user making this call is a goat.

How and when should this be used?



from Proper use cases for Android UserManager.isUserAGoat()?

cython setuptools change output filename

I am using cython to cross-compile external python module. I am using python3.6 on the host and python3.5 on the target. Also I am compiling on x86_64 for target aarch64.

My setup.py looks like:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
import builder_config
import os

os.environ["PATH"] = builder_config.PATH
os.environ["CC"] = builder_config.COMPILER
os.environ["LDSHARED"] = builder_config.COMPILER + " -lpython3.5m -shared"
os.environ["CFLAGS"] = builder_config.CFLAGS
os.environ["LDFLAGS"] = builder_config.LDFLAGS
os.environ["ARCH"] = "aarch64"

setup(
    ext_modules = cythonize((Extension("my_ext", ["file1.pyx", "file2.pyx", "file3.pyx", "file4.pyx", "file5.pyx"]))),
)

When I run python3.6 setup.py build_ext -i I get a file named: my_ext.cpython-36m-x86_64-linux-gnu.so

My problem is that on the target the library will not be loaded unless the name is changed to:

my_ext.cpython-35m-aarch64-linux-gnu.so

How can I change the generated filename?



from cython setuptools change output filename

How to configure storybook story for module with RouterLink

Cannot configure story for module where routerLink is used due to error

ERROR NullInjectorError: StaticInjectorError(DynamicModule)[RouterLinkActive -> Router]

To Reproduce Steps to reproduce the behavior: demo-app Run app and you can test that there is no possible solution to add RouterModule to work with story. It cannot be configured with RouterTestingModule, RouterModule, RouterModule.forRoot with iframe.html path. There is always the same error about missing provider.

Expected behavior To run application and story with routerLink

Additional context Latest version of storybook 5.3.3 and angular ~8.2.14 I was working with different configuration 5.2.8 and this issue does not appear.

How to configure this module, is there an issue in storybook?

Storybook issue



from How to configure storybook story for module with RouterLink

In Android Screen Recording - How can I get each frame?

I am using the MediaRecorder and MediaProjection Api for recording the screen in android app. I am not able to get each frame that I can send over a rtmp stream. For publishing over an RTMP stream I am using JAVACV Android library.

For eg - In case of live streaming through camera, we can get each frame in onPreviewFrame() callback. After getting each frame I simply use the FFmpegFrameRecorder of JAVACV library for streaming each frame on to the rtmp url.

How can I achieve the same with screen recording?

Any help would be appreciated here. Thanks in advance!



from In Android Screen Recording - How can I get each frame?

Equivalent for `--find-links` in `setup.py`

What is the equivalent of --find-links / -f flag for pip in setup.py.

I know dependency_links exist, but that requires pointing to a specific file, I want something similar to -f that can point to a list of links from which the package can be selected based on version&os.



from Equivalent for `--find-links` in `setup.py`

Unable to scroll some element into view while using pseudo selector within driver.execute_script()

I've created a script using selenium to grab a text generating dynamically. It is a requirement that I use selenium, so I don't wanna go for xhr in this very case. I'm trying to use pseudo selector in selenium defining explicit wait within it. As selenium doesn't support pseudo selector, as in :contains(), I used javascript command driver.execute_script() to serve the purpose.

Now, the way I tried works inconsistently as the text I wanna grab is not within the viewport. If I scroll a little down manually while the script is running, it works. Xpath is not an option here by the way.

How can I scroll the element into view while using pseudo selector within driver.execute_script()?

I've tried like [works inconsistently]:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

with webdriver.Chrome() as driver:
    wait = WebDriverWait(driver, 10)
    driver.get('https://www.nyse.com/quote/XNYS:AAN')

    item = wait.until(
        lambda driver: driver.execute_script('''return $('span:contains("AARONS")')[0];''')
    )
    print(item.text)

Expected result:

AARONS INC

PS Before marking this post as duplicate, make sure you at least read the title of the question.



from Unable to scroll some element into view while using pseudo selector within driver.execute_script()

Laravel logging.channels.single.path with queue is cached?

Im using Queue::before in AppServiceProvider.php and set logging.channels.single.path value every time when job started:

config(['logging.channels.single.path' => storage_path('logs/accounts/'.$command->acc->login.'.log')]);

When I running 1 job all ok - logs in the right place. When running 2 or more it writing logs to different files - one account can write to another accounts logfile. Why is it happening? It looks like it is caching the config variable.

Queue on horizon redis. One job after done dispatching another same job with the same $acc instance.



from Laravel logging.channels.single.path with queue is cached?

Xamarin Android how to show list if user start typing with @ special character like whatsapp tagging features?

I want to show the user list when the user starts typing with @ special character like tagging features in WhatsApp.

I use a regular expression but it works for only the first word not working for second words, like "Hello @abc and @xyz."

below is my code.

if (searchtext.ToString().Contains("@"))
{
   Regex regex = new Regex("@([a-zA-Z])+");
   MatchCollection matches = regex.Matches(searchtext.ToString());
   if (matches != null && matches.Count != 0)
    {
       string temptext = matches[matches.Count - 1].ToString().Substring(1);
       searchUserList = userList.Where(s=>s.userName.ToLower().StartsWith(temptext.ToString().ToLower())).ToList();

       _usersListAdapter = new TagUsersListAdapter(this.Activity, searchUserList, this);
       _lstViewUsers.SetAdapter(_usersListAdapter);

       _lstViewUsers.Visibility = ViewStates.Visible;
    }
    else
    {
        _lstViewUsers.Visibility = ViewStates.Visible;
    }

}
else
{
   _lstViewUsers.Visibility = ViewStates.Gone;

   _usersListAdapter = new TagUsersListAdapter(this.Activity, userList, this);
   _lstViewUsers.SetAdapter(_usersListAdapter);
}


from Xamarin Android how to show list if user start typing with @ special character like whatsapp tagging features?

Exclude Xcode header search path

I am using Carthage and as part of that have the following structure:

$SRCROOT
  -Code
  -Carthage
    -Build
    -Checkouts

Everything runs fine, but upon a crash, I get errors like these in debug console.

error: /Users/alex/Desktop/x/Carthage/Build/iOS/CocoaLumberjack.framework/Headers/DDAbstractDatabaseLogger.h:30:1: error: duplicate interface definition for class 'DDAbstractDatabaseLogger'
@interface DDAbstractDatabaseLogger : DDAbstractLogger {
^

/Users/alex/Desktop/x/Carthage/Checkouts/FewPods/Pods/CocoaLumberjack/Classes/DDAbstractDatabaseLogger.h:30:12: note: previous definition is here
@interface DDAbstractDatabaseLogger : DDAbstractLogger {

I am able to resolve by moving the Checkouts folder elsewhere, but that makes things somewhat inconvenient.

Any other way I can make Xcode ignore everything under Checkouts?



from Exclude Xcode header search path

How to replace all the columns dynamically in Data Table using Angular2+?

My requirement to replace the all the columns when ever the changes/event is happening outside of the Data Table.

data table is displaying for the first time with selected columns(from event). if i select second one it's not displaying but columns in dtOptions getting changed but it's not displaying. I think clearing the view the problem but i tried using destroy it's not working out for me. some one please help me to achieve this.

HTML Code:

<div id="data-table-grid-slide">
    <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover"></table>
</div>

Angular Code for DataTable:

import {Component, ViewChild, OnInit, Input, AfterViewInit, OnDestroy, Output, EventEmitter} from '@angular/core';
import { DataTableDirective } from 'angular-datatables';
import { Subject } from 'rxjs';
import { ColumnObject } from '../data-tables-net/model/data-tables-model';
import { HttpClient } from '@angular/common/http';
import { DtServiceService} from '../data-tables-net/dt-service.service';
import { WindowRef} from '../services/WindowRef';

declare var $;
@Component({
  selector: 'app-data-tables-net',
  templateUrl: './data-tables-net.component.html',
  styleUrls: ['./data-tables-net.component.css']
})
export class DataTablesNetComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('dataTable', {static: true}) table;
  @ViewChild(DataTableDirective, {static: false}) dtElement: DataTableDirective;

  dataTableColumn: Array<any> = [];
  dtOptions: DataTables.Settings = {};
  @Input() dataTableGrid: boolean;
  @Input() tableShow: boolean;
  @Output() tableShowChange = new EventEmitter<boolean>();
  @Output() dataTableGridChange = new EventEmitter<boolean>();

  dtTrigger: Subject<any> = new Subject();

 // editor: any;
  columnObject: ColumnObject = {
      title: '',
      data: ''
  };
  constructor(private http: HttpClient, private dtServiceService: DtServiceService, private winRef: WindowRef) { }

  ngOnInit() {
    this.dataTableGrid = true;
    this.initDt();
  }
  ngAfterViewInit(): void {
    // This method get called on pencil click of model in Data Model Visuvalizer
    this.winRef.modelClick$.subscribe((modelObjAttributes) => {
      this.dataTableGrid = true;
      this.tableShow = false;
      this.tableShowChange.emit(this.tableShow);
      this.dataTableGridChange.emit(this.dataTableGrid);
      console.log('modelObjAttributes', modelObjAttributes);
      // tslint:disable-next-line: max-line-length
     // this.dtOptions.columns =  [{title: 'id', data: 'id'}, {title: 'name', data: 'name'}, {title: 'item code', data: 'item code'}, {title: 'addr', data: 'addr'}];
      if (this.dtOptions.columns) {
        // this.dtOptions.destroy = true;
       //  delete this.dtOptions.columns;




this.reRenderDataTable();
       //  console.log('columns', this.dtOptions.columns);
         this.initDt();
         this.dtOptions.columns =   this.getModelDetails(modelObjAttributes);
       //  console.log(this.dtOptions.columns);
         this.dtTrigger.next();
      } else {
        this.dtOptions.columns =   this.getModelDetails(modelObjAttributes);
        console.log(this.dtOptions.columns);
        this.dtTrigger.next();
        // this.dtOptions.destroy = true;
      }
    //  delete this.dtOptions.columns;


    });
  }
  initDt() {
    this.dtOptions = {
      // ajax: 'data/data.json',
      // columns: [{title: 'Column1', data: 'column1'}],
      paging: true,
      searching: true,
      ordering: true,
      info:     false,
      responsive: true,
      destroy: true
    };
    }

  ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();
  }

  // This method used to get the details of model on clicking of pencil icon
  getModelDetails(modelDetailsObj) {
    return this.convertModelAttributesToDataTable(modelDetailsObj.options);
    // this.getModelDetailsFromService(modelDetailsObj.id);
  }

// This method is used to  call the service to get the selected Models / Schema details from Database
 getModelDetailsFromService(schemaId): void {
  this.dtServiceService.getSelectedSchema(schemaId).subscribe(data => {
    console.log(data);
  },
  error => {
    console.log('Data is not getting');
  });
}

  // This method used to form the schema data for Data Table
  convertModelAttributesToDataTable(attributesObject) {
    this.dataTableColumn = [];
    // delete this.dtOptions.columns;

    for (const [index, obj] of attributesObject.entries()) {
      if (obj) {
          this.columnObject = { title: obj.text, data: obj.text};
          console.log('columnObject', this.columnObject);
          this.dataTableColumn.push(this.columnObject);
        //  console.log(this.dtOptions);
      }
    }
   // this.dtTrigger.next();
    return this.dataTableColumn;
  }
  // This method used re-render the data table with updated data's
  reRenderDataTable(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
      // Destroy the table first
      // dtInstance.destroy();
      // Call the dtTrigger to rerender again
      this.dtTrigger.next();
    });
  }

}


from How to replace all the columns dynamically in Data Table using Angular2+?

Matter.Js scaling a sprite (related to other variables)

I'm using Matter.Js for an interactive animation. One feature I'm working on is to scale some of my bodies relative to their distance to the cursor. My issue is that I cannot seem to scale the sprite which covers these bodies. I tried scaling the bodies themselves but the sprite size did not actually change. So I figured I just needed to scale the sprite size. However I can't seem to get any configuration of Matter.Body.set() to make this change. Reading the source I'm not sure it is possible.

The documentation says: "Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. Prefer to use the actual setter functions in performance critical situations."

I've tried:

Body.set(body, {
  render: {
    sprite: {
      texture: // url to sprite reset here incase of overwrite,
      xScale: scaleFactor,
      yScale: scaleFactor
    }
  }
});

This just seems to remove the sprite and any other render settings so I see nothing.

I've tried:

Body.set(body, 'render.sprite.xScale', scaleFactor);

This seems to do nothing at all and doesn't change the rendering.

Is it not possible to set the values of the sprite object at any moment other than the creation of the body? Or am I just targeting those values wrong in my function calls?



from Matter.Js scaling a sprite (related to other variables)

Why firestore document is not creating nor updating data?

Problem

Firestore document is not creating nor updating data

let user = db.collection('users').doc(userId);
let data = {
    timestamp: FieldValue.serverTimestamp(),
        bounties : {
            [impressionId] : {
                timestamp: timestamp,
                amount: amount,
                currency: currency
        }
    }
};

user.set(data, {merge: true});

Expectation

The below example data should be use to create or update cloud firestore document

{
   "example-user-1": {
        "bounties": {
               "example-impression-1": {
                    "timestamp": "12315443",
                    "amount": 0.0,
                    "currency": "null"
               }
         }
   }
}

Results

The document is not created

{"domain":{"domain":null,"_events":{},"_eventsCount":1,"members":[]}}


from Why firestore document is not creating nor updating data?

Thursday 23 January 2020

How can I use nginx with adonis?

I'm try to make a deploy of one api adonis and I'm trying to use nginx to enable external access to my http requests.

I install nginx and go in ssh I go to:

cd /etc/nginx
vi nginx.conf

So, I put this code:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    server {
        listen 80;

        server_name knowhowexpressapp.com ;

        location / {
            proxy_pass http://localhost:3333;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_cache_bypass $http_upgrade;
        }
    }


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

In server name I put the domain; In port I put 3333 because is the port that I put in .env;

I start nginx:

cd /usr/bin/etc/nginx
nginx

Check if nginx is running:

[root@knowhowexpressapp etc]# ps aux | grep nginx
root      14143  0.0  0.0  55320  1028 ?        Ss   11:41   0:00 nginx: master process nginx
nginx     14144  0.0  0.0  55708  1936 ?        S    11:41   0:00 nginx: worker process
root      14188  0.0  0.0 112712   964 pts/2    S+   11:42   0:00 grep --color=auto nginx

My .env archive:

HOST=ip from my server
PORT=3333
NODE_ENV=production
APP_NAME=AdonisJs
APP_URL=http://${HOST}:${PORT}
CACHE_VIEWS=false
APP_KEY=GPhustNKtbIlrxawTZa6xQTIkHcjBXFr
DB_CONNECTION=pg
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=xxxx
DB_DATABASE=xxx
HASH_DRIVER=bcrypt

So, i check pm2 and my server is running:

⇆ PM2+ activated 
┌─────┬───────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id  │ name      │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├─────┼───────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0   │ server    │ default     │ 4.1.0   │ fork    │ 12586    │ 16m    │ 34   │ online    │ 0%       │ 41.0mb   │ root     │ disabled │

But when i try to access my api i'm getting:

Could not get any response There was an error connecting to https://knowhowexpressapp.com/login.

My server is centos 7

My api is only running if i put the http://ipfrommyserver but when i try to access the domain i receive error.



from How can I use nginx with adonis?

Deep clone class instance JavaScript

I'm trying to figure out a way to deep clone a JS class instance while preserving all the prototypes down the chain.

I've seen how to deep clone and object:

JSON.parse(JSON.stringify(instance))

And I have seen how to make a shallow copy of a class instance:

Object.assign( Object.create( Object.getPrototypeOf(instance) ), instance)

But my question is, is there a way to deep clone an instance of a class?



from Deep clone class instance JavaScript

Creating scheduled jobs in a Multi-Tenant application

I am building a Multi-Tenant web application using Laravel/PHP that will be hosted on AWS as SaaS at the end. I have around 15-20 different background jobs that need scheduling for each tenant. The jobs need to be fired every 5 minutes as well. Thus the number of jobs which need to be fired for 100 tenants would be around 2000. I am left with 2 challenges in achieving this

  1. Is there a cloud solution that distributes and manages the load of the scheduled jobs automatically?
  2. If one is out there, how can we create those 15+ scheduled jobs on the fly? Is there an API available?

Looking for your assistance



from Creating scheduled jobs in a Multi-Tenant application

AIOHTTP - Application.make_handler(...) is deprecated - Adding Multiprocessing

I went down a journey of "How much performance can I squeeze out of a Python web-server?" This lead me to AIOHTTP and uvloop. Still, I could see that AIOHTTP wasn't using my CPU to its full potential. I set out to use multiprocessing with AIOHTTP. I learned that there's a Linux kernel feature that allows multiple processes to share the same TCP port. This lead me to develop the following code (Which works wonderfully):

import asyncio
import os
import socket
import time
from aiohttp import web
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count

CPU_COUNT = cpu_count()
print("CPU Count:", CPU_COUNT)


def mk_socket(host="127.0.0.1", port=8000, reuseport=False):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if reuseport:
        SO_REUSEPORT = 15
        sock.setsockopt(socket.SOL_SOCKET, SO_REUSEPORT, 1)
    sock.bind((host, port))
    return sock


async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    pid = os.getpid()
    text = "{:.2f}: Hello {}! Process {} is treating you\n".format(
        time.time(), name, pid)
    #time.sleep(5)  # intentionally blocking sleep to simulate CPU load
    return web.Response(text=text)


def start_server():
    host = "127.0.0.1"
    port=8000
    reuseport = True
    app = web.Application()
    sock = mk_socket(host, port, reuseport=reuseport)
    app.add_routes([web.get('/', handle),
                    web.get('/{name}', handle)])
    loop = asyncio.get_event_loop()
    coro = loop.create_server(
            protocol_factory=app.make_handler(),
            sock=sock,
        )
    srv = loop.run_until_complete(coro)
    loop.run_forever()


if __name__ == '__main__':
    with ProcessPoolExecutor() as executor:
        for i in range(0, CPU_COUNT):
            executor.submit(start_server)

wrk benchmark of my site before applying this code:

Running 30s test @ http://127.0.0.1:8000/
  12 threads and 400 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    54.33ms    6.54ms 273.24ms   89.95%
    Req/Sec   608.68    115.97     2.27k    83.63%
  218325 requests in 30.10s, 41.23MB read
  Non-2xx or 3xx responses: 218325
Requests/sec:   7254.17
Transfer/sec:      1.37MB

wrk benchmark after:

Running 30s test @ http://127.0.0.1:8000/
  12 threads and 400 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    15.96ms    7.27ms  97.29ms   84.78%
    Req/Sec     2.11k   208.30     4.45k    75.50%
  759290 requests in 30.08s, 153.51MB read
Requests/sec:  25242.39
Transfer/sec:      5.10MB

WoW! But there's a problem:

DeprecationWarning: Application.make_handler(...) is deprecated, use AppRunner API instead
  protocol_factory=app.make_handler()

So I tried this:

import asyncio
import os
import socket
import time
from aiohttp import web
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count

CPU_COUNT = cpu_count()
print("CPU Count:", CPU_COUNT)

def mk_socket(host="127.0.0.1", port=8000, reuseport=False):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if reuseport:
        SO_REUSEPORT = 15
        sock.setsockopt(socket.SOL_SOCKET, SO_REUSEPORT, 1)
    sock.bind((host, port))
    return sock

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    pid = os.getpid()
    text = "{:.2f}: Hello {}! Process {} is treating you\n".format(
        time.time(), name, pid)
    #time.sleep(5)  # intentionally blocking sleep to simulate CPU load
    return web.Response(text=text)

async def start_server():
    host = "127.0.0.1"
    port=8000
    reuseport = True
    app = web.Application()
    sock = mk_socket(host, port, reuseport=reuseport)
    app.add_routes([web.get('/', handle),
                    web.get('/{name}', handle)])

    coro = loop.create_server(
            protocol_factory=app.make_handler(),
            sock=sock,
        )
    runner = web.AppRunner(app)
    await runner.setup()
    srv = web.TCPSite(runner, 'localhost', 8000)
    await srv.start()
    print('Server started at http://127.0.0.1:8000')
    return coro, app, runner

async def finalize(srv, app, runner):
    sock = srv.sockets[0]
    app.loop.remove_reader(sock.fileno())
    sock.close()

    #await handler.finish_connections(1.0)
    await runner.cleanup()
    srv.close()
    await srv.wait_closed()
    await app.finish()

def init():
    loop = asyncio.get_event_loop()
    srv, app, runner = loop.run_until_complete(init)
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete((finalize(srv, app, runner)))


if __name__ == '__main__':
    with ProcessPoolExecutor() as executor:
        for i in range(0, CPU_COUNT):
            executor.submit(init)

which is obviously incomplete becuase coro isn't being used. I'm not sure where to integrate the socket with AppRunner. Answer should show original example modified to use App Runner.



from AIOHTTP - Application.make_handler(...) is deprecated - Adding Multiprocessing

How to use ng-template inside innerHTML in Angular

Can someone help me, how to use ng-template inside innerHTML tag,

Stackblitz Demo: https://stackblitz.com/edit/angular-xgnnj4

What I wanted to do is,

In the Component HTML

<div [innerHTML]="htmlString"><div>

In the Component TS

@ViewChild('dynamicComponent', { static: false, read: ViewContainerRef }) myRef: ViewContainerRef;

htmlString = `<ng-template #dynamicComponent></ng-template>`;

  ngAfterViewInit(): void {
    const factory = this.componentFactoryResolver.resolveComponentFactory(CommentComponent);
    const ref = this.myRef.createComponent(factory);
    ref.changeDetectorRef.detectChanges();
  }

I really need to achieve this way because I wanted to get the HTML content from an API and use that value to display the HTML content dynamically

As I am getting the error as Cannot read property 'createComponent' of undefined but if I put outside the innerHTML it works perfectly

I have gone through https://angular.io/guide/dynamic-component-loader but it's not helping my scneario



from How to use ng-template inside innerHTML in Angular

Creating a 2D Gaussian random field from a given 2D variance

I've been trying to create a 2D map of blobs of matter (Gaussian random field) using a variance I have calculated. This variance is a 2D array. I have tried using numpy.random.normal since it allows for a 2D input of the variance, but it doesn't really create a map with the trend I expect from the input parameters. One of the important input constants lambda_c should manifest itself as the physical size (diameter) of the blobs. However, when I change my lambda_c, the size of the blobs does not change if at all. For example, if I set lambda_c = 40 parsecs, the map needs blobs that are 40 parsecs in diameter. A MWE to produce the map using my variance:

import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.pyplot import show, plot
import scipy.integrate as integrate
from scipy.interpolate import RectBivariateSpline



n = 300
c = 3e8
G = 6.67e-11
M_sun = 1.989e30
pc = 3.086e16  # parsec
Dds = 1097.07889283e6*pc 
Ds = 1726.62069147e6*pc
Dd = 1259e6*pc

FOV_arcsec_original = 5.
FOV_arcmin = FOV_arcsec_original/60.   


pix2rad = ((FOV_arcmin/60.)/float(n))*np.pi/180.
rad2pix = 1./pix2rad

x_pix = np.linspace(-FOV_arcsec_original/2/pix2rad/180.*np.pi/3600.,FOV_arcsec_original/2/pix2rad/180.*np.pi/3600.,n)
y_pix = np.linspace(-FOV_arcsec_original/2/pix2rad/180.*np.pi/3600.,FOV_arcsec_original/2/pix2rad/180.*np.pi/3600.,n)
X_pix,Y_pix = np.meshgrid(x_pix,y_pix)

conc = 10.
M = 1e13*M_sun
r_s = 18*1e3*pc

lambda_c = 40*pc  ### The important parameter that doesn't seem to manifest itself in the map when changed

rho_s = M/((4*np.pi*r_s**3)*(np.log(1+conc) - (conc/(1+conc)))) 
sigma_crit = (c**2*Ds)/(4*np.pi*G*Dd*Dds)
k_s = rho_s*r_s/sigma_crit
theta_s = r_s/Dd
Renorm = (4*G/c**2)*(Dds/(Dd*Ds))
#### Here I just interpolate and zoom into my field of view to get better resolutions
A = np.sqrt(X_pix**2 + Y_pix**2)*pix2rad/theta_s



A_1 = A[100:200,0:100]

n_x = n_y = 100

FOV_arcsec_x = FOV_arcsec_original*(100./300)
FOV_arcmin_x = FOV_arcsec_x/60.   
pix2rad_x = ((FOV_arcmin_x/60.)/float(n_x))*np.pi/180.
rad2pix_x = 1./pix2rad_x

FOV_arcsec_y = FOV_arcsec_original*(100./300)
FOV_arcmin_y = FOV_arcsec_y/60.   
pix2rad_y = ((FOV_arcmin_y/60.)/float(n_y))*np.pi/180.
rad2pix_y = 1./pix2rad_y

x1 = np.linspace(-FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,n_x)
y1 = np.linspace(-FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,n_y)
X1,Y1 = np.meshgrid(x1,y1)



n_x_2 = 500
n_y_2 = 500


x2 = np.linspace(-FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,n_x_2)
y2 = np.linspace(-FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,n_y_2)
X2,Y2 = np.meshgrid(x2,y2)

interp_spline = RectBivariateSpline(y1,x1,A_1)

A_2 = interp_spline(y2,x2)



A_3 = A_2[50:450,0:400]

n_x_3 = n_y_3 = 400

FOV_arcsec_x = FOV_arcsec_original*(100./300)*400./500.
FOV_arcmin_x = FOV_arcsec_x/60.   
pix2rad_x = ((FOV_arcmin_x/60.)/float(n_x_3))*np.pi/180.
rad2pix_x = 1./pix2rad_x

FOV_arcsec_y = FOV_arcsec_original*(100./300)*400./500.
FOV_arcmin_y = FOV_arcsec_y/60.   
pix2rad_y = ((FOV_arcmin_y/60.)/float(n_y_3))*np.pi/180.
rad2pix_y = 1./pix2rad_y

x3 = np.linspace(-FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,n_x_3)
y3 = np.linspace(-FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,n_y_3)
X3,Y3 = np.meshgrid(x3,y3)

n_x_4 = 1000
n_y_4 = 1000


x4 = np.linspace(-FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,FOV_arcsec_x/2/pix2rad_x/180.*np.pi/3600.,n_x_4)
y4 = np.linspace(-FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,FOV_arcsec_y/2/pix2rad_y/180.*np.pi/3600.,n_y_4)
X4,Y4 = np.meshgrid(x4,y4)

interp_spline = RectBivariateSpline(y3,x3,A_3)

A_4 = interp_spline(y4,x4)

############### Function to calculate variance

variance = np.zeros((len(A_4),len(A_4)))



def variance_fluctuations(x):
    for i in xrange(len(x)):
        for j in xrange(len(x)):
            if x[j][i] < 1.:
                variance[j][i] = (k_s**2)*(lambda_c/r_s)*((np.pi/x[j][i]) - (1./(x[j][i]**2 -1)**3.)*(((6.*x[j][i]**4. - 17.*x[j][i]**2. + 26)/3.)+ (((2.*x[j][i]**6. - 7.*x[j][i]**4. + 8.*x[j][i]**2. - 8)*np.arccosh(1./x[j][i]))/(np.sqrt(1-x[j][i]**2.)))))
            elif x[j][i] > 1.:
                variance[j][i] = (k_s**2)*(lambda_c/r_s)*((np.pi/x[j][i]) - (1./(x[j][i]**2 -1)**3.)*(((6.*x[j][i]**4. - 17.*x[j][i]**2. + 26)/3.)+ (((2.*x[j][i]**6. - 7.*x[j][i]**4. + 8.*x[j][i]**2. - 8)*np.arccos(1./x[j][i]))/(np.sqrt(x[j][i]**2.-1)))))



variance_fluctuations(A_4)

#### Creating the map 

mean = 0

delta_kappa = np.random.normal(0,variance,A_4.shape)  

xfinal = np.linspace(-FOV_arcsec_x*np.pi/180./3600.*Dd/pc/2,FOV_arcsec_x*np.pi/180./3600.*Dd/pc/2,1000)
yfinal = np.linspace(-FOV_arcsec_x*np.pi/180./3600.*Dd/pc/2,FOV_arcsec_x*np.pi/180./3600.*Dd/pc/2,1000)

Xfinal, Yfinal = np.meshgrid(xfinal,yfinal)
plt.contourf(Xfinal,Yfinal,delta_kappa,100)
plt.show()

1

The map looks like this, with the density of blobs increasing towards the right. However, the size of the blobs don't change and the map looks virtually the same whether I use lambda_c = 40*pc or lambda_c = 400*pc.

I'm wondering if the np.random.normal function isn't really doing what I expect it to do? I feel like the pixel scale of the map and the way samples are drawn make no link to the size of the blobs. Maybe there is a better way to create the map using the variance, would appreciate any insight.

I expect the map to look something like this , the blob sizes change based on the input parameters for my variance :



from Creating a 2D Gaussian random field from a given 2D variance

How to Display No Data for Export Alert when there is no data found Angular 6 kendo-excelexport Component

Below is the code :i used angular 6 kendo-excelexport ^4.5.0 version component.

<kendo-excelexport [data]="excelDataToExport" [collapsible]="true" fileName="Sample.xlsx" #excelexport>
                <kendo-excelexport-column field="taxMonth" title="Month" [width]="200">
                </kendo-excelexport-column>
                <kendo-excelexport-column field="clientName" title="Client Name" [width]="200">
                </kendo-excelexport-column>
                <kendo-excelexport-column field="alertType" title="Alert Type" [width]="200">

                <kendo-excelexport-column field="Description" title="Description" [width]="200">
                </kendo-excelexport-column>

</kendo-excelexport>


from How to Display No Data for Export Alert when there is no data found Angular 6 kendo-excelexport Component

Webpack Config to build sdk for both Node and Browser

Can someone help me in figuring out what should be the webpack sdk config to build sdk for both web and browser?

My current config looks like this

const path = require('path');

let baseConfig = {
  mode: 'production',
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'sdk/js-sdk.js',
    libraryTarget: 'umd',
    library: 'jsSdk',
    globalObject: 'this'
  },
  resolve: {
    extensions: [ ".ts", ".js"]
  },
  externals: {
    "request-promise-native": "request-promise-native",
    "request": "request"
  },
  module: {
    rules: [
    { test: /\.ts$/, use: 'ts-loader' }
    ]
  }
}

module.exports = baseConfig

Which I am building using following command

  "pn-dev-build": "rm -rf dist && npm version patch && webpack --mode=development && npm publish --registry http://localhost:4873",

And then if I install it in my vue-nuxt project it gives following error

  • fs in ./node_modules/request/lib/har.js friendly-errors 09:06:34
  • net in ./node_modules/forever-agent/index.js, ./node_modules/tough-cookie/lib/cookie.js and 1 other
    friendly-errors 09:06:34
  • tls in ./node_modules/forever-agent/index.js, ./node_modules/tunnel-agent/index.js

Can someone help me in solving the above error?



from Webpack Config to build sdk for both Node and Browser

Why is Multi-agent Deep Deterministic Policy Gradient (MADDPG) running slowly and taking only 22% from the GPU?

I tried to run the Distributed Multi-Agent Cooperation Algorithm based on MADDPG with prioritized batch data code with increasing the number of agents to be 12 agents but it takes a lot of times to train 3500 episodes. I have tried different setting and I'm using:

Cuda 10.1

gpu

   # MADDPG 
    gpu_options = tf.GPUOptions(allow_growth=True,per_process_gpu_memory_fraction=0.7)

    # config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)
    with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=True)) as sess:

and the GPU takes only 22% but the CPU takes 100%

enter image description here

I'm working on :

Operating System: Windows 10 Pro 64-bit (10.0, Build 18363) (18362.19h1_release.190318-1202) Processor: Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz (8 CPUs), ~3.0GHz Memory: 32768MB RAM

The parameters of the MADDPG:

        parser = argparse.ArgumentParser(description='provide arguments for DDPG agent')

        # agent parameters
        parser.add_argument('--actor-lr', help='actor network learning rate', default=0.001)
        parser.add_argument('--critic-lr', help='critic network learning rate', default=0.001)
        parser.add_argument('--gamma', help='discount factor for critic updates', default=0.99)
        parser.add_argument('--tau', help='soft target update parameter', default=0.01)
        parser.add_argument('--buffer-size', help='max size of the replay buffer', default=1000000)
        parser.add_argument('--minibatch-size', help='size of minibatch for minibatch-SGD', default=128)

        # run parameters
        #parser.add_argument('--env', help='choose the gym env- tested on {Pendulum-v0}', default='MountainCarContinuous-v0')
        parser.add_argument('--random-seed', help='random seed for repeatability', default=1234)
        parser.add_argument('--max-episodes', help='max num of episodes to do while training', default=3500)
        parser.add_argument('--max-episode-len', help='max length of 1 episode', default=100)
        parser.add_argument('--render-env', help='render the gym env', action='store_true')
        parser.add_argument('--use-gym-monitor', help='record gym results', action='store_true')
        parser.add_argument('--monitor-dir', help='directory for storing gym results', default='./results/videos/video1')
        parser.add_argument('--summary-dir', help='directory for storing tensorboard info', default='./results/4vs2/tfdata_maddpg/')
        parser.add_argument('--modelFolder', help='the folder which saved model data', default="./results/4vs2/weights_proposed/")
        parser.add_argument('--runTest', help='use saved model to run', default=False)
        parser.add_argument('--m-size', help='M size', default=128)
        parser.add_argument('--n-size', help='N size', default=64)

        parser.set_defaults(render_env=False)
        parser.set_defaults(use_gym_monitor=True)

        args = vars(parser.parse_args())

I also tried ubuntu 18.14 and when I run to check the GPU

 from __future__ import absolute_import, division, print_function, unicode_literals

    import tensorflow as tf
    print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
    tf.debugging.set_log_device_placement(True)

    # Create some tensors
    a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
    b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
    c = tf.matmul(a, b)

    print(c)



    from tensorflow.python.client import device_lib

    print("g",device_lib.list_local_devices())

I got

Num GPUs Available:  0
2020-01-21 12:22:14.368278: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
Tensor("MatMul:0", shape=(2, 2), dtype=float32)
2020-01-21 12:22:14.481498: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1005] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-01-21 12:22:14.481901: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x44a1750 executing computations on platform CUDA. Devices:
2020-01-21 12:22:14.481917: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): GeForce RTX 2080 Ti, Compute Capability 7.5
g [name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 16981832204773765455
, name: "/device:XLA_GPU:0"
device_type: "XLA_GPU"
memory_limit: 17179869184
locality {
}
incarnation: 10632369433792260465
physical_device_desc: "device: XLA_GPU device"
, name: "/device:XLA_CPU:0"
device_type: "XLA_CPU"
memory_limit: 17179869184
locality {
}
incarnation: 11745586653788522436
physical_device_desc: "device: XLA_CPU device"
]


from Why is Multi-agent Deep Deterministic Policy Gradient (MADDPG) running slowly and taking only 22% from the GPU?

Android: how to dismiss a DatePicker DialogFragment when touching outside?

I have a working DatePickerFragment that extends DialogFragment. I set up a DatePickerDialog in onCreateDialog() and then tried to add:

"picker.setCanceledOnTouchOutside(true);"

I am testing on a device with Android 8.0 Oreo and nothing happens when touching outside the DatePicker dialog. I am using androidx.appcompat.app.AppCompatActivity as my BaseActivity and androidx.fragment.app.DialogFragment for the DialogFragment;

Code:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);

    DatePickerDialog picker = new DatePickerDialog(getActivity(),this,year,month,day);
    **picker.setCanceledOnTouchOutside(true);**
    return picker;

This is the Activity code that creates the Fragment:

DatePickerFragment newFragment = new DatePickerFragment();
// tried the below also, with no luck
**newFragment.setCancelable(true);**
newFragment.show(getSupportFragmentManager(), "datePicker");

I also tried the below in the DialogFragment, also with no luck:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   ...
   getDialog().setCanceledOnTouchOutside(true);
   ... 
   }

and:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getDialog() != null) {
        getDialog().setCanceledOnTouchOutside(true);
    }
    return super.onCreateView(inflater, container, savedInstanceState);
}    

I referenced this post for possible answers: How to dismiss a DialogFragment when pressing outside the dialog?. What am I missing here?



from Android: how to dismiss a DatePicker DialogFragment when touching outside?

Chrome Extension and gmail.js blocking access to google api

I'm just playing around with a chrome extension based on this tutorial https://cloud.google.com/blog/products/gcp/deepbreath-preventing-angry-emails-with-machine-learning .

When i use the extension for some reason the application does not work. It appears the API from google is blocked?

This is my manifest for those interested,

{
  "name": "Rhea",
  "version": "0.1",
  "description": "Rhea ADHD Extension",
  "content_scripts": [
    {
      "matches": [
      "https://mail.google.com/*"],
      "js": ["content.js"]
    }
  ],
  "permissions": [
  "<all_urls>",
  "history", 
    "https://language.googleapis.com/*"
  ],
  "web_accessible_resources": [
    "third_party/jquery-1.10.2.min.js",
    "third_party/gmail.js",
    "main.js"
  ],
  "manifest_version": 2
}

and content.js

// this is getting the scripts to be able to read the data.

// This gets the extension of Jquery
var j = document.createElement('script');
// creates element in html Script https://www.w3schools.com/jsref/dom_obj_script.asp

j.src = chrome.extension.getURL('third_party/jquery-1.10.2.min.js');

//script element is used to call jquery and could be used to call a javascript scraping library

//this is appending the script into the documents head
(document.head || document.documentElement).appendChild(j);
// This creates another script
var g = document.createElement('script');
//the new script uses the gmail library to parse gmail informaiton.
g.src = chrome.extension.getURL('third_party/gmail.js');

//this is appending the script into the documents head
(document.head || document.documentElement).appendChild(g);

var s = document.createElement('script');
s.src = chrome.extension.getURL('main.js');
//this is appending the script into the documents head
(document.head || document.documentElement).appendChild(s);

Here is the error code

Refused to load the script 'https://apis.google.com/js/rpc:shindig_random.js?onload=init' because it violates the following Content Security Policy directive: "script-src 'report-sample' 'nonce-pdiEXaPpq1kdYvcP3O8iAQ' 'unsafe-inline' 'strict-dynamic' https: http: 'unsafe-eval'". 'strict-dynamic' is present, so host-based whitelisting is disabled. Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Thanks in advance :)



from Chrome Extension and gmail.js blocking access to google api