问:
Unsupported operation: _Namespace ERROR while using rootbundle.loadString()
I am trying to use mapsforge plugin to use my own compiled map. I am not an experienced flutter developer and don't know so much about loading assets therefore can't figure out what the problem is.

File structure;

pubspec.yaml;

```<code>flutter:

  uses-material-design: true

  assets:
    - assets/login/
    - assets/maps/render_themes/
    - assets/maps/icons
</code>```

Code;

```<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mapsforge_flutter/core.dart';
import 'package:mapsforge_flutter/maps.dart';

class MapShow extends StatefulWidget {
  @override
  _MapShowState createState() => _MapShowState();
}

class _MapShowState extends State<MapShow> {
  late MapFile mapFile;
  late SymbolCache symbolCache;
  GraphicFactory graphicFactory = const FlutterGraphicFactory();
  DisplayModel displayModel = DisplayModel();
  late RenderThemeBuilder renderThemeBuilder;
  late String content;
  late RenderTheme renderTheme;
  late MapDataStoreRenderer jobRenderer;
  late MapModel mapModel;
  late ViewModel viewModel;

  void assignSymbolCache() async {}

  @override
  void initState() {
    super.initState();

    rootBundle
        .loadString("assets/maps/render_themes/defaultrender.xml")
        .then((String s) {
      content = s;
    });

    MapFile.from("assets/maps/akuzem.map", null, null).then((MapFile mf) {
      mapFile = mf;
    });
    symbolCache = FileSymbolCache(rootBundle);

    renderThemeBuilder =
        RenderThemeBuilder(graphicFactory, symbolCache, displayModel);

    renderThemeBuilder.parseXml(content);

    renderTheme = renderThemeBuilder.build();

    jobRenderer =
        MapDataStoreRenderer(mapFile, renderTheme, graphicFactory, true);
    mapModel = MapModel(
      displayModel: displayModel,
      renderer: jobRenderer,
    );

    viewModel = ViewModel(displayModel: displayModel);
  }

  @override
  Widget build(BuildContext context) {
    setState(() {});

    return FlutterMapView(
        mapModel: mapModel,
        viewModel: viewModel,
        graphicFactory: graphicFactory);
  }
}

</code>```

Also i saw WidgetsFlutterBinding.ensureInitialized(); in an answer and added my void main() but didnt solved.

Error Showing;

Error in debug console;

```<code>Restarted application in 161ms.
Error: Unsupported operation: _Namespace
    at Object.throw_ [as throw] (http://localhost:60585/dart_sdk.js:5067:11)
    at Function.get _namespacePointer [as _namespacePointer] (http://localhost:60585/dart_sdk.js:56707:17)
    at Function._namespacePointer (http://localhost:60585/dart_sdk.js:54523:28)
    at Function._dispatchWithNamespace (http://localhost:60585/dart_sdk.js:54526:31)
    at io._File.new.exists (http://localhost:60585/dart_sdk.js:54530:23)
at readbufferfile.ReadbufferFile.new._openRaf (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:82:30)
    at _openRaf.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at readbufferfile.ReadbufferFile.new.[_openRaf] (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:77:20)
at readbufferfile.ReadbufferFile.new.length (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:93:29)
    at length.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at readbufferfile.ReadbufferFile.new.length (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:91:20)
at mapfile.MapFile.__._init (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15605:75)
    at _init.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at mapfile.MapFile.__.[_init] (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15602:20)
at from (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15586:34)
    at from.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at Function.from (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15584:20)
at map_show._MapShowState.new.initState (http://localhost:60585/packages/mapping_tool/pages/map/map_show.dart.lib.js:166:23)
</code>```

答:
in your initState method, you used then, It breaks your order of code.

Try this code :

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mapsforge_flutter/core.dart';
import 'package:mapsforge_flutter/maps.dart';

class MapShow extends StatefulWidget {
  @override
  _MapShowState createState() => _MapShowState();
}

class _MapShowState extends State<MapShow> {
  late MapFile mapFile;
  late SymbolCache symbolCache;
  GraphicFactory graphicFactory = const FlutterGraphicFactory();
  DisplayModel displayModel = DisplayModel();
  late RenderThemeBuilder renderThemeBuilder;
  late String content;
  late RenderTheme renderTheme;
  late MapDataStoreRenderer jobRenderer;
  late MapModel mapModel;
  late ViewModel viewModel;

  void assignSymbolCache() async {}

  @override
  void initState() {
    super.initState();
    start();

  }

  start()async{

       ///use await let u place fields in right order
      content = await rootBundle
        .loadString("assets/maps/render_themes/defaultrender.xml");

      mapFile = await MapFile.from("assets/maps/akuzem.map", null, null);

    symbolCache = FileSymbolCache(rootBundle);

    renderThemeBuilder =
        RenderThemeBuilder(graphicFactory, symbolCache, displayModel);

    renderThemeBuilder.parseXml(content);

    renderTheme = renderThemeBuilder.build();

    jobRenderer =
        MapDataStoreRenderer(mapFile, renderTheme, graphicFactory, true);
    mapModel = MapModel(
      displayModel: displayModel,
      renderer: jobRenderer,
    );

    viewModel = ViewModel(displayModel: displayModel);

    ///never use set state before widget return, Do it in when your view is ready to load
    setState(() {});

   }

  @override
  Widget build(BuildContext context) {

    return FlutterMapView(
        mapModel: mapModel,
        viewModel: viewModel,
        graphicFactory: graphicFactory);
  }
}

```

Body:
I am trying to use mapsforge plugin to use my own compiled map. I am not an experienced flutter developer and don't know so much about loading assets therefore can't figure out what the problem is.

File structure;

pubspec.yaml;

flutter:

  uses-material-design: true

  assets:
    - assets/login/
    - assets/maps/render_themes/
    - assets/maps/icons

Code;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mapsforge_flutter/core.dart';
import 'package:mapsforge_flutter/maps.dart';

class MapShow extends StatefulWidget {
  @override
  _MapShowState createState() => _MapShowState();
}

class _MapShowState extends State<MapShow> {
  late MapFile mapFile;
  late SymbolCache symbolCache;
  GraphicFactory graphicFactory = const FlutterGraphicFactory();
  DisplayModel displayModel = DisplayModel();
  late RenderThemeBuilder renderThemeBuilder;
  late String content;
  late RenderTheme renderTheme;
  late MapDataStoreRenderer jobRenderer;
  late MapModel mapModel;
  late ViewModel viewModel;

  void assignSymbolCache() async {}

  @override
  void initState() {
    super.initState();

    rootBundle
        .loadString("assets/maps/render_themes/defaultrender.xml")
        .then((String s) {
      content = s;
    });

    MapFile.from("assets/maps/akuzem.map", null, null).then((MapFile mf) {
      mapFile = mf;
    });
    symbolCache = FileSymbolCache(rootBundle);

    renderThemeBuilder =
        RenderThemeBuilder(graphicFactory, symbolCache, displayModel);

    renderThemeBuilder.parseXml(content);

    renderTheme = renderThemeBuilder.build();

    jobRenderer =
        MapDataStoreRenderer(mapFile, renderTheme, graphicFactory, true);
    mapModel = MapModel(
      displayModel: displayModel,
      renderer: jobRenderer,
    );

    viewModel = ViewModel(displayModel: displayModel);
  }

  @override
  Widget build(BuildContext context) {
    setState(() {});

    return FlutterMapView(
        mapModel: mapModel,
        viewModel: viewModel,
        graphicFactory: graphicFactory);
  }
}

Also i saw WidgetsFlutterBinding.ensureInitialized(); in an answer and added my void main() but didnt solved.

Error Showing;

Error in debug console;

Restarted application in 161ms.
Error: Unsupported operation: _Namespace
    at Object.throw_ [as throw] (http://localhost:60585/dart_sdk.js:5067:11)
    at Function.get _namespacePointer [as _namespacePointer] (http://localhost:60585/dart_sdk.js:56707:17)
    at Function._namespacePointer (http://localhost:60585/dart_sdk.js:54523:28)
    at Function._dispatchWithNamespace (http://localhost:60585/dart_sdk.js:54526:31)
    at io._File.new.exists (http://localhost:60585/dart_sdk.js:54530:23)
at readbufferfile.ReadbufferFile.new._openRaf (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:82:30)
    at _openRaf.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at readbufferfile.ReadbufferFile.new.[_openRaf] (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:77:20)
at readbufferfile.ReadbufferFile.new.length (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:93:29)
    at length.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at readbufferfile.ReadbufferFile.new.length (http://localhost:60585/packages/mapsforge_flutter/src/mapfile/readbufferfile.dart.lib.js:91:20)
at mapfile.MapFile.__._init (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15605:75)
    at _init.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at mapfile.MapFile.__.[_init] (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15602:20)
at from (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15586:34)
    at from.next (<anonymous>)
    at runBody (http://localhost:60585/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:60585/dart_sdk.js:40621:7)
at Function.from (http://localhost:60585/packages/mapsforge_flutter/src/cache/memorytilebitmapcache.dart.lib.js:15584:20)
at map_show._MapShowState.new.initState (http://localhost:60585/packages/mapping_tool/pages/map/map_show.dart.lib.js:166:23)


来源: stackexchange

问:
How to make my SvelteKit API work in production (Github Pages)?

Background

I have my project deployed to Github Pages here: https://zeddrix.github.io/jw-guitar-tabs, so I have this in my svelte.config.js file:

```<code>kit: {
    ...
    paths: {
        base: '/jw-guitar-tabs'
    },
    appDir: 'internal',
    ...
}
</code>```

I have this in my __layout.svelte:

```<code><script lang="ts">
    import { base } from '$app/paths';
    ...
    const fetchFromDBAndStore = async (category: SongCategoriesType) => {
        const res = await fetch(`${base}/api/categories/original-songs`);
        const data = await res.json();
        console.log(data);

    ...other code...
    };

    ...I have my code here that uses this data...
</script>

<Layout><slot /></Layout>
</code>```

Side note: I put it in this file so that this runs on any page, but I have a code to make sure that this doesn't run if I already have the data. This is not the issue.

This calls on the file: src/routes/api/categories/original-songs.ts:

```<code>import fetchSongsDB from '$utils/fetchSongsDB';

export const get = async () => fetchSongsDB('originals');
</code>```

And this fetchSongsDB function fetches the songs from my database.

Everything is working fine in development mode when I run npm run dev and even in preview mode when I run npm run preview after build, of course, in localhost:3000/jw-guitar-tabs.

Issue

However, on the static github page at https://zeddrix.github.io/jw-guitar-tabs, I get this:

It serves the 404 Github Page as the response. I guess it's because it can't find the src/routes/api/categories/original-songs.ts file. But of course Github will not find this file because the deployed folder to gh-pages is the build folder so I don't have this original file route anymore.

How would I solve this?

答:
Rename original-songs.ts to original-songs.json.ts

Change the

```<code>fetch(`${base}/api/categories/original-songs`);
</code>```

to

```<code>fetch(`${base}/api/categories/original-songs.json`);
</code>```

That allows the adapter-static to generate the json files at build time.

(These are static files, to see changes made in mongodb will require a rebuild & redeploy to GitHub pages)

Sometimes the static adapter doesn't autodetect the endpoint.

You can help the adapter by specifying the url in svelte.config.js

  kit: {
    prerender: {
      entries: [
        "*",
        "/api/categories/original-songs.json",
```

Bonus tip: The /favorites url redirects to /favorites/ when refreshing the page, add trailingSlash: "never", to kit to generate favorites.html instead of favorites/index.html and keep the /favorites url on refresh.

ContentLicense: CC BY-SA 4.0

Body:
Background

I have my project deployed to Github Pages here: https://zeddrix.github.io/jw-guitar-tabs, so I have this in my svelte.config.js file:

kit: {
    ...
    paths: {
        base: '/jw-guitar-tabs'
    },
    appDir: 'internal',
    ...
}

I have this in my __layout.svelte:

<Layout><slot /></Layout>

Side note: I put it in this file so that this runs on any page, but I have a code to make sure that this doesn't run if I already have the data. This is not the issue.

This calls on the file: src/routes/api/categories/original-songs.ts:

import fetchSongsDB from '$utils/fetchSongsDB';

export const get = async () => fetchSongsDB('originals');

And this fetchSongsDB function fetches the songs from my database.

Everything is working fine in development mode when I run npm run dev and even in preview mode when I run npm run preview after build, of course, in localhost:3000/jw-guitar-tabs.

Issue

However, on the static github page at https://zeddrix.github.io/jw-guitar-tabs, I get this:

It serves the 404 Github Page as the response. I guess it's because it can't find the src/routes/api/categories/original-songs.ts file. But of course Github will not find this file because the deployed folder to gh-pages is the build folder so I don't have this original file route anymore.

How would I solve this?

Body:
Rename original-songs.ts to original-songs.json.ts

Change the

fetch(`${base}/api/categories/original-songs`);

to

fetch(`${base}/api/categories/original-songs.json`);

That allows the adapter-static to generate the json files at build time.

(These are static files, to see changes made in mongodb will require a rebuild & redeploy to GitHub pages)

Sometimes the static adapter doesn't autodetect the endpoint.

You can help the adapter by specifying the url in svelte.config.js

  kit: {
    prerender: {
      entries: [
        "*",
        "/api/categories/original-songs.json",

Bonus tip: The /favorites url redirects to /favorites/ when refreshing the page, add trailingSlash: "never", to kit to generate favorites.html instead of favorites/index.html and keep the /favorites url on refresh.


问:
Extends interface of generic type T in typescript
Hi am trying to extend interface Message . I am having an error in code as shown below
can someone explain how to proceed with data: T

Am getting the following errors

```<code> component.ts:102:8 - error TS2554: Expected 2-3 arguments, but got 1.

    102       .subscribe(({ studentId,courseNumber }) => {

    node_modules/rxjs/internal/Observable.d.ts:51:39
        51     subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;
                                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    An argument for 'error' was not provided.
</code>```

In my MessageService.ts i have the following

```<code>
interface Message<T> {
  data :T;
  type: MessageActionType;
}

type Messages = {
  [MessageActionType.TeacherRequest]: Subject<TeacherMessageData>;
  [MessageActionType.StudentRequest]: Subject<StudentMessageData>;
};

type MessageData = TeacherMessageData & PersonProcessWebSocketMessageData ;

private messages: Messages = this.getMessages();

private getMessages(): Messages {
    return Object.values(MessageActionType).reduce(
      (accumulator: Messages, nextValue: MessageActionType) => ({
        ...accumulator,
        [nextValue]: new Subject<object>(),
      }),
      {} as Messages
    );
  }

private messageHandler = ({ data, type }:Message<MessageData>): void => {
    this.messages[type].next(data);
  };

  public save<T extends keyof Messages>(actionType: T): Messages[T] {
    if (!this.messages.hasOwnProperty(actionType)) {
      throw new NonFatalError(
        `cannot save type ${
          actionType as string
        } because it is not a valid ActionType in MessageService`,
        'MessageService.save'
      );
    }

    return this.messages[actionType];
  }

</code>```

In my component i call the service messageservice where i invoke the method save

```<code> private destroy$ = new Subject<boolean>();
  this.messagesService
      .save(actionType)
      .pipe(takeUntil(this.destroy$))
      .subscribe(({ studentId, courseNumber }) => {
        if (studentId && courseNumber )
        ) {
          console.log("registered student")
        }
      });
</code>```

In my reference.ts, the data that is needed based on type of action

```<code>export interface TeacherMessageData{
  teacherId?: number;
  moduleNumber: string;
}

export interface StudentMessageData{
  courseNumber: string;
  studentId?: number;
}

</code>```

答:
You are getting the error because TS is using the incorrect (deprecated) overload for subscribe which requires at least 2 parameters (as per the error message):

subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;

whereas you want to be using this one in which all parameters are optional:

subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;

The only thing I can see which might be causing this is that you have an extra  ) after if (studentId && courseNumber ) which is might be confusing the compiler - but I am surprised it compiles at all.

Body:
Hi am trying to extend interface Message . I am having an error in code as shown below
can someone explain how to proceed with data: T

Am getting the following errors

 component.ts:102:8 - error TS2554: Expected 2-3 arguments, but got 1.

    102       .subscribe(({ studentId,courseNumber }) => {

    node_modules/rxjs/internal/Observable.d.ts:51:39
        51     subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;
                                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    An argument for 'error' was not provided.

In my MessageService.ts i have the following

interface Message<T> {
  data :T;
  type: MessageActionType;
}

type Messages = {
  [MessageActionType.TeacherRequest]: Subject<TeacherMessageData>;
  [MessageActionType.StudentRequest]: Subject<StudentMessageData>;
};

type MessageData = TeacherMessageData & PersonProcessWebSocketMessageData ;

private messages: Messages = this.getMessages();

private getMessages(): Messages {
    return Object.values(MessageActionType).reduce(
      (accumulator: Messages, nextValue: MessageActionType) => ({
        ...accumulator,
        [nextValue]: new Subject<object>(),
      }),
      {} as Messages
    );
  }

private messageHandler = ({ data, type }:Message<MessageData>): void => {
    this.messages[type].next(data);
  };

  public save<T extends keyof Messages>(actionType: T): Messages[T] {
    if (!this.messages.hasOwnProperty(actionType)) {
      throw new NonFatalError(
        `cannot save type ${
          actionType as string
        } because it is not a valid ActionType in MessageService`,
        'MessageService.save'
      );
    }

    return this.messages[actionType];
  }

In my component i call the service messageservice where i invoke the method save

 private destroy$ = new Subject<boolean>();
  this.messagesService
      .save(actionType)
      .pipe(takeUntil(this.destroy$))
      .subscribe(({ studentId, courseNumber }) => {
        if (studentId && courseNumber )
        ) {
          console.log("registered student")
        }
      });

In my reference.ts, the data that is needed based on type of action

export interface TeacherMessageData{
  teacherId?: number;
  moduleNumber: string;
}

export interface StudentMessageData{
  courseNumber: string;
  studentId?: number;
}


问:
How to add custom sign in page for FBA application
I have configured FBA for my web application which is working fine with default sign in pages. So i wanted to create custonm sign in page for that application. For that i have created a custom sign in page. but when i entered credential it gives me an error as below.

Server Error in '/' Application.

Object reference not set to an instance of an object.  Description: An
  unhandled exception occurred during the execution of the current web
  request. Please review the stack trace for more information about the
  error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not
  set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an
  object.]

  LdapContosoAuthentication.Layouts.LdapContosoAuthentication.LoginCustmCntrlPage.Button1_Click(Object
  sender, EventArgs e) +193

  System.Web.UI.WebControls.Button.OnClick(EventArgs e) +114

  System.Web.UI.WebControls.Button.RaisePostBackEvent(String
  eventArgument) +139

  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
  sourceControl, String eventArgument) +28

  System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  +2980

Can anyone tell me how can i solved that error?

答:
Put your custom page in layout folder and make below changes. So you can open your custom login page:

```<code><authentication mode="Forms">
  <forms loginUrl="/_layouts/CustomLogin.aspx" />
</authentication>
</code>```

Have you made any change in delegate control (login control) of login.aspx page?

ContentLicense: CC BY-SA 3.0

Body:
Put your custom page in layout folder and make below changes. So you can open your custom login page:

<authentication mode="Forms">
  <forms loginUrl="/_layouts/CustomLogin.aspx" />
</authentication>

Have you made any change in delegate control (login control) of login.aspx page?


问:
capacitor.settings.gradle' as it does not exist
I am new to Ionic while build the app in android. Its opening a project in Android Studio but while gradle sync its showing the following error</p>
```<code>Could not read script 'F:\IonicProjects\mis-tracking-master-latest\mis-tracking-master\mis-tracking\android\capacitor.settings.gradle' as it does not exist.
</code>```

答:
JUST DO

```<code>npx cap sync android
</code>```

If you only use capacitor from (Vuejs, nuxtjs, etc.)

Body:
I am new to Ionic while build the app in android. Its opening a project in Android Studio but while gradle sync its showing the following error

Could not read script 'F:\IonicProjects\mis-tracking-master-latest\mis-tracking-master\mis-tracking\android\capacitor.settings.gradle' as it does not exist.

Body:
JUST DO

npx cap sync android

If you only use capacitor from (Vuejs, nuxtjs, etc.)


问:
move Constraint Layout programmatically
I want to move a ConstraintLayout programmatically. I looked through some solutions on stack overflow but they didn't work for me.

There are two ConstraintLayouts placed vertically. When the code goes into else if("android.permission.CAMERA" in permissionList.toString(), the above constraint layout (layoutLocation) will be invisible and the below constraint layout (layoutCamera) will come up and take its position. I mark where I should use declare it with 'want to use here'.

Code (apology to not ba able to post the whole code due to patent reason)

```<code>class SplashFragment : Fragment() {

private lateinit var mContext: MainActivity

private lateinit var binding : FragmentSplashBinding
private val viewModel : SplashViewModel by inject()
private val getPermissionUseCase : GetPermissionUseCase by inject()

override fun onAttach(context: Context) {
    super.onAttach(context)
    mContext = context as MainActivity
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_splash, container, false)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.viewModel = viewModel
    binding.lifecycleOwner = viewLifecycleOwner

}

private fun actionApplicationSetting(permissionList : List<String>) {
    val layoutInflater = LayoutInflater.from(context)
    val view = layoutInflater.inflate(R.layout.dialog_splash, null)
    val alertDialog = AlertDialog.Builder(requireContext(), R.style.CustomAlertDialog).setView(view).create()
    val layoutLocation : ConstraintLayout = view.findViewById(R.id.layout_box_location)
    val layoutCamera : ConstraintLayout = view.findViewById(R.id.layout_box_camera)

    for(permission in permissionList) {
        if("android.permission.CAMERA" in permissionList.toString() && "android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
            layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
            layoutCamera.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
        }else if("android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
            layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
        }else if("android.permission.CAMERA" in permissionList.toString()) {
            layoutLocation.visibility = View.INVISIBLE
            // want to use here
        }
    }
    alertDialog.show()

}

}
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/layout_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_marginStart="70dp"
        android:layout_marginBottom="10dp"
        app:layout_constraintBottom_toBottomOf="@+id/layout_wrapper"
        app:layout_constraintEnd_toEndOf="@+id/layout_wrapper"
        app:layout_constraintStart_toStartOf="@+id/layout_wrapper">
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout_wrapper"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layout_box_location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layout_box_camera"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/layout_box_location" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

答: Instead of layoutLocation.visibility = View.INVISIBLE try layoutLocation.visibility = View.GONE

Title: move Constraint Layout programmatically

Body:
I want to move a ConstraintLayout programmatically. I looked through some solutions on stack overflow but they didn't work for me.

There are two ConstraintLayouts placed vertically. When the code goes into else if("android.permission.CAMERA" in permissionList.toString(), the above constraint layout (layoutLocation) will be invisible and the below constraint layout (layoutCamera) will come up and take its position. I mark where I should use declare it with 'want to use here'.

Code (apology to not ba able to post the whole code due to patent reason)

class SplashFragment : Fragment() {

private lateinit var mContext: MainActivity

private lateinit var binding : FragmentSplashBinding
private val viewModel : SplashViewModel by inject()
private val getPermissionUseCase : GetPermissionUseCase by inject()

override fun onAttach(context: Context) {
    super.onAttach(context)
    mContext = context as MainActivity
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_splash, container, false)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.viewModel = viewModel
    binding.lifecycleOwner = viewLifecycleOwner

}

private fun actionApplicationSetting(permissionList : List<String>) {
    val layoutInflater = LayoutInflater.from(context)
    val view = layoutInflater.inflate(R.layout.dialog_splash, null)
    val alertDialog = AlertDialog.Builder(requireContext(), R.style.CustomAlertDialog).setView(view).create()
    val layoutLocation : ConstraintLayout = view.findViewById(R.id.layout_box_location)
    val layoutCamera : ConstraintLayout = view.findViewById(R.id.layout_box_camera)

    for(permission in permissionList) {
        if("android.permission.CAMERA" in permissionList.toString() && "android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
            layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
            layoutCamera.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
        }else if("android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
            layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
        }else if("android.permission.CAMERA" in permissionList.toString()) {
            layoutLocation.visibility = View.INVISIBLE
            // want to use here
        }
    }
    alertDialog.show()

}

}

XML

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/layout_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_marginStart="70dp"
        android:layout_marginBottom="10dp"
        app:layout_constraintBottom_toBottomOf="@+id/layout_wrapper"
        app:layout_constraintEnd_toEndOf="@+id/layout_wrapper"
        app:layout_constraintStart_toStartOf="@+id/layout_wrapper">
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout_wrapper"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layout_box_location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layout_box_camera"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/layout_box_location" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>


问:
Visual Studio Code Deleting Custom Color Themes
I have made my own custom color theme for visual studio code following the directions at https://code.visualstudio.com/api/extension-guides/color-theme#create-a-new-color-theme. In order to use the theme, I copy and paste the theme's folder into the extensions folder of visual studio code. This works fine until anywhere from an hour to a month when visual studio code randomly decides to delete my custom color theme from the extensions folder, and I have to copy it over again.

How do I get visual studio code to stop deleting my custom color theme?

I have tried turning sync settings both on and off, and messing with my sync settings settings in general. Even with it off though my theme will eventually get deleted. I have also messed with internal layout of my theme and its package.json, copying both from guides online and themes already existing in the extensions folder. This does not fix it. I have been considering publishing my color theme to the vs market as a solution, but this seems like a hassle and it would require me to divulge a lot of personal information to microsoft which I do not want to do.

Does anyone else have any ideas what is going on and how to fix it? The nondeterministic nature of this bug has been driving me crazy. I will be eternally grateful to anyone with the solution.

答:
You can package your extension using vsce in your extension folder:

```<code>npm install vsce
vsce package
</code>```

This will create a .vsix file of your extension. You can then install this file using the code command:

```<code>code --install-extension my-extension.vsix
</code>```

Using this way I have never experienced an issue like you described.

Body:
You can package your extension using vsce in your extension folder:

npm install vsce
vsce package

This will create a .vsix file of your extension. You can then install this file using the code command:

code --install-extension my-extension.vsix

Using this way I have never experienced an issue like you described.


问:
Monotone weighted interpolation
Given two points (x1, y1) and (x2, y2), the linear interpolation at x (between x1 and x2) is y = (y1*(x2-x)+y2*(x-x1))/(x2-x1).

But when the two points are of different importance, this linear interpolation may not be ideal.

Suppose the weights of the two points are w1 and w2, a modification to the above linear interpolation may be y = (y1*w1*(x2-x)+y2*w2*(x-x1))/(w1*(x2-x)+w2*(x-x1)). I don't find a name to this interpolation. What is the name of this interpolation?

approxfun() in R is just linear interpolation. Does R have an implementation of the weighted interpolation that I described above?

EDIT: I am not sure if spline is relevant to this question. But I just add it as a tag in case it is relevant. If not, please remove it.

I mention spline, because I think there may be a way to expand the linear interpolation to spline so that different weights can be given to the input points. It also has the added benefit of making the fitted curve smooth. My above-proposed interpolation method may not be continuous at the 1st order derivative. But a spline should make the 1st order derivative continuous, which is good to have.

EDIT2: When the input data is monotone, my proposed rational interpolation should maintain the monotonousness (i.e., the input x_i < x_{i+1} and y_i < y_{i+1}, the output curve should have positive 1st order derivative). But a regular spline interpolation can not guarantee so. What spline interpolation can maintain the monotonousness? Is there an implementation that is read to use?

EDIT3: It seems that this implementation can maintain monotonicity. But it does not support weights. An implementation along this line but support weights could be helpful. Note that weights have an effect similar to that of the rational interpolation. In the rational interpolation above, if the weight is high at an input point, the slope should be greater than that if the weights of all points were equal.

https://rdrr.io/cran/signal/man/pchip.html

答: Linear interpolation is equivalent to the trivial case of a first order spline. Weighing using a line does not make sense, because there is just one possible line between any two points. Therefore, it's the same interpolation line no matter on how you choose your weights. If you want to use a polynomial of a higher degree, there is indeed a e.g. weighted cubic spline interpolation emphasizing one point more than the other.</p>

Title: Monotone weighted interpolation


问:
How to remove special characters from a XML Document?
Input:

```<code><author>John & Fleck</author>

<date>Jun<e> 2002</date>

<keyword>example <keyword</keyword>
</code>```

Output:

```<code><author>John  Fleck</author>

<date>June 2002</date>

<keyword>example keyword</keyword>
</code>```

I want to keep the xml doc intact and remove the special characters as you can see in the above example

答:
You're not trying to remove special characters from an XML Document.

You're trying to convert a non-XML document to XML.

To do that you need to parse the non-XML document, and to do that you need to know (a) the grammar to which it conforms and (b) the rules for how this grammar maps to the grammar of XML.

You haven't told us anything about this grammar; you've just given one example of a non-XML document, and that's not enough to infer the general rules.

Body:
Input:

<author>John & Fleck</author>

<date>Jun<e> 2002</date>

<keyword>example <keyword</keyword>

Output:

<author>John  Fleck</author>

<date>June 2002</date>

<keyword>example keyword</keyword>

I want to keep the xml doc intact and remove the special characters as you can see in the above example


问:
How to set CheckedListBox items to checked by default
Is there an option in Visual Studio to set all items in a CheckedListBox to checked by default? By this I mean I would like all items to be checked upon start up, and the user can unselect items as needed.

If not, is my only option to set all items to checked programatically inside the constructor?

答:
try this i have used in VB.net

At the time of adding Items in CheckedListBox use below code :

For i As Integer = 0 To Dt.Rows.Count - 1
    CLB_FolderList.Items.Add(Dt.Rows(i)("Source_FolderName").ToString(),True)
Next
```


问:
Text doesn't break in special case
I have a problem that the text doesn't break in a popup made with Vue.js which is included in the header like this:

The text breaks normally if I include the popup into the main screen, but doesn't if I include it into the header. I have also drawn border around the
 element which contains the text and the border is drawn correctly.

Here is the sample code: https://codesandbox.io/s/cold-feather-3zi3d?file=/src/components/BasicModal.vue

答:
Try to remove :

```<code>white-space: nowrap;
</code>```

from header-frame class

Title: Text doesn't break in special case

Body:
Try to remove :

white-space: nowrap;

from header-frame class


问:
Algorithm of Permutation with Limited Repetition
Is there an algorithm to list out all the permutations with a limited repetition? If there is an existing Java library, it would be so nice!

Let's say we have 3 items {A, B, C}. We want a permutation of 2 items. It would be 3P2:

```<code>{A, B}
{A, C}
{B, A}
{B, C}
{C, A}
{C, B}
</code>```

But if we allow a maximum repetition of twice. How it would be like? (i don't really know.)

I try to imaging we are getting a permutation of 2 from the set {A, A, B, B, C, C}. It would be 6P2 = 30. But we have to take away those duplicates. I have done it by hand and it is 9. I don't know how to calculate 9 from maths.

```<code>{A, A}
{A, B}
{A, C}
{B, B}
{B, A}
{B, C}
{C, C}
{C, A}
{C, B}
</code>```

(In fact 3P2 with a repetition of 2 is not a good example. It is because there are only 2 elements in the permutations. Therefore, there are no differences between an unlimited repetition. 4P3 with a repetition of 2 would be a nicer example. But it would be tough to list out all the permutations.)

A better example for illustration: 4P3 of set {A, B, C, D}:

```<code>{A, B, C}
{A, B, D}
{A, C, B}
{A, C, D}
{A, D, B}
{A, D, C}
... repeat for permutations starting from {B, ... }
... repeat for permutations starting from {C, ... }
... repeat for permutations starting from {D, ... }
</code>```

And 4P3 of set {A, B, C, D} with a repetition limit of 2:

```<code>{A, A, B}
{A, A, C}
{A, A, D}

{A, B, A}
{A, B, B}
{A, B, C}
{A, B, D}

{A, C, A}
{A, C, B}
{A, C, C}
{A, C, D}

{A, D, A}
{A, D, B}
{A, D, C}
{A, D, D}

... repeat for permutations starting from {B, ... }
... repeat for permutations starting from {C, ... }
... repeat for permutations starting from {D, ... }
</code>```

Here is a webpage talking about similar thing. But it seems it requires nPn (selecting all the elements). Also, i still need an algorithm to generate and list out the permutations.

Thanks for your helps!

For programming implementation, in fact there is a "not smart" approach.

For set {A, B, C, D}, keep a complementary array int used[0, 0, 0, 0], which are the numbers of times each element is used. Increment the count every time an element is chosen, and pass a copy of the array forward (down the call tree). Then with the recursive approach inspired here, alter it to allow unlimited repetition (by not deleting the selected one from the element set), and add an if (used[i] <= LIMIT) checking statement after for.

This is "not smart" and not good enough because we need a complementary array and require checking the used number every time.

答:
You can think of permutations as binary carry processing. For example, 0000,0001,0010 in binary.</p>
```<code> public static int[][] permutation(int size,int carryNum) {
    if(size == 0)
        return new int[0][0];

    int s = size - 1;
    int cNum = carryNum - 1;
    int s1 = 1;
    for(int i=0;i<size;i++){
        s1 = s1 * carryNum ;
    }
    int[][] commands = new int[s1][size];
    for (int i = 1; i < s1; i++) {

        for (int j = s; j >= 0; j--) {
            commands[i][j] = commands[i - 1][j];
        }

        for (int j = s; j >= 0; j--) {
            int last = commands[i][j];
            if ((last + 1) > cNum) {
                commands[i][j] = 0;
            } else {
                commands[i][j] = last + 1;
                break;
            }
        }
    }
    return commands;
}

public static void main(String[] args) {

    int[][] s = permutation(7,3);
    for (int[] command : s) {
        System.out.println(Arrays.toString(command));
    }
}

output result:

[0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 1]

[0, 0, 0, 0, 0, 0, 2]
          .
          .
          .
[0, 0, 0, 0, 2, 0, 2]

[2, 2, 2, 2, 2, 2, 2]
</code>```

Body:
Is there an algorithm to list out all the permutations with a limited repetition? If there is an existing Java library, it would be so nice!

Let's say we have 3 items {A, B, C}. We want a permutation of 2 items. It would be 3P2:

{A, B}
{A, C}
{B, A}
{B, C}
{C, A}
{C, B}

But if we allow a maximum repetition of twice. How it would be like? (i don't really know.)

I try to imaging we are getting a permutation of 2 from the set {A, A, B, B, C, C}. It would be 6P2 = 30. But we have to take away those duplicates. I have done it by hand and it is 9. I don't know how to calculate 9 from maths.

{A, A}
{A, B}
{A, C}
{B, B}
{B, A}
{B, C}
{C, C}
{C, A}
{C, B}

(In fact 3P2 with a repetition of 2 is not a good example. It is because there are only 2 elements in the permutations. Therefore, there are no differences between an unlimited repetition. 4P3 with a repetition of 2 would be a nicer example. But it would be tough to list out all the permutations.)

A better example for illustration: 4P3 of set {A, B, C, D}:

{A, B, C}
{A, B, D}
{A, C, B}
{A, C, D}
{A, D, B}
{A, D, C}
... repeat for permutations starting from {B, ... }
... repeat for permutations starting from {C, ... }
... repeat for permutations starting from {D, ... }

And 4P3 of set {A, B, C, D} with a repetition limit of 2:

{A, A, B}
{A, A, C}
{A, A, D}

{A, B, A}
{A, B, B}
{A, B, C}
{A, B, D}

{A, C, A}
{A, C, B}
{A, C, C}
{A, C, D}

{A, D, A}
{A, D, B}
{A, D, C}
{A, D, D}

... repeat for permutations starting from {B, ... }
... repeat for permutations starting from {C, ... }
... repeat for permutations starting from {D, ... }

Here is a webpage talking about similar thing. But it seems it requires nPn (selecting all the elements). Also, i still need an algorithm to generate and list out the permutations.

Thanks for your helps!

For programming implementation, in fact there is a "not smart" approach.

For set {A, B, C, D}, keep a complementary array int used[0, 0, 0, 0], which are the numbers of times each element is used. Increment the count every time an element is chosen, and pass a copy of the array forward (down the call tree). Then with the recursive approach inspired here, alter it to allow unlimited repetition (by not deleting the selected one from the element set), and add an if (used[i] <= LIMIT) checking statement after for.

This is "not smart" and not good enough because we need a complementary array and require checking the used number every time.

Body:
You can think of permutations as binary carry processing. For example, 0000,0001,0010 in binary.

 public static int[][] permutation(int size,int carryNum) {
    if(size == 0)
        return new int[0][0];

    int s = size - 1;
    int cNum = carryNum - 1;
    int s1 = 1;
    for(int i=0;i<size;i++){
        s1 = s1 * carryNum ;
    }
    int[][] commands = new int[s1][size];
    for (int i = 1; i < s1; i++) {

        for (int j = s; j >= 0; j--) {
            commands[i][j] = commands[i - 1][j];
        }

        for (int j = s; j >= 0; j--) {
            int last = commands[i][j];
            if ((last + 1) > cNum) {
                commands[i][j] = 0;
            } else {
                commands[i][j] = last + 1;
                break;
            }
        }
    }
    return commands;
}

public static void main(String[] args) {

    int[][] s = permutation(7,3);
    for (int[] command : s) {
        System.out.println(Arrays.toString(command));
    }
}

output result:

[0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 1]

[0, 0, 0, 0, 0, 0, 2]
          .
          .
          .
[0, 0, 0, 0, 2, 0, 2]

[2, 2, 2, 2, 2, 2, 2]


问:
DropzoneJS & Laravel - Output form validation errors
I am trying to output form validation errors when you hover over the "X" in the dropped off file in Dropzone.

What I get:

How can I make the object Object output the actual error message from the form validation? I can alert the error message but can't actually show the error message upon hovering over the x.

My js file:

```<code> Dropzone.options.fileupload = {
    maxFilesize: 20,

    init: function () {
        thisDropzone = this;
        this.on("error", function (file, responseText) {

                $.each(responseText, function (index, value) {
                    alert( value); //this shows the alert of the error message

                });

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

My controller:

```<code>$this->validate($request, [
        'file' => 'max:20000',
    ]);
</code>```

答:
If you want just laravel validation errors use that.

```<code>...
        init: function () {
            thisDropzone = this;
            this.on("error", function (file, responseText) {
                $.each(responseText, function (index, value) {
                    if (index === 'errors'){
                        $('.dz-error-message').text(value.file);
                    }
                });
            });
        },
...
</code>```

Or if you just want dropzone.js error outputs change.

```<code>if(index === message)
</code>```

Body:
I am trying to output form validation errors when you hover over the "X" in the dropped off file in Dropzone.

What I get:

How can I make the object Object output the actual error message from the form validation? I can alert the error message but can't actually show the error message upon hovering over the x.

My js file:

 Dropzone.options.fileupload = {
    maxFilesize: 20,

    init: function () {
        thisDropzone = this;
        this.on("error", function (file, responseText) {

                $.each(responseText, function (index, value) {
                    alert( value); //this shows the alert of the error message

                });

        });
    }
};

My controller:

$this->validate($request, [
        'file' => 'max:20000',
    ]);

Body:
If you want just laravel validation errors use that.

...
        init: function () {
            thisDropzone = this;
            this.on("error", function (file, responseText) {
                $.each(responseText, function (index, value) {
                    if (index === 'errors'){
                        $('.dz-error-message').text(value.file);
                    }
                });
            });
        },
...

Or if you just want dropzone.js error outputs change.

if(index === message)


问:
Kafka producer resetting the last seen epoch of partition, resulting in timeout
Recently my kafka producer running as a cronjob on a kubernetes cluster has started doing the following when pushing new messages to the queue:

```<code>{"@version":1,"source_host":"<job pod name>","message":"[Producer clientId=producer-1] Resetting the last seen epoch of partition <topic name> to 4 since the associated topicId changed from null to JkTOJi-OSzavDEomRvAIOQ","thread_name":"kafka-producer-network-thread | producer-1","@timestamp":"2022-02-11T08:45:40.212+0000","level":"INFO","logger_name":"org.apache.kafka.clients.Metadata"}
</code>```

This results in the producer running into a timeout:

```<code>"exception":{"exception_class":"java.util.concurrent.ExecutionException","exception_message":"org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for <topic name>:120000 ms has passed since batch creation", stacktrace....}
</code>```

The logs of the kafka consumer pod and kafka cluster pods don't show any out-of-the-ordinary changes.

Has anyone seen this behavior before and if yes, how do I prevent it?

答:
Reason:

the Java API mode generator cannot connect with Kafka

Solution:

On each server Add a sentence to the properties file

host.name = server IP;
```

Body:
Recently my kafka producer running as a cronjob on a kubernetes cluster has started doing the following when pushing new messages to the queue:

{"@version":1,"source_host":"<job pod name>","message":"[Producer clientId=producer-1] Resetting the last seen epoch of partition <topic name> to 4 since the associated topicId changed from null to JkTOJi-OSzavDEomRvAIOQ","thread_name":"kafka-producer-network-thread | producer-1","@timestamp":"2022-02-11T08:45:40.212+0000","level":"INFO","logger_name":"org.apache.kafka.clients.Metadata"}

This results in the producer running into a timeout:

"exception":{"exception_class":"java.util.concurrent.ExecutionException","exception_message":"org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for <topic name>:120000 ms has passed since batch creation", stacktrace....}

The logs of the kafka consumer pod and kafka cluster pods don't show any out-of-the-ordinary changes.

Has anyone seen this behavior before and if yes, how do I prevent it?


问:
javascript reduce on properties of an array of objects acting weird
I have an array like this:

```<code>parts: [
      {
        name: 'Fundamentals of React',
        exercises: 10,
        id: 1
      },
      {
        name: 'Using props to pass data',
        exercises: 7,
        id: 2
      },
      {
        name: 'State of a component',
        exercises: 14,
        id: 3
      },
      {
        name: 'Redux',
        exercises: 11,
        id: 4
      }
    ]
</code>```

I would like to get the sum of the excercises. I'm trying to accomplish it thusly:

```<code>const Total = (props) => {

  const total = props.parts.reduce( (prev, cur) => {

    console.log('prev.excercises : ', prev.exercises)
    console.log('cur.excercises : ', cur.exercises)

    return prev.exercises + cur.exercises
  })

  return (
    <>
      <p>Number of exercises {total}</p>
    </>
  )
}
</code>```

But this results in NaN. The console shows why this result occurs, but not why the prev.excercises value is acting weird:

```<code>prev.excercises :  10
cur.excercises :  7
prev.excercises :  undefined
cur.excercises :  14
prev.excercises :  undefined
cur.excercises :  11
</code>```

I'm really new to js, so there is probably something really simple I'm doing wrong.. appreciate the help in advance!

答:
You're trying to access it as an object but are returning it as an integer

```<code>const Total = (props) => {

  const total = props.parts.reduce( (prev, cur) => {

    console.log('prev.excercises : ', prev.exercises)
    console.log('cur.excercises : ', cur.exercises)

    return {exercises : prev.exercises + cur.exercises}
  })
</code>```

If you don't want to return object you can do it like this

```<code>const total = props.parts.reduce( (prev,    cur) => {
prev=typeof prev==="object" ?  prev.exercises:prev
console.log('prev.excercises : ', prev)
console.log('cur.excercises : ', cur.exercises)

return  prev+ cur.exercises  })
</code>```

Body:
I have an array like this:

parts: [
      {
        name: 'Fundamentals of React',
        exercises: 10,
        id: 1
      },
      {
        name: 'Using props to pass data',
        exercises: 7,
        id: 2
      },
      {
        name: 'State of a component',
        exercises: 14,
        id: 3
      },
      {
        name: 'Redux',
        exercises: 11,
        id: 4
      }
    ]

I would like to get the sum of the excercises. I'm trying to accomplish it thusly:

const Total = (props) => {

  const total = props.parts.reduce( (prev, cur) => {

    console.log('prev.excercises : ', prev.exercises)
    console.log('cur.excercises : ', cur.exercises)

    return prev.exercises + cur.exercises
  })

  return (
    <>

Number of exercises {total}

    </>
  )
}

But this results in NaN. The console shows why this result occurs, but not why the prev.excercises value is acting weird:

prev.excercises :  10
cur.excercises :  7
prev.excercises :  undefined
cur.excercises :  14
prev.excercises :  undefined
cur.excercises :  11

I'm really new to js, so there is probably something really simple I'm doing wrong.. appreciate the help in advance!

Body:
You're trying to access it as an object but are returning it as an integer

const Total = (props) => {

  const total = props.parts.reduce( (prev, cur) => {

    console.log('prev.excercises : ', prev.exercises)
    console.log('cur.excercises : ', cur.exercises)

    return {exercises : prev.exercises + cur.exercises}
  })

If you don't want to return object you can do it like this

const total = props.parts.reduce( (prev,    cur) => {
prev=typeof prev==="object" ?  prev.exercises:prev
console.log('prev.excercises : ', prev)
console.log('cur.excercises : ', cur.exercises)

return  prev+ cur.exercises  })


问:
Regex exclude rows in csv that has forbidding word
I've been trying to exclude all the rows that contain 'shirt' and then from that have the rows that have 'cotton' (case insensitive)
for example:

"Cotton Shirt for sale" - don't include

"Cotton Dress for Sale" - Pass

"dress shirt-V-neck-cotton" -fail

"no words relevant" - Fail (no cotton in it)

"cotton-url click" - pass

My regex:

```<code>pattern = re.compile('(?i)^((?!.*shirt).).*(?=.*cotton.*)')
</code>```

But for some reason my rows in csv still remain on a sentence:

"Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look"

my code:

```<code>pattern1 = re.compile("(?i)(.*shirt.*)")
    with open("sample.csv", 'r', encoding="utf-8") as bigCSV:
        csv_reader = csv.reader(bigCSV)
        counterWithout = 0
        counterCheck = 0
        headFlag = True
        for row in csv_reader:
            if headFlag:
                header = row
                headFlag = False
            if any(pattern.match(line) for line in row)://there is a difference in the number of rows here
                if any(pattern1.match(line) for line in row):
                    print(row)
                    counterCheck += 1
                counterWithout += 1
</code>```

Help fix regex please

答:
You can use .*(cotton)?.*shirt.*|.*shirt.*(cotton)?.*
It will match every shirt with condition of cotton before or after it. So you can delete every row that satisfy this.

example

```<code>import re
import csv

header = ['name', 'val', 'test']
data = [
    ["Cotton Dress for Sale", 1, 'test1'],
    ["dress shirt-V-neck-cotton", 2, 'test2'],
    ["no words relevant", 3, 'test3'],
    ["Cotton Shirt for sale", 4, 'test4'],
    ["Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look", 5, 'test5'],
    ["cotton-url click", 6, 'test6'],
]

# with open('test.csv', 'w', encoding='UTF8', newline='') as f:
#     writer = csv.writer(f)

#     # write the header
#     writer.writerow(header)

#     # write multiple rows
#     writer.writerows(data)

regex = re.compile(r'.*(cotton)?.*shirt.*|.*shirt.*(cotton)?.*',
                   re.IGNORECASE)
with open('test.csv', 'r', encoding='UTF8', newline='') as f:
    reader = csv.reader(f)
    headFlag = True
    counterWithout = 0
    counterCheck = 0
    for row in reader:
        if headFlag:
            header = row
            headFlag = False
        else:
            if not any(regex.match(x) for x in row):
                counterCheck += 1
                print(row)
            else:
                counterWithout += 1
    print(f'{counterCheck=}, {counterWithout=}')

</code>```

Body:
I've been trying to exclude all the rows that contain 'shirt' and then from that have the rows that have 'cotton' (case insensitive)
for example:

"Cotton Shirt for sale" - don't include

"Cotton Dress for Sale" - Pass

"dress shirt-V-neck-cotton" -fail

"no words relevant" - Fail (no cotton in it)

"cotton-url click" - pass

My regex:

pattern = re.compile('(?i)^((?!.*shirt).).*(?=.*cotton.*)')

But for some reason my rows in csv still remain on a sentence:

"Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look"

my code:

pattern1 = re.compile("(?i)(.*shirt.*)")
    with open("sample.csv", 'r', encoding="utf-8") as bigCSV:
        csv_reader = csv.reader(bigCSV)
        counterWithout = 0
        counterCheck = 0
        headFlag = True
        for row in csv_reader:
            if headFlag:
                header = row
                headFlag = False
            if any(pattern.match(line) for line in row)://there is a difference in the number of rows here
                if any(pattern1.match(line) for line in row):
                    print(row)
                    counterCheck += 1
                counterWithout += 1

Help fix regex please

Body:
You can use .*(cotton)?.*shirt.*|.*shirt.*(cotton)?.*
It will match every shirt with condition of cotton before or after it. So you can delete every row that satisfy this.

example

import re
import csv

header = ['name', 'val', 'test']
data = [
    ["Cotton Dress for Sale", 1, 'test1'],
    ["dress shirt-V-neck-cotton", 2, 'test2'],
    ["no words relevant", 3, 'test3'],
    ["Cotton Shirt for sale", 4, 'test4'],
    ["Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look", 5, 'test5'],
    ["cotton-url click", 6, 'test6'],
]

# with open('test.csv', 'w', encoding='UTF8', newline='') as f:
#     writer = csv.writer(f)

#     # write the header
#     writer.writerow(header)

#     # write multiple rows
#     writer.writerows(data)

regex = re.compile(r'.*(cotton)?.*shirt.*|.*shirt.*(cotton)?.*',
                   re.IGNORECASE)
with open('test.csv', 'r', encoding='UTF8', newline='') as f:
    reader = csv.reader(f)
    headFlag = True
    counterWithout = 0
    counterCheck = 0
    for row in reader:
        if headFlag:
            header = row
            headFlag = False
        else:
            if not any(regex.match(x) for x in row):
                counterCheck += 1
                print(row)
            else:
                counterWithout += 1
    print(f'{counterCheck=}, {counterWithout=}')


问:
Why pandas dataframe lost its decimal position when downloaded to csv and opened in excel
Background - I have a pandas dataframe, that I want to save in csv, then further analyze in Microsoft Excel

Here's my pandas dataframe

```<code>percentile  avg             min
96          109572.557673   104500.000000
100         351892.011122   193328.000000
</code>```

My code is just basic like

`pd_read_csv(table.csv)'

When I save and this to excel the result become

How to download that with normal decimal place

答:
The problem is most likely that Excel is set to use as decimal separator the character , while the pandas to_csv() function uses .. Try to modify the export line as this:

```<code>df.to_csv('file.csv', index=False, decimal=',')
</code>```

Body:
Background - I have a pandas dataframe, that I want to save in csv, then further analyze in Microsoft Excel

Here's my pandas dataframe

percentile  avg             min
96          109572.557673   104500.000000
100         351892.011122   193328.000000

My code is just basic like

`pd_read_csv(table.csv)'

When I save and this to excel the result become

How to download that with normal decimal place

Body:
The problem is most likely that Excel is set to use as decimal separator the character , while the pandas to_csv() function uses .. Try to modify the export line as this:

df.to_csv('file.csv', index=False, decimal=',')


问:
How do i get Django to store already uploaded cover image to a user without getting it deleted
How do i get Django to store already uploaded cover image to a user without getting it deleted when a new image is uploaded, but simply replace it? I'm having a challenge trying to figure out how to maintain old cover images while adding new once to a user. what happens is that when i upload a new cover image it simply deletes the previous one from the database. Here is my cover image models:

```<code>class AccountCover(models.Model):
    account = models.ForeignKey(Account,on_delete=models.CASCADE)
    cover_image = models.ImageField(max_length=255,upload_to=get_cover_cover_image_filepath,default=get_default_cover_image,)
</code>```

My view.py

```<code> cover = AccountCover.objects.filter(account=account.id).first()
    if request.user:
        forms = CoverImageForm(request.POST, request.FILES,instance=cover,
                        initial = {'cover_image':cover.cover_image})

    if request.method == 'POST':
        f = CoverImageForm(request.POST, request.FILES,instance=cover)
        if f.is_valid():
             data = forms.save()
             data.account = cover.account
             data.save()
             return redirect('account:edit', account.id)

    else:
        f = CoverImageForm()
    context['f'] = f
</code>```

答:
You can keep old instances of AccountCover by forcing the form to save a new one each time. Simply remove the instance argument in the form, and remember save the form with commit=false before to set the account foreign key.

forms = CoverImageForm(request.POST, request.FILES, initial={'cover_image': cover.cover_image})

# ...
data = forms.save(commit=False)
data.account = cover.account
data.save()
```

I guess you need to preserve the old database record, not just the image file. An image file without any relation to the user's registry has no utility.

Body:
How do i get Django to store already uploaded cover image to a user without getting it deleted when a new image is uploaded, but simply replace it? I'm having a challenge trying to figure out how to maintain old cover images while adding new once to a user. what happens is that when i upload a new cover image it simply deletes the previous one from the database. Here is my cover image models:

class AccountCover(models.Model):
    account = models.ForeignKey(Account,on_delete=models.CASCADE)
    cover_image = models.ImageField(max_length=255,upload_to=get_cover_cover_image_filepath,default=get_default_cover_image,)

My view.py

 cover = AccountCover.objects.filter(account=account.id).first()
    if request.user:
        forms = CoverImageForm(request.POST, request.FILES,instance=cover,
                        initial = {'cover_image':cover.cover_image})

    if request.method == 'POST':
        f = CoverImageForm(request.POST, request.FILES,instance=cover)
        if f.is_valid():
             data = forms.save()
             data.account = cover.account
             data.save()
             return redirect('account:edit', account.id)

    else:
        f = CoverImageForm()
    context['f'] = f

Body:
You can keep old instances of AccountCover by forcing the form to save a new one each time. Simply remove the instance argument in the form, and remember save the form with commit=false before to set the account foreign key.

forms = CoverImageForm(request.POST, request.FILES, initial={'cover_image': cover.cover_image})

# ...
data = forms.save(commit=False)
data.account = cover.account
data.save()

I guess you need to preserve the old database record, not just the image file. An image file without any relation to the user's registry has no utility.


问:
How can I read an IP address from the user in a bash script?
```<code>if [ "$1" == "-s" ]; then
  echo "Connecting to host.."
  scp root@IP_ADDRESS:/private/var/mobile/Library/SMS/sms.db /private/var/mobile/Media/BackupSMS
  echo " "
  exit
fi
</code>```

I need to ask user for a IP-address, that will then be placed where IP_ADDRESS is above. I'm new to scripts, but I'm trying.

How would I do this?

答:
Use the built in read command

```<code>read IP_ADDRESS
</code>```

or, if you want a nice prompt:

```<code>read -p "Enter ip address: " IP_ADDRESS
</code>```

and then add a $ to the scp line:

```<code>scp root@$IP_ADDRESS:/...
         ^
</code>```

Body:
if [ "$1" == "-s" ]; then
  echo "Connecting to host.."
  scp root@IP_ADDRESS:/private/var/mobile/Library/SMS/sms.db /private/var/mobile/Media/BackupSMS
  echo " "
  exit
fi

I need to ask user for a IP-address, that will then be placed where IP_ADDRESS is above. I'm new to scripts, but I'm trying.

How would I do this?

Body:
Use the built in read command

read IP_ADDRESS

or, if you want a nice prompt:

read -p "Enter ip address: " IP_ADDRESS

and then add a $ to the scp line:

scp root@$IP_ADDRESS:/...
         ^


问:
Elixir recovering erl_crash.dump from a k8s pod with memory issues
I have Elixir code running on Kubernetes pods which crashes from what I suspect is a memory issue. Once Elixir crashes the pod restarts and doesn't have the erl_crash.dump anywhere under the /opt/ directory, I suspect because the pod is ephemeral.

The log message I get is,

```<code>Crash dump is being written to: erl_crash.dump...done
</code>```

Is there some way to write this file to an s3 bucket or see what it's contents are to get more granular info on why the crash is occurring?

答: You could attach a persistent volume to the pods - this way you don't lose the file at reboot and you can retrieve it afterwards.</p>

Body:
I have Elixir code running on Kubernetes pods which crashes from what I suspect is a memory issue. Once Elixir crashes the pod restarts and doesn't have the erl_crash.dump anywhere under the /opt/ directory, I suspect because the pod is ephemeral.

The log message I get is,

Crash dump is being written to: erl_crash.dump...done

Is there some way to write this file to an s3 bucket or see what it's contents are to get more granular info on why the crash is occurring?


问:
Check if two numbers have same digits
I need to write a program which will check if two numbers have same digits.
For example:

```<code>a = 4423, b = 2433;
</code>```

Even though their digits don't appear the same amount if times, they have same digits.

```<code>#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}
</code>```

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

答:
Here is a simpler version of Aki Suihkonen's solution that works for all int values including INT_MIN:

```<code>#include <stdlib.h>

int digit_set(int a) {
    int set = 0;
    // construct the set, one bit per digit value.
    // do / while allows for digit_set(0) = 1
    // integer division truncates towards 0 so the
    // remainder is the negative value of the low digit
    // hence abs(a % 10) is the digit value.
    // this works for all values including INT_MIN
    do {
        set |= 1 << abs(a % 10);
    } while ((a /= 10) != 0);

    return set;
}

bool same_digits(int a, int b) { return digit_set(a) == digit_set(b); }
</code>```

Title: Check if two numbers have same digits

Body:
I need to write a program which will check if two numbers have same digits.
For example:

a = 4423, b = 2433;

Even though their digits don't appear the same amount if times, they have same digits.

#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

Body:
Here is a simpler version of Aki Suihkonen's solution that works for all int values including INT_MIN:

#include <stdlib.h>

int digit_set(int a) {
    int set = 0;
    // construct the set, one bit per digit value.
    // do / while allows for digit_set(0) = 1
    // integer division truncates towards 0 so the
    // remainder is the negative value of the low digit
    // hence abs(a % 10) is the digit value.
    // this works for all values including INT_MIN
    do {
        set |= 1 << abs(a % 10);
    } while ((a /= 10) != 0);

    return set;
}

bool same_digits(int a, int b) { return digit_set(a) == digit_set(b); }


问:
How do I convert the certain column of RDD into integer type and save it as txt?
For example, when I read a csv csv document and use rdd to transform it into a txt file, how do I choose the first columns and save it as the txt file?
It seems rdd do not have that special function to select the 1st column</p>

答:
Plain RDDs don't have any schema, unless you imposed one: so the concept of column doesn't really apply.
You can try with

```<code>rdd[0]
</code>```

and that will give you the data corresponding to the first column.

Body:
Plain RDDs don't have any schema, unless you imposed one: so the concept of column doesn't really apply.
You can try with

rdd[0]

and that will give you the data corresponding to the first column.


问:
How to listen `disconnect` event in Java NIO?
In java NIO server, we can register SelectionKey.OP_ACCEPT, listen and read channel from selector.select() and selector.selectedKeys().

But how to listen to the 'disconnected' event?

Trying channel.read() and catching the exception is a way if the channel has been read from the selector. But what should I do if the channel has not been read from the selector any more?

答: A disconnect is a read event with an error.</p>


问:
Programmatically download the QR image
I  tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.

Base on my code bellow.

```<code>function genQR(link_string){
    let qr_code_element = document.querySelector(".qr-code");

      if (link_string != "") {
          if (qr_code_element.childElementCount == 0) {
            generate(qr_code_element, link_string);
          } else {
          qr_code_element.innerHTML = "";
            generate(qr_code_element, link_string);
          }
      } else {
          alert("not valid QR input");
          qr_code_element.style = "display: none";
      }
  }

  function generate(qr_code_element, link_string) {
    qr_code_element.style = "";
    var qrcode = new QRCode(qr_code_element, {
        text: link_string,
        width: 200,
        height: 200,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

    let download = document.createElement("button");
    // qr_code_element.appendChild(download);

    let download_link = document.createElement("a");
    download_link.setAttribute("download", "qr.png");
    download_link.setAttribute("id", "downloadbtn");
    download_link.innerText = "Download";
    // download.appendChild(download_link);

    let qr_code_img = document.querySelector(".qr-code img");
    let qr_code_canvas = document.querySelector("canvas");

    if (qr_code_img.getAttribute("src") == null) {
      setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
      }, 300);
    } else {
        setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
        }, 300);
    }

    var clickEvent = new MouseEvent("click", {
      "view": window,
      "bubbles": true,
      "cancelable": false
  });

  //I expect the below line will automatically download the QR but nothing fires.
  download_link.dispatchEvent(clickEvent);
}
</code>```

If I use button to click and download by hand will works fine for me but I want to reduce too many steps.

I think I almost done here but failed.

Could anyone show me how to automatic download?

Thank you in advance.

答:
I've had this issue in the past, and I've worked around it by creating a small util function I can invoke upon button pressing. But invoking it directly at the end of your function should have the same result as a user click, effectively automatically downloading the QR code without user input.

```<code>export function download(blob, filename) {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.download = filename
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
}
</code>```

I'm guessing you could try passing generate as the first parameter if the object you're getting is a Blob. Otherwise, you'll probably need to convert it before.

Title: Programmatically download the QR image

Body:
I  tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.

Base on my code bellow.

function genQR(link_string){
    let qr_code_element = document.querySelector(".qr-code");

      if (link_string != "") {
          if (qr_code_element.childElementCount == 0) {
            generate(qr_code_element, link_string);
          } else {
          qr_code_element.innerHTML = "";
            generate(qr_code_element, link_string);
          }
      } else {
          alert("not valid QR input");
          qr_code_element.style = "display: none";
      }
  }

  function generate(qr_code_element, link_string) {
    qr_code_element.style = "";
    var qrcode = new QRCode(qr_code_element, {
        text: link_string,
        width: 200,
        height: 200,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

    let download = document.createElement("button");
    // qr_code_element.appendChild(download);

    let download_link = document.createElement("a");
    download_link.setAttribute("download", "qr.png");
    download_link.setAttribute("id", "downloadbtn");
    download_link.innerText = "Download";
    // download.appendChild(download_link);

    let qr_code_img = document.querySelector(".qr-code img");
    let qr_code_canvas = document.querySelector("canvas");

    if (qr_code_img.getAttribute("src") == null) {
      setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
      }, 300);
    } else {
        setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
        }, 300);
    }

    var clickEvent = new MouseEvent("click", {
      "view": window,
      "bubbles": true,
      "cancelable": false
  });

  //I expect the below line will automatically download the QR but nothing fires.
  download_link.dispatchEvent(clickEvent);
}

If I use button to click and download by hand will works fine for me but I want to reduce too many steps.

I think I almost done here but failed.

Could anyone show me how to automatic download?

Thank you in advance.

Body:
I've had this issue in the past, and I've worked around it by creating a small util function I can invoke upon button pressing. But invoking it directly at the end of your function should have the same result as a user click, effectively automatically downloading the QR code without user input.

export function download(blob, filename) {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.download = filename
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
}

I'm guessing you could try passing generate as the first parameter if the object you're getting is a Blob. Otherwise, you'll probably need to convert it before.


问:
Read XML into DataTable. Need to match Schema
I am trying to read an XML file into a DataTable and I am having a hard time matching the schema, and converting it properly.  This is what the XML could look like...

```<code><?xml version="1.0" encoding="utf-8"?>
<School>
  <Teacher>
    <Name>Teacher1</Name>
    <Student>
      <Student-Name>Student1</Student-Name>
      <Gender>M</Gender>
      <Address>Address1</Address>
    </Student>
    <Student>
      <Student-Name>Student2</Student-Name>
      <Gender>F</Gender>
      <Address>Address2</Address>
    </Student>
  </Teacher>
  <Teacher>
    <Name>Teacher2</Name>
    <Student>
      <Student-Name>Student3</Student-Name>
      <Gender>F</Gender>
      <Address>Address3</Address>
    </Student>
  </Teacher>
</School>
</code>```

I need to add it to a DataTable so that it the table looks like this

Name                       Student-Name          Gender         Address

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

Teacher1            Student1                        M              Address1

Teacher1            Student2                        F              Address2

Teacher2            Student3                        F              Address3

DataTable.ReadXML() --> wont allow me to read in this XML file. The error says that DataTable doesn't support schema inference

DataSet.ReadXML() --> doesn't pick up on the schema and separates this into two tables the first being a Teacher Table and the second being a Student Table, even when it is set to Infer the schema.

The other problem is that I am doing this with several types of XML files.  All of which have a different number of nodes nested within the student, and I need to make this generic so that it can read the XML regardless of the number of nodes.

I am wondering if I need to set up an XmlReader to read this in, or if there is any settings on the DataSet.ReadXML()/DataTable.ReadXML() that I need to use.  Thank You.

答:
You encounter this problem because you are working using a DataTable (not a DataSet) and your XML schema has not been defined.

Here is an example in which SQL data are exported in a DataTable

```<code>Dim sTable As String = "payement"
Dim sFileName = "db.select." & sTable & ".xml"
Dim cmd = New NpgsqlCommand(sSQL, npgconx)
Dim rxSheet as IDataReader= cmd.ExecuteReader()

Dim dtSheet = New DataTable(sTable)
dtSheet.Load(rxSheet)
dtSheet.WriteXml(sFileName)
dtSheet.WriteXmlSchema(sFileName.Replace(".xml", ".Schema.xml"))
</code>```

In this code just after having exported SQL Data in XML file, WriteXmlSchema() function is used to export XML Schema.

and now, same data are imported in a DataTable

```<code>Dim sTable As String = "payement"
Dim sFileName = "db.select." & sTable & ".xml"
Dim dtSheet = New DataTable(sTable)
dtSheet.ReadXmlSchema(sFileName.Replace(".xml", ".Schema.xml"))
dtSheet.ReadXml(sFileName)
</code>```

It is important that ReadXmlSchema() function is executed before ReadXml() function.

In WriteXml() function it is also important to pass the table's name.

I use this code to serialize tuples returned by a SELECT SQL command on my PC when number of records is extremely high so next time I want to test my program I don't load DataBase with my big extraction ... and some time I don't wait a lot of time.

Body:
I am trying to read an XML file into a DataTable and I am having a hard time matching the schema, and converting it properly.  This is what the XML could look like...

<?xml version="1.0" encoding="utf-8"?>
<School>
  <Teacher>
    <Name>Teacher1</Name>
    <Student>
      <Student-Name>Student1</Student-Name>
      <Gender>M</Gender>
      <Address>Address1</Address>
    </Student>
    <Student>
      <Student-Name>Student2</Student-Name>
      <Gender>F</Gender>
      <Address>Address2</Address>
    </Student>
  </Teacher>
  <Teacher>
    <Name>Teacher2</Name>
    <Student>
      <Student-Name>Student3</Student-Name>
      <Gender>F</Gender>
      <Address>Address3</Address>
    </Student>
  </Teacher>
</School>

I need to add it to a DataTable so that it the table looks like this

Name                       Student-Name          Gender         Address

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

Teacher1            Student1                        M              Address1

Teacher1            Student2                        F              Address2

Teacher2            Student3                        F              Address3

DataTable.ReadXML() --> wont allow me to read in this XML file. The error says that DataTable doesn't support schema inference

DataSet.ReadXML() --> doesn't pick up on the schema and separates this into two tables the first being a Teacher Table and the second being a Student Table, even when it is set to Infer the schema.

The other problem is that I am doing this with several types of XML files.  All of which have a different number of nodes nested within the student, and I need to make this generic so that it can read the XML regardless of the number of nodes.

I am wondering if I need to set up an XmlReader to read this in, or if there is any settings on the DataSet.ReadXML()/DataTable.ReadXML() that I need to use.  Thank You.

Body:
You encounter this problem because you are working using a DataTable (not a DataSet) and your XML schema has not been defined.

Here is an example in which SQL data are exported in a DataTable

Dim sTable As String = "payement"
Dim sFileName = "db.select." & sTable & ".xml"
Dim cmd = New NpgsqlCommand(sSQL, npgconx)
Dim rxSheet as IDataReader= cmd.ExecuteReader()

Dim dtSheet = New DataTable(sTable)
dtSheet.Load(rxSheet)
dtSheet.WriteXml(sFileName)
dtSheet.WriteXmlSchema(sFileName.Replace(".xml", ".Schema.xml"))

In this code just after having exported SQL Data in XML file, WriteXmlSchema() function is used to export XML Schema.

and now, same data are imported in a DataTable

Dim sTable As String = "payement"
Dim sFileName = "db.select." & sTable & ".xml"
Dim dtSheet = New DataTable(sTable)
dtSheet.ReadXmlSchema(sFileName.Replace(".xml", ".Schema.xml"))
dtSheet.ReadXml(sFileName)

It is important that ReadXmlSchema() function is executed before ReadXml() function.

In WriteXml() function it is also important to pass the table's name.

I use this code to serialize tuples returned by a SELECT SQL command on my PC when number of records is extremely high so next time I want to test my program I don't load DataBase with my big extraction ... and some time I don't wait a lot of time.


问:
Low quality of xml preview in android studio
I was designing my layout, however the layout is in a low quality state.
How i can resolve it?

答: this problem is solved at android studio version 2021.1.1 (Bumblebee) that released at 25 January 2022</p>


答:
One option I would consider is mounting some node-local storage into the pod and setting $ERL_CRASH_DUMP to point to it. You can do that in the rel/env.sh.eex file.

Then use a DaemonSet pod to watch the same volume for these files and push them to S3.

Title: Elixir recovering erl_crash.dump from a k8s pod with memory issues


问:
How to use icon on quick_actions
I have a doubt about the icon property of Quick Icons.

Can someone give a proper example of how to use it?

A list of names of native supported icons would be great.

There is a way to use custom icons? If yes, how?

答:
I found this solution on github topex-psy

You can add icons following these steps :

Generate App Icon from here App Icon Generator and give it a name like "ic_myicon"

You will get 5 folders, paste it in   \android\app\src\main\res

In the first folder mipmap-hdpi copy your icon and paste in \android\app\src\main\res\drawable

In same folder \android\app\src\main\res\drawable Create new file quick_actions.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_myicon" /> <!-- here your icon name-->

</layer-list>
</code>```

In \android\app\src\main\res\values Create new file styles.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
 <resources>
 ...
  <style name="QuickActions">
    <item name="android:windowBackground">@drawable/quick_actions</item>
  </style>
 </resources>
</code>```

Title: How to use icon on quick_actions

Body:
I found this solution on github topex-psy

You can add icons following these steps :

Generate App Icon from here App Icon Generator and give it a name like "ic_myicon"

You will get 5 folders, paste it in   \android\app\src\main\res

In the first folder mipmap-hdpi copy your icon and paste in \android\app\src\main\res\drawable

In same folder \android\app\src\main\res\drawable Create new file quick_actions.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_myicon" /> <!-- here your icon name-->

</layer-list>

In \android\app\src\main\res\values Create new file styles.xml

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
 ...
  <style name="QuickActions">
    <item name="android:windowBackground">@drawable/quick_actions</item>
  </style>
 </resources>


问:
Download a file from HTTPS using download.file()
I would like to read online data to R using download.file() as shown below.

```<code>URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
download.file(URL, destfile = "./data/data.csv", method="curl")
</code>```

Someone suggested to me that I add the line setInternet2(TRUE), but it still doesn't work.

The error I get is:

```<code>Warning messages:
1: running command 'curl  "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"  -o "./data/data.csv"' had status 127
2: In download.file(URL, destfile = "./data/data.csv", method = "curl",  :
  download had nonzero exit status
</code>```

Appreciate your help.

答:
Downloading files through the httr-package also works:

URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"

httr::GET(URL,
          httr::write_disk(path = basename(URL),
                           overwrite = TRUE))
```

Body:
I would like to read online data to R using download.file() as shown below.

URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
download.file(URL, destfile = "./data/data.csv", method="curl")

Someone suggested to me that I add the line setInternet2(TRUE), but it still doesn't work.

The error I get is:

Warning messages:
1: running command 'curl  "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"  -o "./data/data.csv"' had status 127
2: In download.file(URL, destfile = "./data/data.csv", method = "curl",  :
  download had nonzero exit status

Appreciate your help.