问:
Read Sequence Diagram from XMI using EMF
I searched a lot about reading UML diagrams from XMI using EMF Java
 Eclipse. I only found solutions to read class diagram but my task is
to read Sequence diagram from XMI. Can anyone please help me out?</p>

答:
After a hectic efforts finally I found a working solution, You only need to put path of error-free UML diagram in the main class, Provided code will read all nodes and sub-nodes respectively. You can customize the code as per your requirements. This code can be used both for class diagram as well as sequence diagram.

Sequence Diagram Model Reader (Main Class)

```<code>public static void main(String[] args) {
     MododelLoader umlModel= new ModelLoader();
    // sequence diagram XMI
     String umlFilePath = "SequenceDiagramUML\\sequenceDiagram.uml";

        String uri = null;
        try {
            uri = umlModel.getFileURI(umlFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object objModel = umlModel.loadModel(uri);
        Model sourceModel;
        EList<PackageableElement> sourcePackagedElements = null;
        if (objModel instanceof Model) {
            sourceModel = (Model) objModel;
            sourcePackagedElements = sourceModel.getPackagedElements();
        } else if (objModel instanceof Package) {
            Package sourcePackage = (Package) objModel;
            sourcePackagedElements = sourcePackage.getPackagedElements();
        }
        for (PackageableElement element : sourcePackagedElements){
            //for nested package
            if(element.eClass() == UMLPackage.Literals.PACKAGE){
                org.eclipse.uml2.uml.Package nestedPackage =
             (org.eclipse.uml2.uml.Package) element;
                EList<PackageableElement> nestedPackagedElements =
           nestedPackage.getPackagedElements();
                for (PackageableElement nestedElement : nestedPackagedElements){
                    printModelDetails(nestedElement);
                }
            }
            else
                printModelDetails(element);
        }

</code>```

Model Details Extractor (Helper Class)

```<code> private static void printModelDetails(PackageableElement element){

    int counterEnd=1;
    String classfierName="Test";
    boolean isClass=false;
    if(element.eClass()==UMLPackage.Literals.COLLABORATION){
        Collaboration collab=(Collaboration)element;
        System.out.println("Collaboration Name: "+collab.getName());
        EList<Behavior> behaviours = collab.getOwnedBehaviors();

        System.out.println("Behavious: ");
        if(!behaviours.isEmpty()){
            for (Behavior obj: behaviours)
            {
                Interaction interaction=(Interaction)obj;
                EList<Lifeline> lifelines=interaction.getLifelines();
                EList<InteractionFragment> fragments=interaction.getFragments();
                EList<Message> messages=interaction.getMessages();

                if(!lifelines.isEmpty()) {

                    for(Lifeline lifln:lifelines) {

                EList<EAnnotation> inter=lifln.getEAnnotations();
                  }
                }
               if(!fragments.isEmpty()) {

                    for(InteractionFragment frag:fragments) {

                    EList<Element> elements=    frag.getOwnedElements();
                    }
                }
               if(!messages.isEmpty()) {

                    for(Message msg:messages) {
                        EList<ConnectorEnd>
   connectorEnds=msg.getConnector().getEnds();
                        String conEnd1=connectorEnds.get(0).getRole().getName();
                        String conEnd2=connectorEnds.get(1).getRole().getName();
                        System.out.println("Messages: "+msg.getName());

           System.out.println("Message_Receive_event:"+msg.getMessageSort());

                        System.out.println("ConEnd1:  "+conEnd1);
                        System.out.println("ConEnd2:  "+conEnd2);
                    }
                }
                System.out.println("Interaction Name: "+obj.getName());
                EList<Connector> connectors = obj.getOwnedConnectors();
                System.out.println("Connectors: ");
                if(!connectors.isEmpty()){
                    for (Connector behav: connectors)
                    {

                        EList<ConnectorEnd> property = behav.getEnds();
                        if(!property.isEmpty()) {

                            System.out.println("Connector Ends "+counterEnd);
                            for(ConnectorEnd ends:property) {

                     System.out.println("EndName:"+ends.getRole().getName());
                            }
                            counterEnd++;
                        }
                    }
                }
</code>```

ModelLoader Class (Helper Class)

```<code>public class ModelLoader {
     private final ResourceSet RESOURCE_SET;
      public ModelLoader() {
      RESOURCE_SET = new ResourceSetImpl();
    }

/**
 * A method that converts input path to uri and return uri.
 *
 * @param path
 * @return uri
 * @throws Exception
 */
public String getFileURI(String path) throws Exception {
    File f = new File(path);
    String uri = f.toURI().toString();
    return uri;
}
/**
 * A method that loads UML/Ecore model from input URI.
 *
 * @param uri:String
 * @return model:Object
 */
public Object loadModel(String uri){
    URI modelUri = URI.createURI(uri);
    registerPackages(RESOURCE_SET);
    registerResourceFactories();
    String relPath = null;
    try {
        relPath = new File(".").getCanonicalPath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    URIConverter.URI_MAP.put(URI.createURI("platform:/plugin/org.eclipse.uml2.uml/"),
             URI.createURI("jar:file:"+
              relPath+"/EMF_Lib/org.eclipse.uml2.uml_3.1.2.v201010261927.jar! /"));
    Resource resource = null;
    try {
        resource = RESOURCE_SET.getResource(modelUri, true);
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    Object result;

    Model _model = (Model) EcoreUtil.getObjectByType(resource.getContents(),
    UMLPackage.Literals.MODEL);
    result = _model;
    // org.eclipse.uml2.uml.Package _model =
    //
      (org.eclipse.uml2.uml.Package)EcoreUtil.getObjectByType(resource.getContents(),
    // UMLPackage.Literals.PACKAGE);
    if (_model == null) {
        result = resource.getContents().get(0);
    }
    return result;
    }

public void loadResources(){
    registerPackages(RESOURCE_SET);
    registerResourceFactories();
    String relPath = null;
    try {
        relPath = new File(".").getCanonicalPath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    URIConverter.URI_MAP.put(URI.createURI("platform:/plugin/org.eclipse.uml2.uml/"),

         URI.createURI("jar:file:"+
       relPath+"/EMF_Lib/org.eclipse.uml2.uml_3.1.2.v201010261927.jar!/"));
    }

     private void registerResourceFactories()
  {
    Map extensionFactoryMap =
      Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap();
    extensionFactoryMap.put(UMLResource.FILE_EXTENSION,
      UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(Ecore2XMLResource.FILE_EXTENSION,
       Ecore2XMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(UML22UMLResource.FILE_EXTENSION,
  UML22UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(UMLResource.FILE_EXTENSION,
  UML22UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(UMLResource.FILE_EXTENSION,
     UML22UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(Resource.Factory.Registry.DEFAULT_EXTENSION,new
   XMIResourceFactoryImpl());
    }

    private void registerPackages(ResourceSet resourceSet)
     {
    Map packageRegistry = resourceSet.getPackageRegistry();
    packageRegistry.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE);
    packageRegistry.put(Ecore2XMLPackage.eNS_URI, Ecore2XMLPackage.eINSTANCE);
    packageRegistry.put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
    packageRegistry .put(UML212UMLResource.UML_METAMODEL_NS_URI,
  UMLPackage.eINSTANCE);
    //for RSA

   packageRegistry.put("http://www.eclipse.org/uml2/2.0.0/UML",UMLPackage.eINSTANCE);
    //for Papyrus

   packageRegistry.put("http://www.eclipse.org/uml2/5.0.0/UML",UMLPackage.eINSTANCE);
    }
     }
</code>```

Body:
After a hectic efforts finally I found a working solution, You only need to put path of error-free UML diagram in the main class, Provided code will read all nodes and sub-nodes respectively. You can customize the code as per your requirements. This code can be used both for class diagram as well as sequence diagram.

Sequence Diagram Model Reader (Main Class)

public static void main(String[] args) {
     MododelLoader umlModel= new ModelLoader();
    // sequence diagram XMI
     String umlFilePath = "SequenceDiagramUML\\sequenceDiagram.uml";

        String uri = null;
        try {
            uri = umlModel.getFileURI(umlFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object objModel = umlModel.loadModel(uri);
        Model sourceModel;
        EList<PackageableElement> sourcePackagedElements = null;
        if (objModel instanceof Model) {
            sourceModel = (Model) objModel;
            sourcePackagedElements = sourceModel.getPackagedElements();
        } else if (objModel instanceof Package) {
            Package sourcePackage = (Package) objModel;
            sourcePackagedElements = sourcePackage.getPackagedElements();
        }
        for (PackageableElement element : sourcePackagedElements){
            //for nested package
            if(element.eClass() == UMLPackage.Literals.PACKAGE){
                org.eclipse.uml2.uml.Package nestedPackage =
             (org.eclipse.uml2.uml.Package) element;
                EList<PackageableElement> nestedPackagedElements =
           nestedPackage.getPackagedElements();
                for (PackageableElement nestedElement : nestedPackagedElements){
                    printModelDetails(nestedElement);
                }
            }
            else
                printModelDetails(element);
        }

Model Details Extractor (Helper Class)

 private static void printModelDetails(PackageableElement element){

    int counterEnd=1;
    String classfierName="Test";
    boolean isClass=false;
    if(element.eClass()==UMLPackage.Literals.COLLABORATION){
        Collaboration collab=(Collaboration)element;
        System.out.println("Collaboration Name: "+collab.getName());
        EList<Behavior> behaviours = collab.getOwnedBehaviors();

        System.out.println("Behavious: ");
        if(!behaviours.isEmpty()){
            for (Behavior obj: behaviours)
            {
                Interaction interaction=(Interaction)obj;
                EList<Lifeline> lifelines=interaction.getLifelines();
                EList<InteractionFragment> fragments=interaction.getFragments();
                EList<Message> messages=interaction.getMessages();

                if(!lifelines.isEmpty()) {

                    for(Lifeline lifln:lifelines) {

                EList<EAnnotation> inter=lifln.getEAnnotations();
                  }
                }
               if(!fragments.isEmpty()) {

                    for(InteractionFragment frag:fragments) {

                    EList<Element> elements=    frag.getOwnedElements();
                    }
                }
               if(!messages.isEmpty()) {

                    for(Message msg:messages) {
                        EList<ConnectorEnd>
   connectorEnds=msg.getConnector().getEnds();
                        String conEnd1=connectorEnds.get(0).getRole().getName();
                        String conEnd2=connectorEnds.get(1).getRole().getName();
                        System.out.println("Messages: "+msg.getName());

           System.out.println("Message_Receive_event:"+msg.getMessageSort());

                        System.out.println("ConEnd1:  "+conEnd1);
                        System.out.println("ConEnd2:  "+conEnd2);
                    }
                }
                System.out.println("Interaction Name: "+obj.getName());
                EList<Connector> connectors = obj.getOwnedConnectors();
                System.out.println("Connectors: ");
                if(!connectors.isEmpty()){
                    for (Connector behav: connectors)
                    {

                        EList<ConnectorEnd> property = behav.getEnds();
                        if(!property.isEmpty()) {

                            System.out.println("Connector Ends "+counterEnd);
                            for(ConnectorEnd ends:property) {

                     System.out.println("EndName:"+ends.getRole().getName());
                            }
                            counterEnd++;
                        }
                    }
                }

ModelLoader Class (Helper Class)

public class ModelLoader {
     private final ResourceSet RESOURCE_SET;
      public ModelLoader() {
      RESOURCE_SET = new ResourceSetImpl();
    }

/**
 * A method that converts input path to uri and return uri.
 *
 * @param path
 * @return uri
 * @throws Exception
 */
public String getFileURI(String path) throws Exception {
    File f = new File(path);
    String uri = f.toURI().toString();
    return uri;
}
/**
 * A method that loads UML/Ecore model from input URI.
 *
 * @param uri:String
 * @return model:Object
 */
public Object loadModel(String uri){
    URI modelUri = URI.createURI(uri);
    registerPackages(RESOURCE_SET);
    registerResourceFactories();
    String relPath = null;
    try {
        relPath = new File(".").getCanonicalPath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    URIConverter.URI_MAP.put(URI.createURI("platform:/plugin/org.eclipse.uml2.uml/"),
             URI.createURI("jar:file:"+
              relPath+"/EMF_Lib/org.eclipse.uml2.uml_3.1.2.v201010261927.jar! /"));
    Resource resource = null;
    try {
        resource = RESOURCE_SET.getResource(modelUri, true);
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    Object result;

    Model _model = (Model) EcoreUtil.getObjectByType(resource.getContents(),
    UMLPackage.Literals.MODEL);
    result = _model;
    // org.eclipse.uml2.uml.Package _model =
    //
      (org.eclipse.uml2.uml.Package)EcoreUtil.getObjectByType(resource.getContents(),
    // UMLPackage.Literals.PACKAGE);
    if (_model == null) {
        result = resource.getContents().get(0);
    }
    return result;
    }

public void loadResources(){
    registerPackages(RESOURCE_SET);
    registerResourceFactories();
    String relPath = null;
    try {
        relPath = new File(".").getCanonicalPath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    URIConverter.URI_MAP.put(URI.createURI("platform:/plugin/org.eclipse.uml2.uml/"),

         URI.createURI("jar:file:"+
       relPath+"/EMF_Lib/org.eclipse.uml2.uml_3.1.2.v201010261927.jar!/"));
    }

     private void registerResourceFactories()
  {
    Map extensionFactoryMap =
      Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap();
    extensionFactoryMap.put(UMLResource.FILE_EXTENSION,
      UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(Ecore2XMLResource.FILE_EXTENSION,
       Ecore2XMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(UML22UMLResource.FILE_EXTENSION,
  UML22UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(UMLResource.FILE_EXTENSION,
  UML22UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(UMLResource.FILE_EXTENSION,
     UML22UMLResource.Factory.INSTANCE);
    extensionFactoryMap.put(Resource.Factory.Registry.DEFAULT_EXTENSION,new
   XMIResourceFactoryImpl());
    }

    private void registerPackages(ResourceSet resourceSet)
     {
    Map packageRegistry = resourceSet.getPackageRegistry();
    packageRegistry.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE);
    packageRegistry.put(Ecore2XMLPackage.eNS_URI, Ecore2XMLPackage.eINSTANCE);
    packageRegistry.put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
    packageRegistry .put(UML212UMLResource.UML_METAMODEL_NS_URI,
  UMLPackage.eINSTANCE);
    //for RSA

   packageRegistry.put("http://www.eclipse.org/uml2/2.0.0/UML",UMLPackage.eINSTANCE);
    //for Papyrus

   packageRegistry.put("http://www.eclipse.org/uml2/5.0.0/UML",UMLPackage.eINSTANCE);
    }
     }


来源: stackexchange

问:
Which is make best performance dynamicaly added controls or drag and drop form toolbox?
I am new to software programming.

So tell me Which is make best performance dynamicaly added controls or drag and drop form toolbox? and how to calculate performance?

答:
Dynamically Added a controls make best performance then drag and drop
dynamic control can be occupy less memory then drag and drop and u can also create HTML controls dynamically...
and other option is you can create your own controls (User controls) also and then use it in your page</p>

ContentLicense: CC BY-SA 3.0


问:
Getting started with PhpStorm
I am setting up the PhpStorm Workshop, using this link.

However when I get to the step about setting up the docker-compose.yml file, I keep getting errors.

```<code>D:\xampp\htdocs\phpstormworkshop>
docker-compose up
ERROR: yaml.parser.ParserError: while parsing a block mapping
in ".\docker-compose.yml", line 18, column 5
expected <block end>, but found '<block sequence start>'
in ".\docker-compose.yml", line 25, column 7
</code>```

The file is the file that came with PhpStorm and all I have done is uncomment the Windows path.

```<code>version: '2'
services:
  debug:
    image: phpstorm/php-71-apache-xdebug
    ports:
     - "8081:80"
    volumes:
      - ./workshop/07_Debugging:/var/www/html
    environment:
        #For Windows and macOS, replace the line below with `host.docker.internal`, which will automatically resolve to the internal address of the host Docker is running on.
        #For Linux, replace the line below with your hostname, which you can obtain by executing `hostname` in Terminal.
        XDEBUG_CONFIG: remote_host=host.docker.internal

        #For macOS, if you use a local Homebrew php-fpm installation, port `9000` (which is the default debugging port) may become occupied. PhpStorm will remain silent on starting listening for incoming connections. If this is the case, in the Settings | Languages & Frameworks | PHP | Debug, set the Debug port to 9001, and use the following configuration line instead.

        #XDEBUG_CONFIG: remote_host=host.docker.internal, remote_port=9001
  sftp:
    image: phpstorm/sftp-server
    ports:
      - "2022:22"
    volumes:
  #   Uncomment for Windows
       - C:/temp:/home/jetbrains/upload
  #   Uncomment for macOS/Linux
      - /tmp:/home/jetbrains/upload
    command: jetbrains:jetbrains:1001
  mysql:
      image: phpstorm/mysql
      ports:
        - "33056:3306"
      volumes:
        - ./data:/var/lib/mysql
</code>```

Any ideas why I might be getting this error? Have not been able to find anything on the web.

答:
You should uncomment only 1 of these lines:

```<code>  #   Uncomment for Windows
  #     - C:/temp:/home/jetbrains/upload
  #   Uncomment for macOS/Linux
      - /tmp:/home/jetbrains/upload
</code>```

OR (if you use Windows)

```<code>  #   Uncomment for Windows
       - C:/temp:/home/jetbrains/upload
  #   Uncomment for macOS/Linux
  #    - /tmp:/home/jetbrains/upload
</code>```

ContentLicense: CC BY-SA 4.0

Title: Getting started with PhpStorm

Body:
I am setting up the PhpStorm Workshop, using this link.

However when I get to the step about setting up the docker-compose.yml file, I keep getting errors.

D:\xampp\htdocs\phpstormworkshop>
docker-compose up
ERROR: yaml.parser.ParserError: while parsing a block mapping
in ".\docker-compose.yml", line 18, column 5
expected <block end>, but found '<block sequence start>'
in ".\docker-compose.yml", line 25, column 7

The file is the file that came with PhpStorm and all I have done is uncomment the Windows path.

version: '2'
services:
  debug:
    image: phpstorm/php-71-apache-xdebug
    ports:
     - "8081:80"
    volumes:
      - ./workshop/07_Debugging:/var/www/html
    environment:
        #For Windows and macOS, replace the line below with `host.docker.internal`, which will automatically resolve to the internal address of the host Docker is running on.
        #For Linux, replace the line below with your hostname, which you can obtain by executing `hostname` in Terminal.
        XDEBUG_CONFIG: remote_host=host.docker.internal

        #For macOS, if you use a local Homebrew php-fpm installation, port `9000` (which is the default debugging port) may become occupied. PhpStorm will remain silent on starting listening for incoming connections. If this is the case, in the Settings | Languages & Frameworks | PHP | Debug, set the Debug port to 9001, and use the following configuration line instead.

        #XDEBUG_CONFIG: remote_host=host.docker.internal, remote_port=9001
  sftp:
    image: phpstorm/sftp-server
    ports:
      - "2022:22"
    volumes:
  #   Uncomment for Windows
       - C:/temp:/home/jetbrains/upload
  #   Uncomment for macOS/Linux
      - /tmp:/home/jetbrains/upload
    command: jetbrains:jetbrains:1001
  mysql:
      image: phpstorm/mysql
      ports:
        - "33056:3306"
      volumes:
        - ./data:/var/lib/mysql

Any ideas why I might be getting this error? Have not been able to find anything on the web.

Body:
You should uncomment only 1 of these lines:

  #   Uncomment for Windows
  #     - C:/temp:/home/jetbrains/upload
  #   Uncomment for macOS/Linux
      - /tmp:/home/jetbrains/upload

OR (if you use Windows)

  #   Uncomment for Windows
       - C:/temp:/home/jetbrains/upload
  #   Uncomment for macOS/Linux
  #    - /tmp:/home/jetbrains/upload


问:
Is it safe to expose Firebase apiKey to the public?
The Firebase Web-App guide states I should put the given apiKey in my Html to initialize Firebase:

// TODO: Replace with your project's customized code snippet

```

By doing so, the apiKey is exposed to every visitor.

What is the purpose of that key and is it really meant to be public?

答:
You should not expose this info. in public, specially api keys.
It may lead to a privacy leak.

Before making the website public you should hide it. You can do it in 2 or more ways

Complex coding/hiding

Simply put firebase SDK codes at bottom of your website or app thus firebase automatically does all works. you don't need to put API keys anywhere

Body:
The Firebase Web-App guide states I should put the given apiKey in my Html to initialize Firebase:

// TODO: Replace with your project's customized code snippet

By doing so, the apiKey is exposed to every visitor.

What is the purpose of that key and is it really meant to be public?


问:
How to create a regex that matches either 0 occurrences, or between 7 and 50 occurrences?
In regex, I can match zero or more occurrences with *, and between 7 and 50 occurrences with {7,50}. How can I match either zero or between 7 and 50 occurrences?

答:
you can use this regex

```<code>(\S{7,50})?
</code>```

\S{7,50} means 7 to 50 occurrence of non-whitespace character

(\S{7,50})? means 0 or 1 occurrence of \S{7,50}

Body:
you can use this regex

(\S{7,50})?

\S{7,50} means 7 to 50 occurrence of non-whitespace character

(\S{7,50})? means 0 or 1 occurrence of \S{7,50}


问:
What are the parameters in arow function in JS?
please help the newbie figure it out.

There is such a code:

```<code>    function makeDouble (x) {
      return x * 2;
   }
    var doMath = (x, func) => func(x + 5);

   var num = 5;
</code>```

The task is:

*Using only makeDouble, doMath, and num, make the value of num equal to 20.

num = _____________________________________________________*

I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?

答:
Thank very much you all!

My problem was that I did not notice that the makeDouble() function in the parameters of the arrow function did not return the value, but the content of the function itself. And then in the body of the arrow function, it can be to call the makeDouble() function as a parameter.

Body:
please help the newbie figure it out.

There is such a code:

    function makeDouble (x) {
      return x * 2;
   }
    var doMath = (x, func) => func(x + 5);

   var num = 5;

The task is:

*Using only makeDouble, doMath, and num, make the value of num equal to 20.

num = _____________________________________________________*

I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?


问:
How is an int data stored on the memory in terms of bits? Is it not right-aligned?
I got really confused while I was trying some things out with fwrite function in C.

I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/

It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to 4 characters.

I thought that a bit representation of a value is right-aligned on memory. That is, 98(ascii of 'b') would be stored as

00000000 00000000 00000000 01100010

on the memory. So I expected the fwrite function to write ' ', ' ', ' ', 'b' in the txt file. Instead, it wrote 'b', ' ', ' ', ' '.

I got confused so I tested it again with pointer, hoping my knowledge about memory storage was not wrong and it was only about fwrite function. I made an integer array arr, and put (1<<8)+2, 98 in it.

I used char pointer to split each integer into four bytes. Here's the code.

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

int main()
{
    int arr[5]={(1<<8)+2, 98, 'c', 'd', 'e'};
    char *p = (char*)&(arr[0]);

    printf("%d %d %d %d %d %d", arr[0], (int)(*p), (int)(*(p+1)), (int)(*(p+2)), (int)(*(p+3)), (int)(*(p+4)));

    FILE *fp;

    fp = fopen("TestFile2.txt", "a");
    fwrite(arr, sizeof(char), 5, fp);
    fclose(fp);
}
</code>```

The program printed "258 2 1 0 0 98" on the console, and "  b" was written in TestFile2 (exlcluding "s).

In my knowledge, (1<<8)+2 representation in terms of bits is

00000000 00000000 00000001 00000010 so the program should've printed 258 0 0 1 2 0.

The weird thing is that the result is not even left-aligned bit representation of the value either.

How is a value store on the memory bitwise? Is it not like what I thought it is? Or, am I missing something else here?

Any helps would be really appreciated.

答:
Looks like you are missing the terminology Endianess. Many systems save their words (4-bytes in a 32-bit system) in "Little Endian" order - that is "little end" first. This means the least significant byte (LSB) is first (lowest address), and it goes up from there. That's why 2 is first (lowest address, LSB) and 1 is second, and then the 0s of the most significant bytes. Endianess is only important when you are manipulating byte level data, but then it is very important to know which endianess your system uses.

Alignment has nothing to do with it - single bytes are always read the same in all systems, like we usually write numbers - LSB on the right.

Body:
I got really confused while I was trying some things out with fwrite function in C.

I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/

It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to 4 characters.

I thought that a bit representation of a value is right-aligned on memory. That is, 98(ascii of 'b') would be stored as

00000000 00000000 00000000 01100010

on the memory. So I expected the fwrite function to write ' ', ' ', ' ', 'b' in the txt file. Instead, it wrote 'b', ' ', ' ', ' '.

I got confused so I tested it again with pointer, hoping my knowledge about memory storage was not wrong and it was only about fwrite function. I made an integer array arr, and put (1<<8)+2, 98 in it.

I used char pointer to split each integer into four bytes. Here's the code.

#include <stdio.h>

int main()
{
    int arr[5]={(1<<8)+2, 98, 'c', 'd', 'e'};
    char *p = (char*)&(arr[0]);

    printf("%d %d %d %d %d %d", arr[0], (int)(*p), (int)(*(p+1)), (int)(*(p+2)), (int)(*(p+3)), (int)(*(p+4)));

    FILE *fp;

    fp = fopen("TestFile2.txt", "a");
    fwrite(arr, sizeof(char), 5, fp);
    fclose(fp);
}

The program printed "258 2 1 0 0 98" on the console, and "  b" was written in TestFile2 (exlcluding "s).

In my knowledge, (1<<8)+2 representation in terms of bits is

00000000 00000000 00000001 00000010 so the program should've printed 258 0 0 1 2 0.

The weird thing is that the result is not even left-aligned bit representation of the value either.

How is a value store on the memory bitwise? Is it not like what I thought it is? Or, am I missing something else here?

Any helps would be really appreciated.


问:
Unable to get all the sub projects using JitPack
I am unable to load all the sub projects of this project: https://github.com/dankito/RichTextEditor
or the from the fork of same https://github.com/tangentq-admin/RichTextEditor

Ideally it should list:
RichTextEditorAndroid
RichTextEditorCommon
RichTextEditorJavaFX

But it loads only: RichTextEditorCommon and RichTextEditorJavaFX. RichTextEditorAndroid is missing.

URL: https://jitpack.io/#tangentq-admin/RichTextEditor/v2.0.15

I don't get what is missing in this subproject that it is not loading.

Thank you!

答:
no need JitPack

test it

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.0"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Body:
no need JitPack

test it

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.0"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
How to create the following XML tag through DOM in Java
```<code><tableCategory>
        <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
</tableCategory>
</code>```

In the above xml tag, I want to add one more item as follows-

```<code><item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>
</code>```

So finally the XML tag will look like-

```<code><tableCategory>
            <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
                <item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>
 </tableCategory>
</code>```

I am getting the tag -

```<code>Element paletteElement = (Element) doc.getElementsByTagName("tableCategory").item(0); //tag
</code>```

But not getting the clue after that.

答: Look at the Element.addContent() method</p>

Body:
<tableCategory>
        <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
</tableCategory>

In the above xml tag, I want to add one more item as follows-

<item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>

So finally the XML tag will look like-

<tableCategory>
            <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
                <item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>
 </tableCategory>

I am getting the tag -

Element paletteElement = (Element) doc.getElementsByTagName("tableCategory").item(0); //tag

But not getting the clue after that.

Body: Look at the Element.addContent() method


问:
Storing the active class data in localStorage of browser
I'm trying to store the active class of the clicked link in localStorage when i navigate to other page. How to do it?

A

P

S

```

答:
Create a id for each list..

```<code><body onload = "check_storage()">
<div id="collapse2" class="panel-collapse collapse">
<ul class="list-group">
  <li class="list-group-item active" id="id1" onclick= "active("id1")"><a id="a" style="color: white">A</a</li>
  <li class="list-group-item" id = "id2" onclick = "active("id2")"><a id="p" style="color: white">P</a></li>
  <li class="list-group-item" id = "id3" onclick = "active("id3")"><a id="s" style="color: white">S</a></li>
</ul>
</div>
</code>```

In JavaScript create funtion to store the id in localstorage

```<code>//onload of your page this will get called
 function check_storage() {
    //check if there is any value in localStorage
if (localStorage.getItem("listId") != null) {
    //get that value
    var val= localStorage.getItem("listId");
    console.log(val);
    setActive(val); //call function
     }
     }

 function active(id) {
localStorage.removeItem('listId');//clear previous data
localStorage.setItem("listId", id);//add data to storage
console.log(id);
      }

 function setActive(value) {
document.getElementById(value).classList.value = "list-group-item active";
    }
</code>```

On loading of the body of the page, it checks for the id in localstorage and make that id the active group. Upon calling active function, it clears previously stored data and adds the current id to local storage.

Body:
Create a id for each list..

<body onload = "check_storage()">
<div id="collapse2" class="panel-collapse collapse">
<ul class="list-group">
  <li class="list-group-item active" id="id1" onclick= "active("id1")"><a id="a" style="color: white">A</a</li>
  <li class="list-group-item" id = "id2" onclick = "active("id2")"><a id="p" style="color: white">P</a></li>
  <li class="list-group-item" id = "id3" onclick = "active("id3")"><a id="s" style="color: white">S</a></li>
</ul>
</div>

In JavaScript create funtion to store the id in localstorage

//onload of your page this will get called
 function check_storage() {
    //check if there is any value in localStorage
if (localStorage.getItem("listId") != null) {
    //get that value
    var val= localStorage.getItem("listId");
    console.log(val);
    setActive(val); //call function
     }
     }

 function active(id) {
localStorage.removeItem('listId');//clear previous data
localStorage.setItem("listId", id);//add data to storage
console.log(id);
      }

 function setActive(value) {
document.getElementById(value).classList.value = "list-group-item active";
    }

On loading of the body of the page, it checks for the id in localstorage and make that id the active group. Upon calling active function, it clears previously stored data and adds the current id to local storage.


问:
How to truncate a table in web api using EF Core?
```<code>await context.Database.ExecuteSqlCommand("TRUCATE Table Nlog")--
</code>```

I get an error from this code:

int does not contain a definition for get awaiter

I tried a stored procedure which just truncates the table. But that is also causing an error as required Id field is not present.

答:
The command that you are using is not an asynchronous command.  Remove the await or use

```<code>context.Database.ExecuteSqlCommandAsync("TRUNCATE Table Nlog").
</code>```

Also, keep in mind that you can only truncate a table if the records are not being referenced by other tables. If they are being referenced, you need to truncate those tables first before truncating this one.

Body:
await context.Database.ExecuteSqlCommand("TRUCATE Table Nlog")--

I get an error from this code:

int does not contain a definition for get awaiter

I tried a stored procedure which just truncates the table. But that is also causing an error as required Id field is not present.

Body:
The command that you are using is not an asynchronous command.  Remove the await or use

context.Database.ExecuteSqlCommandAsync("TRUNCATE Table Nlog").

Also, keep in mind that you can only truncate a table if the records are not being referenced by other tables. If they are being referenced, you need to truncate those tables first before truncating this one.


问:
How to set ssh-client port
My quession is like the follow

SSH session - fixed port on the client side

Is there any solution to use like tcp-client:1234 ------> tcp-server-ssh:22

答:
I have fix it to compile openssh,I use version openssh-portable-V_8_3_P1

add int  options.bind_port

fix main()

```<code>char myaddress[100]={};
.....
    case 'b':
        sscanf(optarg,"%[^:]:%d",myaddress,&options.bind_port);
        options.bind_address = myaddress;
        break;
</code>```

fix sshconnect.c at line430

```<code>    ((struct sockaddr_in*)&bindaddr)->sin_port= htons(options.bind_port);
    if (bind(sock, (struct sockaddr *)&bindaddr, bindaddrlen) != 0) {
        error("bind %s: %s", ntop, strerror(errno));
        goto fail;
    }
</code>```

./configure && make

ln -s .ssh  .myssh

try

```<code>./myssh  -b 192.168.1.153:5566  root@xxx.xyz
</code>```

then  you can see

```<code>vmuser@ubuntu:~$ lsof | grep "myssh.*TCP"
myssh     110179                 vmuser    3u     IPv4            4018314      0t0        TCP ubuntu:5566->myother_ubuntu:ssh (ESTABLISHED)
myssh     110187                 vmuser    3u     IPv4            4017137      0t0        TCP ubuntu:5588->myother_ubuntu:ssh (ESTABLISHED)

</code>```

Title: How to set ssh-client port

Body:
I have fix it to compile openssh,I use version openssh-portable-V_8_3_P1

add int  options.bind_port

fix main()

char myaddress[100]={};
.....
    case 'b':
        sscanf(optarg,"%[^:]:%d",myaddress,&options.bind_port);
        options.bind_address = myaddress;
        break;

fix sshconnect.c at line430

    ((struct sockaddr_in*)&bindaddr)->sin_port= htons(options.bind_port);
    if (bind(sock, (struct sockaddr *)&bindaddr, bindaddrlen) != 0) {
        error("bind %s: %s", ntop, strerror(errno));
        goto fail;
    }

./configure && make

ln -s .ssh  .myssh

try

./myssh  -b 192.168.1.153:5566  root@xxx.xyz

then  you can see

vmuser@ubuntu:~$ lsof | grep "myssh.*TCP"
myssh     110179                 vmuser    3u     IPv4            4018314      0t0        TCP ubuntu:5566->myother_ubuntu:ssh (ESTABLISHED)
myssh     110187                 vmuser    3u     IPv4            4017137      0t0        TCP ubuntu:5588->myother_ubuntu:ssh (ESTABLISHED)


问:
use of session value in constructor in laravel
I am stuck to the use of session value in __constructor but it shows null value. I also add some configuration in kernel.php but still, it is not working. please help.</p>

```<code>public function __construct()
{
    /** PayPal api context **/
    $this->middleware(function ($request, $next) {
        $paypal_conf = \Config::get('paypal');
        $orgId=Session::get('org_id');
        $org_credentials=PaypalCredentials::where('org_id','=',orgId)->first();
        $credentials=$org->paypalCredentials;
        $this->_api_context = new ApiContext(new OAuthTokenCredential(
            $credentials->client_id,
            $credentials->client_secret));
        $this->_api_context->setConfig($paypal_conf['settings']);

       return $next($request);
 });

}

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
</code>```

答:
```<code>    public function __construct()
    {
        /** PayPal api context **/
        $this->middleware(function ($request, $next) {
            $paypal_conf = \Config::get('paypal');
            $orgID = $this->getSession('org_id');

            $org_credentials=PaypalCredentials::where('org_id','=',orgId)->first();
            $credentials=$org->paypalCredentials;
            $this->_api_context = new ApiContext(new OAuthTokenCredential(
                $credentials->client_id,
                $credentials->client_secret));
            $this->_api_context->setConfig($paypal_conf['settings']);

           return $next($request);
     });

    }

private function getSession(){

            return \Session::get('org_id');

}
</code>```

Body:
I am stuck to the use of session value in __constructor but it shows null value. I also add some configuration in kernel.php but still, it is not working. please help.

public function __construct()
{
    /** PayPal api context **/
    $this->middleware(function ($request, $next) {
        $paypal_conf = \Config::get('paypal');
        $orgId=Session::get('org_id');
        $org_credentials=PaypalCredentials::where('org_id','=',orgId)->first();
        $credentials=$org->paypalCredentials;
        $this->_api_context = new ApiContext(new OAuthTokenCredential(
            $credentials->client_id,
            $credentials->client_secret));
        $this->_api_context->setConfig($paypal_conf['settings']);

       return $next($request);
 });

}

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];


问:
Java HTTP getResponseCode returns 200 for non-existent URL
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

```<code>    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }
</code>```

答:
try adding a "connection.connect();" or look at the contents returned...

it could be a dns issue, ie: your dns is being sent to a parking place... for example: freedns does this.

Body:
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }


问:
Sorting a tab delimited file
I have a data with the following format:

```<code>foo<tab>1.00<space>1.33<space>2.00<tab>3
</code>```

Now I tried to sort the file based on the last field decreasingly.
I tried the following commands but it wasn't sorted as we expected.

```<code>$ sort -k3nr file.txt  # apparently this sort by space as delimiter

$ sort -t"\t" -k3nr file.txt
  sort: multi-character tab `\\t'

$ sort -t "`/bin/echo '\t'`" -k3,3nr file.txt
  sort: multi-character tab `\\t'
</code>```

What's the right way to do it?

Here is the sample data.

答:
Lars Haugseth answer only worked from the command line for me where it gives this error if executed from a shell script:

sort: multi-character tab ‘$\t’

The solution if it's coded in a shell script if anyone's looking is

```<code>sort -t'    '
</code>```

the tab character is in between the quote.

Title: Sorting a tab delimited file

Body:
I have a data with the following format:

foo<tab>1.00<space>1.33<space>2.00<tab>3

Now I tried to sort the file based on the last field decreasingly.
I tried the following commands but it wasn't sorted as we expected.

$ sort -k3nr file.txt  # apparently this sort by space as delimiter

$ sort -t"\t" -k3nr file.txt
  sort: multi-character tab `\\t'

$ sort -t "`/bin/echo '\t'`" -k3,3nr file.txt
  sort: multi-character tab `\\t'

What's the right way to do it?

Here is the sample data.

Body:
Lars Haugseth answer only worked from the command line for me where it gives this error if executed from a shell script:

sort: multi-character tab ‘$\t’

The solution if it's coded in a shell script if anyone's looking is

sort -t'    '

the tab character is in between the quote.


问:
Joint Three Table and sum column value
bellow is my data

Order

```<code>ID         state
1           2
2           1
</code>```

OrderItem

```<code>orderID    item    qty  price
1           A       1     10
1           B       3     20
2           A       2     10
</code>```

OrderState

```<code>stateID    name
1          new
2          complete
</code>```

the view i'm after

```<code>Id    state     total_qty   Total_price
1     complete      4           70
2     new           2           20
</code>```

my query so far

```<code>   SELECT distinct O.Id, OS.name, SUM(OI.qty) as total_qty, SUM(OI.qty*OI.price) as Total_price
       FROM Order O
       join OrderItem OI ON O.ID = OI.ordeID
       join OrderState OS ON O.state = OS.StateID
       GROUP BY O.ID
</code>```

its keep back error about grouping can't think way to by pass it
Appreciate the help

答:
You need to group by all columns that you select and don't aggregate with functions like  sum()

```<code>SELECT o.id,
       os.name as state_name,
       SUM(oi.qty) as total_qty,
       SUM(oi.qty * oi.price) as total_price
FROM `order` o
JOIN OrderItem oi ON o.id = oi.orderID
JOIN OrderState os ON o.state = os.StateID
GROUP BY o.id, os.name
</code>```

Title: Joint Three Table and sum column value

Body:
bellow is my data

Order

ID         state
1           2
2           1

OrderItem

orderID    item    qty  price
1           A       1     10
1           B       3     20
2           A       2     10

OrderState

stateID    name
1          new
2          complete

the view i'm after

Id    state     total_qty   Total_price
1     complete      4           70
2     new           2           20

my query so far

   SELECT distinct O.Id, OS.name, SUM(OI.qty) as total_qty, SUM(OI.qty*OI.price) as Total_price
       FROM Order O
       join OrderItem OI ON O.ID = OI.ordeID
       join OrderState OS ON O.state = OS.StateID
       GROUP BY O.ID

its keep back error about grouping can't think way to by pass it
Appreciate the help

Body:
You need to group by all columns that you select and don't aggregate with functions like  sum()

SELECT o.id,
       os.name as state_name,
       SUM(oi.qty) as total_qty,
       SUM(oi.qty * oi.price) as total_price
FROM `order` o
JOIN OrderItem oi ON o.id = oi.orderID
JOIN OrderState os ON o.state = os.StateID
GROUP BY o.id, os.name


问:
How to give output of a java script variable in a button
I have a javascript variable "len" and I want its value in my button ,here is my button code :</p>

```<code><button type="button" class="btn btn-primary">
   Pending Task
   <span class="badge badge-light"></span>
   <span class="sr-only"></span>
</button>
</code>```

答:
In your case I suggest to add another  to make the text of your button addressable without changing the icons. So your button becomes

```<code><button type="button" class="btn btn-primary">
   <span class="content">Pending Task</span>
   <span class="badge badge-light"></span>
   <span class="sr-only"></span>
</button>
</code>```

Then in your JavaScript, you need a selector to address this new . Currently you button has no ID, so the following selector might also select other buttons. As you're already using bootstrap, you'll have jQuery available. That makes the code for setting the text rather short:

```<code> $( 'nav button .content' ).text( len );
</code>```

As you're just using vanilla JS right now, the above line could also be rewritten like this

```<code> document.querySelector( 'nav button .content' ).textContent = len;
</code>```

Body:
I have a javascript variable "len" and I want its value in my button ,here is my button code :

<button type="button" class="btn btn-primary">
   Pending Task

</button>

Body:
In your case I suggest to add another <span> to make the text of your button addressable without changing the icons. So your button becomes

<button type="button" class="btn btn-primary">
   <span class="content">Pending Task</span>
   <span class="badge badge-light"></span>
   <span class="sr-only"></span>
</button>

Then in your JavaScript, you need a selector to address this new <span>. Currently you button has no ID, so the following selector might also select other buttons. As you're already using bootstrap, you'll have jQuery available. That makes the code for setting the text rather short:

 $( 'nav button .content' ).text( len );

As you're just using vanilla JS right now, the above line could also be rewritten like this

 document.querySelector( 'nav button .content' ).textContent = len;


问:
How to get tfidf with pandas dataframe?
I want to calculate tf-idf from the documents below. I'm using python and pandas.

```<code>import pandas as pd
df = pd.DataFrame({'docId': [1,2,3],
               'sent': ['This is the first sentence','This is the second sentence', 'This is the third sentence']})
</code>```

First, I thought I would need to get word_count for each row. So I wrote a simple function:

```<code>def word_count(sent):
    word2cnt = dict()
    for word in sent.split():
        if word in word2cnt: word2cnt[word] += 1
        else: word2cnt[word] = 1
return word2cnt
</code>```

And then, I applied it to each row.

```<code>df['word_count'] = df['sent'].apply(word_count)
</code>```

But now I'm lost. I know there's an easy method to calculate tf-idf if I use Graphlab, but I want to stick with an open source option. Both Sklearn and gensim look overwhelming. What's the simplest solution to get tf-idf?

答:
I found a slightly different method using CountVectorizer from sklearn.
--count vectorizer: Ultraviolet Analysis word frequency
--preprocessing/cleaning text: Usman Malik scraping tweets preprocessing
I won't be covering preprocessing in this answer. Basically what you want to do is import CountVectorizer and fit your data to the CountVectorizer object, which will let you access the .vocabulary._items() feature, which will give you the vocabulary of your dataset (the unique words present and their frequencies, given any limiting parameters you pass into CountVectorizer like match feature number, etc)

Then, you're going to use the Tfidtransformer to generate tf-idf weights for the terms in a similar manner

I am coding in a jupyter notebook file using pandas and the pycharm ide

Here is a code snippet:

```<code>from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np
#https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
countVec = CountVectorizer(max_features= 5000, stop_words='english', min_df=.01, max_df=.90)

#%%
#use CountVectorizer.fit(self, raw_documents[, y] to learn vocabulary dictionary of all tokens in raw documents
#raw documents in this case will betweetsFrameWords["Text"] (processed text)
countVec.fit(tweetsFrameWords["Text"])
#useful debug, get an idea of the item list you generated
list(countVec.vocabulary_.items())

#%%
#convert to bag of words
#sparse matrix representation? (README: could use an edit/explanation)
countVec_count = countVec.transform(tweetsFrameWords["Text"])

#%%
#make array from number of occurrences
occ = np.asarray(countVec_count.sum(axis=0)).ravel().tolist()

#make a new data frame with columns term and occurrences, meaning word and number of occurences
bowListFrame = pd.DataFrame({'term': countVec.get_feature_names(), 'occurrences': occ})
print(bowListFrame)

#sort in order of number of word occurences, most->least. if you leave of ascending flag should default ASC
bowListFrame.sort_values(by='occurrences', ascending=False).head(60)

#%%
#now, convert to a more useful ranking system, tf-idf weights
#TfidfTransformer: scale raw word counts to a weighted ranking using the
#https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html
tweetTransformer = TfidfTransformer()

#initial fit representation using transformer object
tweetWeights = tweetTransformer.fit_transform(countVec_count)

#follow similar process to making new data frame with word occurrences, but with term weights
tweetWeightsFin = np.asarray(tweetWeights.mean(axis=0)).ravel().tolist()

#now that we've done Tfid, make a dataframe with weights and names
tweetWeightFrame = pd.DataFrame({'term': countVec.get_feature_names(), 'weight': tweetWeightsFin})
print(tweetWeightFrame)
tweetWeightFrame.sort_values(by='weight', ascending=False).head(20)
</code>```

Title: How to get tfidf with pandas dataframe?

Body:
I want to calculate tf-idf from the documents below. I'm using python and pandas.

import pandas as pd
df = pd.DataFrame({'docId': [1,2,3],
               'sent': ['This is the first sentence','This is the second sentence', 'This is the third sentence']})

First, I thought I would need to get word_count for each row. So I wrote a simple function:

def word_count(sent):
    word2cnt = dict()
    for word in sent.split():
        if word in word2cnt: word2cnt[word] += 1
        else: word2cnt[word] = 1
return word2cnt

And then, I applied it to each row.

df['word_count'] = df['sent'].apply(word_count)

But now I'm lost. I know there's an easy method to calculate tf-idf if I use Graphlab, but I want to stick with an open source option. Both Sklearn and gensim look overwhelming. What's the simplest solution to get tf-idf?

Body:
I found a slightly different method using CountVectorizer from sklearn.
--count vectorizer: Ultraviolet Analysis word frequency
--preprocessing/cleaning text: Usman Malik scraping tweets preprocessing
I won't be covering preprocessing in this answer. Basically what you want to do is import CountVectorizer and fit your data to the CountVectorizer object, which will let you access the .vocabulary._items() feature, which will give you the vocabulary of your dataset (the unique words present and their frequencies, given any limiting parameters you pass into CountVectorizer like match feature number, etc)

Then, you're going to use the Tfidtransformer to generate tf-idf weights for the terms in a similar manner

I am coding in a jupyter notebook file using pandas and the pycharm ide

Here is a code snippet:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np
#https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
countVec = CountVectorizer(max_features= 5000, stop_words='english', min_df=.01, max_df=.90)

#%%
#use CountVectorizer.fit(self, raw_documents[, y] to learn vocabulary dictionary of all tokens in raw documents
#raw documents in this case will betweetsFrameWords["Text"] (processed text)
countVec.fit(tweetsFrameWords["Text"])
#useful debug, get an idea of the item list you generated
list(countVec.vocabulary_.items())

#%%
#convert to bag of words
#sparse matrix representation? (README: could use an edit/explanation)
countVec_count = countVec.transform(tweetsFrameWords["Text"])

#%%
#make array from number of occurrences
occ = np.asarray(countVec_count.sum(axis=0)).ravel().tolist()

#make a new data frame with columns term and occurrences, meaning word and number of occurences
bowListFrame = pd.DataFrame({'term': countVec.get_feature_names(), 'occurrences': occ})
print(bowListFrame)

#sort in order of number of word occurences, most->least. if you leave of ascending flag should default ASC
bowListFrame.sort_values(by='occurrences', ascending=False).head(60)

#%%
#now, convert to a more useful ranking system, tf-idf weights
#TfidfTransformer: scale raw word counts to a weighted ranking using the
#https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html
tweetTransformer = TfidfTransformer()

#initial fit representation using transformer object
tweetWeights = tweetTransformer.fit_transform(countVec_count)

#follow similar process to making new data frame with word occurrences, but with term weights
tweetWeightsFin = np.asarray(tweetWeights.mean(axis=0)).ravel().tolist()

#now that we've done Tfid, make a dataframe with weights and names
tweetWeightFrame = pd.DataFrame({'term': countVec.get_feature_names(), 'weight': tweetWeightsFin})
print(tweetWeightFrame)
tweetWeightFrame.sort_values(by='weight', ascending=False).head(20)


问:
Toggle class on buttons in Svelte
Consider this Svelte code

```<code>{#each filters as filters, i}
   <div class='filter-container'>
      <div class='button filter' on:click={ () => setFilter(filters.name, filterContext)}>{filters.name}</div>
   </div>
{/each}
</code>```

The above filter buttons are made depending on how many filters there are in some js object. How can I create a class that is toggled for all filter buttons when the one button is clicked.

eg. when one is active all the others are not?

答:
We can easily bind class names to expressions, so that the class will be added if the expression becomes truthy:

```<code><script>
    let isActive = false
</script>

<style>
    .active {
        color: red;
    }
</style>

<h1 class:active={isActive}>Hello!</h1>
<button on:click={() => isActive = !isActive}>Click me</button>
</code>```

Here, clicking the button toggles the isActive boolean. The class active is bound to that variable on the h1 element and you can see that the color now changes on every button click.

That is the standard way on how to set single classes dynamically.

REPL: https://svelte.dev/repl/988df145876a42c49bb8de51d2cae0f2?version=3.23.0

Title: Toggle class on buttons in Svelte

Body:
Consider this Svelte code

{#each filters as filters, i}

 setFilter(filters.name, filterContext)}>{filters.name}

{/each}

The above filter buttons are made depending on how many filters there are in some js object. How can I create a class that is toggled for all filter buttons when the one button is clicked.

eg. when one is active all the others are not?

Body:
We can easily bind class names to expressions, so that the class will be added if the expression becomes truthy:

<script>
    let isActive = false
</script>

<style>
    .active {
        color: red;
    }
</style>

<h1 class:active={isActive}>Hello!</h1>
<button on:click={() => isActive = !isActive}>Click me</button>

Here, clicking the button toggles the isActive boolean. The class active is bound to that variable on the h1 element and you can see that the color now changes on every button click.

That is the standard way on how to set single classes dynamically.

REPL: https://svelte.dev/repl/988df145876a42c49bb8de51d2cae0f2?version=3.23.0


问:
Conditional if else list data in react
I have json data and I have on the list. Here I want to use an empty data approval condition.

But I have not succeeded:

```<code>   componentDidMount(){
        this.getJson();
    }

 getJson= () => {

        const url = `https://example.com/priceon?ori=${a}&des=${b}`
        fetch(url)
          ....
    };

render() {
    //here I make a condition if the data exists and does not exist
    if (this.state.results == '') {
        return(
        <View>
            <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
        </View>
        );
    } else {
        return (
        <Container style={styles.container}>
                    <List
                        keyExtractor = {(item, index)=> index.toString()}
                        dataArray={this.state.results}
                        renderRow={(results) =>
                        <ListItem>
                            <Body>
                                <CardItem>
                                    <Text>{results.tipe} - {results.service}</Text>
                                </CardItem>
                            </Body>
                        </ListItem>
                    }>

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

How to make the right conditions?

If the data exists then it appears, if it is empty then display  null data

答:
If the API call returns as an array then you can do this.state.results.length check maybe with additional null check.

Try as the following:

```<code>render() {
   <>
      {
          this.state.results && this.state.results.length ?
             <Container style={styles.container}>
                 { /* your code */ }
             </Container>
          :
             <View>
                 <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
             </View>
      }
   </>
</code>```

Read further about Conditional Rendering. Especially the Inline If with Logical && Operator section.

Title: Conditional if else list data in react

Body:
I have json data and I have on the list. Here I want to use an empty data approval condition.

But I have not succeeded:

   componentDidMount(){
        this.getJson();
    }

 getJson= () => {

        const url = `https://example.com/priceon?ori=${a}&des=${b}`
        fetch(url)
          ....
    };

render() {
    //here I make a condition if the data exists and does not exist
    if (this.state.results == '') {
        return(
        <View>
            <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
        </View>
        );
    } else {
        return (
        <Container style={styles.container}>
                    <List
                        keyExtractor = {(item, index)=> index.toString()}
                        dataArray={this.state.results}
                        renderRow={(results) =>
                        <ListItem>

                                <CardItem>
                                    <Text>{results.tipe} - {results.service}</Text>
                                </CardItem>

                        </ListItem>
                    }>

      </Container>
    );
      }
    }

How to make the right conditions?

If the data exists then it appears, if it is empty then display  null data

Body:
If the API call returns as an array then you can do this.state.results.length check maybe with additional null check.

Try as the following:

render() {
   <>
      {
          this.state.results && this.state.results.length ?
             <Container style={styles.container}>
                 { /* your code */ }
             </Container>
          :
             <View>
                 <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
             </View>
      }
   </>

Read further about Conditional Rendering. Especially the Inline If with Logical && Operator section.


问:
What is the appropriate replacement of deprecated getSupportLoaderManager()?
I came to know that getSupportLoaderManager is deprecated. But I want to call:

```<code>getSupportLoaderManager().initLoader(0, null, mRecipeLoaderManager);
</code>```

What should be an alternative to that call?
Or can I still use getSupportLoaderManager without worrying?

答:
Same problem occurred with me!

getSupportLoaderManger() can be replaced by LoaderManager.getInstance(this) and the further code remains the same. So, finally your code will become:

```<code>LoaderManager.getInstance(this).initLoader(0, null, mRecipeLoaderManager);
</code>```

You can refer Android official documentation:
https://developer.android.com/reference/androidx/fragment/app/FragmentActivity#getSupportLoaderManager()

Body:
I came to know that getSupportLoaderManager is deprecated. But I want to call:

getSupportLoaderManager().initLoader(0, null, mRecipeLoaderManager);

What should be an alternative to that call?
Or can I still use getSupportLoaderManager without worrying?

Body:
Same problem occurred with me!

getSupportLoaderManger() can be replaced by LoaderManager.getInstance(this) and the further code remains the same. So, finally your code will become:

LoaderManager.getInstance(this).initLoader(0, null, mRecipeLoaderManager);

You can refer Android official documentation:
https://developer.android.com/reference/androidx/fragment/app/FragmentActivity#getSupportLoaderManager()


问:
How do I append a JSON file?
How would I append a JSON file? I know how to append a JSON variable, but how do I append a file? for example, if my JSON file was:

```<code>{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}
</code>```

If I wanted to add another name to people, and that was in a JSON file, how would I do that?

答:
You can try

```<code>with open("json_exp.txt", "r+") as f:
         json_obj = json.loads(f.read())
         json_obj["people"].append({"name":"new_person"})
         f.seek(0)
         json.dump(json_obj, f)
</code>```

This code will read a text file that have a JSON object in it and will append a new value to the dict that made by the JSON object in the file then it will store the new JSON object to the file.

Title: How do I append a JSON file?

Body:
How would I append a JSON file? I know how to append a JSON variable, but how do I append a file? for example, if my JSON file was:

{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}

If I wanted to add another name to people, and that was in a JSON file, how would I do that?

Body:
You can try

with open("json_exp.txt", "r+") as f:
         json_obj = json.loads(f.read())
         json_obj["people"].append({"name":"new_person"})
         f.seek(0)
         json.dump(json_obj, f)

This code will read a text file that have a JSON object in it and will append a new value to the dict that made by the JSON object in the file then it will store the new JSON object to the file.


问:
Java dynamically create buttons and pass a parameter to action performed
I am new to java and i am trying a small project on my own, i want to list the first and lastname of users from a sql database (this all works fine, but i don't just want to list them

I want to list all users in a GUI with a delete button, naturally this delete button will be generated dynamically and i want to pass the userID of the button to the action performed.
like this:

```<code> John      Doe      'Delete button'
 Jane      Doe      'Delete button'
</code>```

In my code below i just generate 16 buttons dynamically (without a users table) instead of passing the userID i am trying to pass the 'i' value of the for loop, but my code does not seem to work

CODE

    public class UsersView implements ActionListener {

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    public UsersView() {

        //Create the 16 buttons.
        for (int i=0; i<16; i++) {
            Button button = new Button("Click "+i);
            button.setId(i);  //this gives me and error 'Symbol not find' on the 'setId'
            panel.add(button);
            button.addActionListener(this);
        }

        panel.setBorder(BorderFactory.createBevelBorder(0, Color.lightGray, Color.yellow));
        //panel.setBorder(BorderFactory.createEmptyBorder(300, 300, 100, 300));
        panel.setLayout(new GridLayout(4,4)); //Rows Cols

        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("App GUI");
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        // TODO code application logic here
        new UsersView();
    }

    //On button click.
    @Override
    public void actionPerformed(ActionEvent e) {
        //I know i have nothing here (yet) that is because the 'setId' gives me an error.

    }

}
```

答:
One of the issues you're having is creating a monolithic action listener, and then expecting to delegate actions from that. One nice feature of java are anonymous classes, or since java 7 lambdas.

```<code>JButton button = new JButton("Click " + i);
panel.add(button);
int id = i;
button.addActionListener( evt->{
    performActionOnId( id );
});
</code>```

Now instead of having the main class be an action listener, the main class has methods that are descriptive.

```<code>public void addUser( User a ){
    //just showing delete button.

    JButton delete = new JButton("X");
    delete.addActionListener( evt ->{
        removeUser( a );
        //clean up gui.
    });
}
</code>```

This puts some of the steps of delegation at the creation of the user. Otherwise you'll have to delegate in your action performed.

```<code>public void actionPerformed( ActionEvent evt ){
    //has to be a new class to have id attribute.
    CustomButton b = (CustomButton)evt.getSource();
    int id = b.getId();
    User u = getUserById(id);
    removeUser(u);
}
</code>```

Body:
I am new to java and i am trying a small project on my own, i want to list the first and lastname of users from a sql database (this all works fine, but i don't just want to list them

I want to list all users in a GUI with a delete button, naturally this delete button will be generated dynamically and i want to pass the userID of the button to the action performed.
like this:

 John      Doe      'Delete button'
 Jane      Doe      'Delete button'

In my code below i just generate 16 buttons dynamically (without a users table) instead of passing the userID i am trying to pass the 'i' value of the for loop, but my code does not seem to work

CODE

    public class UsersView implements ActionListener {

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    public UsersView() {

        //Create the 16 buttons.
        for (int i=0; i<16; i++) {
            Button button = new Button("Click "+i);
            button.setId(i);  //this gives me and error 'Symbol not find' on the 'setId'
            panel.add(button);
            button.addActionListener(this);
        }

        panel.setBorder(BorderFactory.createBevelBorder(0, Color.lightGray, Color.yellow));
        //panel.setBorder(BorderFactory.createEmptyBorder(300, 300, 100, 300));
        panel.setLayout(new GridLayout(4,4)); //Rows Cols

        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("App GUI");
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        // TODO code application logic here
        new UsersView();
    }

    //On button click.
    @Override
    public void actionPerformed(ActionEvent e) {
        //I know i have nothing here (yet) that is because the 'setId' gives me an error.

    }

}

Body:
One of the issues you're having is creating a monolithic action listener, and then expecting to delegate actions from that. One nice feature of java are anonymous classes, or since java 7 lambdas.

JButton button = new JButton("Click " + i);
panel.add(button);
int id = i;
button.addActionListener( evt->{
    performActionOnId( id );
});

Now instead of having the main class be an action listener, the main class has methods that are descriptive.

public void addUser( User a ){
    //just showing delete button.

    JButton delete = new JButton("X");
    delete.addActionListener( evt ->{
        removeUser( a );
        //clean up gui.
    });
}

This puts some of the steps of delegation at the creation of the user. Otherwise you'll have to delegate in your action performed.

public void actionPerformed( ActionEvent evt ){
    //has to be a new class to have id attribute.
    CustomButton b = (CustomButton)evt.getSource();
    int id = b.getId();
    User u = getUserById(id);
    removeUser(u);
}


问:
SharedPreferences - java.lang.Boolean cannot be cast to java.lang.String
I'm confused with an exception that is thrown for something that shouldn't.
The error is the following:

```<code>java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
</code>```

But, my code doesn't try to cast a Boolean to String Ô_o
Is it possible that the compiler is wrong in indicating where the exception is coming from? I'm using an Huawei

This part triggers the exception:

```<code>if(SharedPreferencesManager.getUserMRZ(ScanEUID.this).equals("0")
&& SharedPreferencesManager.getUserDocumentIdFront(ScanEUID.this) != null
&& SharedPreferencesManager.getUserDocumentIdBack(ScanEUID.this) != null)
{
</code>```

The associated methods are the following

```<code>public static String getUserMRZ(Context context){
    return getSharedPreferences(context).getString(Constants.USER_HAS_MRZ, "0");
}
public static String getUserDocumentIdFront(Context context) {
    return getSharedPreferences(context).getString(Constants.USER_DOCUMENT_ID_FRONT, null);
}
public static String getUserDocumentIdBack(Context context) {
    return getSharedPreferences(context).getString(Constants.USER_DOCUMENT_ID_BACK, null);
}
</code>```

The setMRZ method

```<code>public static void setUserMRZ(Context context, String has_mrz){
        final SharedPreferences.Editor editor = getSharedPreferences(context).edit();
        editor.putString(Constants.USER_HAS_MRZ, has_mrz);
        editor.apply();
}
</code>```

答: In my case, I just surround the get methods with Try Catch and it works!</p>

Body:
I'm confused with an exception that is thrown for something that shouldn't.
The error is the following:

java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String

But, my code doesn't try to cast a Boolean to String Ô_o
Is it possible that the compiler is wrong in indicating where the exception is coming from? I'm using an Huawei

This part triggers the exception:

if(SharedPreferencesManager.getUserMRZ(ScanEUID.this).equals("0")
&& SharedPreferencesManager.getUserDocumentIdFront(ScanEUID.this) != null
&& SharedPreferencesManager.getUserDocumentIdBack(ScanEUID.this) != null)
{

The associated methods are the following

public static String getUserMRZ(Context context){
    return getSharedPreferences(context).getString(Constants.USER_HAS_MRZ, "0");
}
public static String getUserDocumentIdFront(Context context) {
    return getSharedPreferences(context).getString(Constants.USER_DOCUMENT_ID_FRONT, null);
}
public static String getUserDocumentIdBack(Context context) {
    return getSharedPreferences(context).getString(Constants.USER_DOCUMENT_ID_BACK, null);
}

The setMRZ method

public static void setUserMRZ(Context context, String has_mrz){
        final SharedPreferences.Editor editor = getSharedPreferences(context).edit();
        editor.putString(Constants.USER_HAS_MRZ, has_mrz);
        editor.apply();
}