问:
Spring WS produces notification instead of request-response
I've been attempting to create a port of an existing JAX-WS Web Service in Spring, using Spring WebService (following their guide loosely at https://spring.io/guides/gs/producing-web-service/).

I've got an endpoint working, using both the XSD the existing application (with JAX-WS) uses, and by generating a new set with SoapUI.

For some reason, the Web Service seems to be publishing with the Type of 'Notification', rather than 'Request-Response' like the original, existing methods on the pre-existing JAX-WS endpoint.  The Spring WS also has an 'Output' with a Response-suffixed class stated, where the JAX-WS one does not.  This is visually different in SoapUI with the Spring wsdl having a red 'left arrow' next to each method, instead of the contraflow arrows.

I think this is manifesting itself as an issue I'm seeing when I call the one endpoint I have set up - an error is logged stating 'No endpoint mapping found for [SaajSoapMessage .... myEndpointMethodResponse" (e.g. the response object from the endpoint method, not the endpoint method itself).

As mentioned, I feel like the 'Type' on the methods is the smoking gun, but I can't see what is causing it.  I have looked up the issue but can't find anything common?

Update The following helped with the request-response (Invalid wsdl generated by spring-ws when the request element doesn't end with 'Request'), but I'm now getting a response back in SOAPUI of 'No adapter for endpoint' referencing my Response class.  The PayloadRoot and ResponsePayload match the wsdl objects exactly.

答:
OK, as the only 'help' on here was a close vote (thanks, very helpful), I've managed this myself now and will post the solution. There were two parts:

As per the 'update' in the question, the Request methods in the XSD were named after the method, and weren't suffixed 'Request'.  This meant that I had to make a custom WSDL11Definition class that would allow the setRequestSuffix to be null (empty).  The question link has more details.

The objects on the method needed to be wrapped in JAXBElement<> in order to recognise the input and output successfully.

One all the above had been done, my breakpoint was hit in my IDE using SOAPUI.


来源: stackexchange

问:
Azure Vnet Private IP Ranges
I've not from a networking background. I'm data platform solution architecture and data/ai engineer. Since distributed data processing and scale out using containers has come into my world I've decided to bite the bullet and learn IP fundamentals so I can build clusters.

I've been doing lots of training but have a simple and relatively dumb question but finding simple answers to simple questions seems quite hard on the topic networking!

I have 2 Azure VNets for example in my subscription on the same domain does it matter if a subnet on 1 vnet overlaps a subnet on other vnet? Presumably that would only be a problem when they're peered together. Does the vnet ring fence it's private ip ranges?

答: no, its doesn't. But you won't be able to peer\vpn them together. So they are effectively isolated from each other forever (or at least until you fix that).</p>

ContentLicense: CC BY-SA 4.0

Title: Azure Vnet Private IP Ranges


问:
Request aborted when trying to post data from vue js to laravel backend
I have been struggling with an issue for like the whole day now. Every time I want to post data to my laravel back end from my vue js component, it says that the request has been aborted. I really can't see what's wrong with my code. Any help is greatly appreciated. I have CORS installed so that' not the problem. I have tried to clear the route cache and that didn't work either.

Controller store method. Here is where I make a check whether the title exists and if not, proceed to save the story in the database:

```<code>public function store(
    AuthenticatedUserId $authenticatedUserId,
    CreateNewRecordInDatabase $createNewRecordInDatabase,
    FindDataById $findDataById,
    RetrieveAllData $retrieveAllData,
    Request $request,
    $writer
    )
{
    $writer = $findDataById->findDataById(User::class, $writer);

    $stories = $retrieveAllData->retrieveAllData(Story::class);

    foreach ($stories as $check_title) {
        if ($check_title->title == $request->title) {
            return redirect()
                ->route('writer.create', ['writer' => $authenticatedUserId->authId()])
                ->with('title_exists', 'Title already exists');
        }
    }

    $createNewRecordInDatabase->createRecord($writer->stories(), [
        'title' => $request->title,
        'story' => $request->story,
        'published_on' => date('m-d-Y'),
        'category_id' => $request->category_id
    ]);

    return response()->json('success');
}
</code>```

API route:

```<code>Route::post('/dashboard/writer/{writer}/store', 'Story\StoryController@store');
</code>```

Vue component:

```<code><template>
<div class="row">
    <form class="col s12">
        <input type="hidden" name="_token" :value="csrf">

        <div class="row">
            <div class="col s12">
                <input  v-model="title" type="text"
                        class="input-field"
                        placeholder="Give it a catchy title"
                        required
                        >
                <label for="title">Give it a catchy title</label>
            </div>
        </div>

        <div class="row">
            <div class="input-field col s12">
                <select v-model="category_id" name="category_id">
                     <option
                        v-for="category in categories"
                        v-bind:key="category.id"
                        v-bind:value="category.id"
                        >{{ category.category }}
                     </option>
                </select>
            </div>
        </div>

        <div class="white col s12" id="editorjs"></div>

        <div class="col s12">
            <button @click="publishStory" class="btn waves-effect waves-light">Publish</button>
        </div>
    </form>

</div>
</code>```

```<code><script>

import EditorJS from '@editorjs/editorjs';
import Header from '@editorjs/header';
import Link from '@editorjs/link';
import List from '@editorjs/list';
import Quote from '@editorjs/quote';

export default {
    props: ['categories', 'writer'],
    data() {
        return  {
            title: null,
            category_id: null,
            story: [],
            editor: new EditorJS({
                tools: {
                    header: {
                        class: Header,
                        inlineToolbar: true
                    },
                    list: {
                        class: List,
                        inlineToolbar: true
                    },
                    link: {
                        class: Link,
                        inlineToolbar: true
                    },
                    quote: {
                        class: Quote,
                        inlineToolbar: true
                    }
                }
            }),
            csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    },
    methods: {
        publishStory() {
            this.editor.save()
            .then(outputData => this.story = outputData.blocks)
            .catch(err => console.log(err))
            axios.post(`http://localhost:8000/api/dashboard/writer/${this.writer}/store`, {
                    title: this.title,
                    story: this.story,
                    category_id: this.category_id,
                })
                .then(res => console.log(res))
                .catch(err => console.log(err))
        }

    },
    mounted() {}
}
</script>
</code>```

答:
Try to increase php.ini settings

```<code>max_input_time
upload_max_filesize
post_max_size
memory_limit
max_input_vars
</code>```

PHP Truncating POST Data

Body:
I have been struggling with an issue for like the whole day now. Every time I want to post data to my laravel back end from my vue js component, it says that the request has been aborted. I really can't see what's wrong with my code. Any help is greatly appreciated. I have CORS installed so that' not the problem. I have tried to clear the route cache and that didn't work either.

Controller store method. Here is where I make a check whether the title exists and if not, proceed to save the story in the database:

public function store(
    AuthenticatedUserId $authenticatedUserId,
    CreateNewRecordInDatabase $createNewRecordInDatabase,
    FindDataById $findDataById,
    RetrieveAllData $retrieveAllData,
    Request $request,
    $writer
    )
{
    $writer = $findDataById->findDataById(User::class, $writer);

    $stories = $retrieveAllData->retrieveAllData(Story::class);

    foreach ($stories as $check_title) {
        if ($check_title->title == $request->title) {
            return redirect()
                ->route('writer.create', ['writer' => $authenticatedUserId->authId()])
                ->with('title_exists', 'Title already exists');
        }
    }

    $createNewRecordInDatabase->createRecord($writer->stories(), [
        'title' => $request->title,
        'story' => $request->story,
        'published_on' => date('m-d-Y'),
        'category_id' => $request->category_id
    ]);

    return response()->json('success');
}

API route:

Route::post('/dashboard/writer/{writer}/store', 'Story\StoryController@store');

Vue component:

<template>

    <form class="col s12">
        <input type="hidden" name="_token" :value="csrf">

                <input  v-model="title" type="text"
                        class="input-field"
                        placeholder="Give it a catchy title"
                        required
                        >
                Give it a catchy title

                <select v-model="category_id" name="category_id">
                     <option
                        v-for="category in categories"
                        v-bind:key="category.id"
                        v-bind:value="category.id"
                        >{{ category.category }}
                     </option>
                </select>

            <button @click="publishStory" class="btn waves-effect waves-light">Publish</button>

    </form>

Body:
Try to increase php.ini settings

max_input_time
upload_max_filesize
post_max_size
memory_limit
max_input_vars

PHP Truncating POST Data


问:
Parsing XML files that do not have 'root' node in Python
My client wants me to parse over 100,00 xml files and converting them into a text file.

I have successfully parse a couple of files and converting them into a text file. However I managed to do that by editing the xml and adding <root></root> in the xml file.

This would seem inefficient since I would have to edit nearly 100,00 xml files to achieve my desired result.

Is there anyway for my python code to recognize the first node and read it as the root node?

I have tried using the method showed in Python XML Parsing without root
,however I do not fully understand it and I do not know where to implement this.

The XML format is as follows:

```<code><Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
        <UserID></UserID>
        <Date></Date>
        <icontent></icontent>
  </InitPost>
  <Post>
       <UserID></UserID>
       <Date></Date>
       <rcontent></rcontent>
  </Post>
</Thread>
</code>```

And this is my code on how to parse the XML files:

```<code>import os
from xml.etree import ElementTree

saveFile = open('test3.txt','w')

for path, dirs, files in os.walk("data/sample"):
   for f in files:
    fileName = os.path.join(path, f)
    with open(fileName, "r", encoding="utf8") as myFile:
        dom = ElementTree.parse(myFile)

        thread = dom.findall('Thread')

        for t in thread:

            threadID = str(t.find('ThreadID').text)
            threadID = threadID.strip()

            title = str(t.find('Title').text)
            title = title.strip()

            userID = str(t.find('InitPost/UserID').text)
            userID = userID.strip()

            date = str(t.find('InitPost/Date').text)
            date = date.strip()

            initPost = str(t.find('InitPost/icontent').text)
            initPost = initPost.strip()

        post = dom.findall('Thread/Post')
</code>```

The rest of the code is just writing to the output text file.

答:
Not sure about Python, but generally speaking you can use SGML to infer missing tags, whether at the document element (root) level or elsewhere. The basic technique is creating a DTD for declaring the document element like so

```<code><!DOCTYPE root [
  <!ELEMENT root O O ANY>
]>
<!-- your document character data goes here -->
</code>```

where the important things are the O O (letter O) tag omission indicators telling SGML that both the start- and end-element tags for root can be omitted.

See also the following questions with more details:

Querying Non-XML compliant structured data

Adding missing XML closing tags in Javascript

Body:
My client wants me to parse over 100,00 xml files and converting them into a text file.

I have successfully parse a couple of files and converting them into a text file. However I managed to do that by editing the xml and adding <root></root> in the xml file.

This would seem inefficient since I would have to edit nearly 100,00 xml files to achieve my desired result.

Is there anyway for my python code to recognize the first node and read it as the root node?

I have tried using the method showed in Python XML Parsing without root
,however I do not fully understand it and I do not know where to implement this.

The XML format is as follows:

<Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
        <UserID></UserID>
        <Date></Date>
        <icontent></icontent>
  </InitPost>
  <Post>
       <UserID></UserID>
       <Date></Date>
       <rcontent></rcontent>
  </Post>
</Thread>

And this is my code on how to parse the XML files:

import os
from xml.etree import ElementTree

saveFile = open('test3.txt','w')

for path, dirs, files in os.walk("data/sample"):
   for f in files:
    fileName = os.path.join(path, f)
    with open(fileName, "r", encoding="utf8") as myFile:
        dom = ElementTree.parse(myFile)

        thread = dom.findall('Thread')

        for t in thread:

            threadID = str(t.find('ThreadID').text)
            threadID = threadID.strip()

            title = str(t.find('Title').text)
            title = title.strip()

            userID = str(t.find('InitPost/UserID').text)
            userID = userID.strip()

            date = str(t.find('InitPost/Date').text)
            date = date.strip()

            initPost = str(t.find('InitPost/icontent').text)
            initPost = initPost.strip()

        post = dom.findall('Thread/Post')

The rest of the code is just writing to the output text file.

Body:
Not sure about Python, but generally speaking you can use SGML to infer missing tags, whether at the document element (root) level or elsewhere. The basic technique is creating a DTD for declaring the document element like so

<!DOCTYPE root [
  <!ELEMENT root O O ANY>
]>
<!-- your document character data goes here -->

where the important things are the O O (letter O) tag omission indicators telling SGML that both the start- and end-element tags for root can be omitted.

See also the following questions with more details:

Querying Non-XML compliant structured data

Adding missing XML closing tags in Javascript


问:
How to read PSD format image by Java?
I am developing a java swing based application which show thumbnail of any format(jpg,png) images. For that, at first I read the image file by ImageIO.read(file name) and then create thumbnail of it. But it shows null pointer exception when read PSD format file.

I use ideli library for read PSD type file but it requires subcription/paid. So there have any free library to read PSD type file in Java?

```<code>image = ImageIO.read(new File(i));
thumb = Thumbnails.of(image).size(140,100).outputFormat("png").asBufferedImage();
ImageIO.write(thumb, "png", new File("thumb.png"));
</code>```

By above code, I can read (without PSD) image file and create thumbnail  of image.

答:
Have a read of the documentation, PSD is not a supported format.

You might find some value from a similar question here.

Title: How to read PSD format image by Java?

Body:
I am developing a java swing based application which show thumbnail of any format(jpg,png) images. For that, at first I read the image file by ImageIO.read(file name) and then create thumbnail of it. But it shows null pointer exception when read PSD format file.

I use ideli library for read PSD type file but it requires subcription/paid. So there have any free library to read PSD type file in Java?

image = ImageIO.read(new File(i));
thumb = Thumbnails.of(image).size(140,100).outputFormat("png").asBufferedImage();
ImageIO.write(thumb, "png", new File("thumb.png"));

By above code, I can read (without PSD) image file and create thumbnail  of image.


问:
How would you design a good search UI?
I want to provide my users with an 'advanced' search engine.
I basically have a lot of search criteria to chose from :

some are very simple/common and will be largely use (ie time period, item id)

some are a bit less mainstream

and some won't be used a lot, but I still want to provide them

Overall, I have around 30+ criteria to chose from

The result is a dataset which I display in a grid.

I've search for inspiration on internet, and even google doesn't seem to have a nice solution for advanced search.

I've designed this kind of tools in the past, and I wasn't really pleased by the result, although the user were eventually able to use it quite effectively.

Do you think the search panel should be visible all the time (ie displayed on top of my result grid) or available in a separate form (which would let me use more place for all the controls)

Do you think it's better to display all the search criteria, or to let the user click on 'advanced' if he wants to see/use more criteria

How would you organize the criteria? by usage frequency, or rather by area (ie. criteria related to user, to location, to time, etc.)

Where should I put the 'Search' button? next to the more common search controls, or at the bottom, or both?

And more generally, do you have tips you want to share on how to design a nice search UI ?
What kind of functionalities do you usually miss in this kind of 'advanced' search engines?

答: The default design pattern which I use is Filter Table. That covers maybe 90% of the use cases. For more complex searches, I would need more specific information on the goals and use cases of the users, so that it would be possible to design a more optimal solution for those situations.</p>

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

Title: How would you design a good search UI?

LastEditorDisplayName: onnodb

OwnerDisplayName: Esko Luontola


问:
SELECT all (but one column as null)
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

```<code>SELECT *, id AS (SELECT '') FROM my_table WHERE 1
</code>```

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

答:
What about

```<code>SELECT *, NULL AS id FROM my_table
</code>```

You'd get id listed twice, so you need to expand the * to all the column names, for each table you want this to run on.

(If you want column names to be extracted automatically, you can probably use vendor-specific functions; I can't remember if MySQL has any for this situation).

ContentLicense: CC BY-SA 3.0

Title: SELECT all (but one column as null)

Body:
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

SELECT *, id AS (SELECT '') FROM my_table WHERE 1

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

Body:
What about

SELECT *, NULL AS id FROM my_table

You'd get id listed twice, so you need to expand the * to all the column names, for each table you want this to run on.

(If you want column names to be extracted automatically, you can probably use vendor-specific functions; I can't remember if MySQL has any for this situation).


问:
How to print SQL statement in codeigniter model
I have a sql statement in my model,

I then say

```<code>$query = $this->db->query($sql, array(fields, fields1);

if ($query) {
    return true:
} else {
    echo "failed";
    return false;
}
</code>```

My query always fails, how do I get php to print the exact sql statement being sent to my database? And display that on my php view, page

答:
I'm using xdebug for watch this values in VSCode with the respective extension and CI v2.x. I add the expresion $this->db->last_query() in the watch section, and I add xdebugSettings node like these lines for get non truncate value in the launch.json.

```<code>{
  "name": "Launch currently open script",
  "type": "php",
  "request": "launch",
  "program": "${file}",
  "cwd": "${fileDirname}",
  "port": 9000,
  "xdebugSettings": {
    "max_data": -1,
    "max_children": -1
  }
},
</code>```

And run my debuger with the breakpoint and finally just select my expresion and do click right  > copy value.

Body:
I have a sql statement in my model,

I then say

$query = $this->db->query($sql, array(fields, fields1);

if ($query) {
    return true:
} else {
    echo "failed";
    return false;
}

My query always fails, how do I get php to print the exact sql statement being sent to my database? And display that on my php view, page

Body:
I'm using xdebug for watch this values in VSCode with the respective extension and CI v2.x. I add the expresion $this->db->last_query() in the watch section, and I add xdebugSettings node like these lines for get non truncate value in the launch.json.

{
  "name": "Launch currently open script",
  "type": "php",
  "request": "launch",
  "program": "${file}",
  "cwd": "${fileDirname}",
  "port": 9000,
  "xdebugSettings": {
    "max_data": -1,
    "max_children": -1
  }
},

And run my debuger with the breakpoint and finally just select my expresion and do click right  > copy value.


问:
Multiple versions of .Net Core on Macos with brew
I have been searching for a while but I haven't found anything accurate in 2019 about that how can I have multiple versions from .Net Core on Mac. My use case is that, I use .Net Core 2.2 for active development, and I'd like to play with .Net Core 3 and the goodness it has now like Razor Components and Blazor stuff.

I found articles about how .Net Core multiple version can live on the same system on Windows, which is awesome. But, Mac is not Windows (luckily, and unfortunately), and I'd like to use brew as package manager which is dealing with managing versions instead of me. If it is possible, I don't want to move out form brew zone.

I haven't found information about that how brew can help me out, rather it throws an error message saying that it will overwrite dotnet command.

```<code>mbp2017 ➜  ~ brew search dotnet
==> Casks
dotnet                                      dotnet-preview                              dotnet-sdk ✔                                dotnet-sdk-preview
mbp2017 ➜  ~ dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   2.2.105
 Commit:    7cecb35b92

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.14
 OS Platform: Darwin
 RID:         osx.10.14-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.2.105/

Host (useful for support):
  Version: 2.2.3
  Commit:  6b8ad509b6

.NET Core SDKs installed:
  2.2.105 [/usr/local/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download
mbp2017 ➜  ~ brew cask install dotnet-sdk-preview
Error: Cask 'dotnet-sdk-preview' conflicts with 'dotnet-sdk'.
➜  ~ dotnet --list-sdks
2.2.105 [/usr/local/share/dotnet/sdk]
</code>```

I found articles about DNVM, but turned out that it was something around .Net Core 1.x, since then seems not usable.

How is possible to have multiple versions from .Net Core for example using brew? If brew can't do this, then what is the suggested way?

答:
This worked for me:</p>

```<code>brew cask install \
  https://raw.githubusercontent.com/Homebrew/homebrew-cask/master/Casks/dotnet-sdk.rb
</code>```

Body:
I have been searching for a while but I haven't found anything accurate in 2019 about that how can I have multiple versions from .Net Core on Mac. My use case is that, I use .Net Core 2.2 for active development, and I'd like to play with .Net Core 3 and the goodness it has now like Razor Components and Blazor stuff.

I found articles about how .Net Core multiple version can live on the same system on Windows, which is awesome. But, Mac is not Windows (luckily, and unfortunately), and I'd like to use brew as package manager which is dealing with managing versions instead of me. If it is possible, I don't want to move out form brew zone.

I haven't found information about that how brew can help me out, rather it throws an error message saying that it will overwrite dotnet command.

mbp2017 ➜  ~ brew search dotnet
==> Casks
dotnet                                      dotnet-preview                              dotnet-sdk ✔                                dotnet-sdk-preview
mbp2017 ➜  ~ dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   2.2.105
 Commit:    7cecb35b92

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.14
 OS Platform: Darwin
 RID:         osx.10.14-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.2.105/

Host (useful for support):
  Version: 2.2.3
  Commit:  6b8ad509b6

.NET Core SDKs installed:
  2.2.105 [/usr/local/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download
mbp2017 ➜  ~ brew cask install dotnet-sdk-preview
Error: Cask 'dotnet-sdk-preview' conflicts with 'dotnet-sdk'.
➜  ~ dotnet --list-sdks
2.2.105 [/usr/local/share/dotnet/sdk]

I found articles about DNVM, but turned out that it was something around .Net Core 1.x, since then seems not usable.

How is possible to have multiple versions from .Net Core for example using brew? If brew can't do this, then what is the suggested way?

Body:
This worked for me:

brew cask install \
  https://raw.githubusercontent.com/Homebrew/homebrew-cask/master/Casks/dotnet-sdk.rb


问:
What's the difference between pytz and dateutil?
I'm trying to implement timezone awareness in my Python application, and I have come across two different Python modules that implement this feature: pytz and python-dateutil. What is the difference between these two modules?

(pytz) http://pytz.sourceforge.net/

(dateutil) https://dateutil.readthedocs.io/en/stable/

答:
pytz has the predefined time zones avialable in simple call methods such as 'Asia/kolkata' for 'kolkata' and dateutil will use all the time zones available in your operating system.
for the common time zones they are one available in pytz. That is the main difference between both of them, but pytz is less complicated.</p>


问:
Import a standard http request in postman?
I have a simple HTTP request :

```<code>POST /a/b/c HTTP/1.1
Host: localhost:17814
Content-Type: application/json
jwt: x.x.x

{
    "requestId": "E1EC8B9E-A78E-443A-B2A9-8D6F7692B63C"
}
</code>```

I don't have another format. It's a basic HTTP standard request structure.

I want to invoke it in Postman.

But it seems that when I try to "Import" it in postman it says :

Question:

Is there any way to import standard HTTP requests in postman? there must be. it's the standard syntax

答:
The Import feature only supports certain formats.

Import a Postman Collection, Environment, data dump, curl command, or
  a RAML / WADL / Open API (1.0/2.0/3.0) / GraphQL Schema / Runscope
  file

I guess that would be something this in curl:

```<code>curl -X POST 'localhost:17814/a/b/c' \
-H 'jwt: x.x.x' \
-H 'Content-Type: application/json' \
-d '{
    "requestId": "E1EC8B9E-A78E-443A-B2A9-8D6F7692B63C"
}'
</code>```

You can import that format into the app and it should create the request.

Body:
I have a simple HTTP request :

POST /a/b/c HTTP/1.1
Host: localhost:17814
Content-Type: application/json
jwt: x.x.x

{
    "requestId": "E1EC8B9E-A78E-443A-B2A9-8D6F7692B63C"
}

I don't have another format. It's a basic HTTP standard request structure.

I want to invoke it in Postman.

But it seems that when I try to "Import" it in postman it says :

Question:

Is there any way to import standard HTTP requests in postman? there must be. it's the standard syntax

Body:
The Import feature only supports certain formats.

Import a Postman Collection, Environment, data dump, curl command, or
  a RAML / WADL / Open API (1.0/2.0/3.0) / GraphQL Schema / Runscope
  file

I guess that would be something this in curl:

curl -X POST 'localhost:17814/a/b/c' \
-H 'jwt: x.x.x' \
-H 'Content-Type: application/json' \
-d '{
    "requestId": "E1EC8B9E-A78E-443A-B2A9-8D6F7692B63C"
}'

You can import that format into the app and it should create the request.


问:
How to read decimals form jsonobjects in java?
How do I read decimal values from JSONObject in java?

I have the "time" key with value as a decimal from python's Decimal module. How can I read this in java? say the json containing it is called request_json, do i get the value with

request_json.getDouble("time")?

答:
```<code>String res = request_json.getString("time");
BigDecimal decimal = new BigDecimal(res);
</code>```


问:
Departments not showing in Laravel
I have two tables ,departments and users.One department has many users.One user belongs to one department.Im trying to write a foreach loop to display the names of the departments with its users but i get this error.

Facade\Ignition\Exceptions\ViewException
  Undefined variable: departments (View: C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.blade.php)

create_users_table

```<code>
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }
</code>```

create_departments_table

```<code>public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }
</code>```

Department.php

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function department()
{
    return $this->belongsTo(Department::class);
}

}

</code>```

User.php

```<code><?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     public function department()
    {
        return $this->belongsTo(Department::class);
    }

}
</code>```

dashboard.blade.php

```<code> @extends ('layouts.master')

@section('title')
DASHBOARD | Admin
@endsection

@section('content')

<div class="row">
  <div class="col-md-12">
    <div class="card">
      @if (session('status'))
      <div class="alert alert-success" role="alert">
        {{ session('status') }}
      </div>
      @endif
      <div class="card-header">
        <h4 class="card-title"> DASHBOARD </h4>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <thead class=" text-primary">
              <th>ID</th>
              <th>Name</th>
              <th>Last Name</th>
              <th>Department</th>
            </thead>
            <tbody>
            @foreach($departments as $department)
              <td> {{$department->name}}</td>
              @endforeach
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  @endsection

  @section('scripts')

  @endsection
</code>```

DashboardController.php

```<code>class DashboardController extends Controller
{  public function index()
    {
      $users= User::all();
      foreach($users as $user)
      {
        echo $user->department->name;
        echo $user->name;
      }
   }
}
</code>```

web.php

```<code>
Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['middleware' => ['auth','admin']], function  () {

    Route::get('/dashboard', function () {
        $users= User::all();
        $departments = Department::with('users')->get();
        dd($departments);
        return view('admin.dashboard',compact('departments','users'));
    });
    //Route::get('/dashboard', "Admin\DashboardController@index");
   // Route::get('/dashboard{id}', "Admin\DashboardController@index");
    Route::get('/role-register','Admin\DashboardController@registered');
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');

});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
</code>```

I have tried this too but still the same.

```<code><td> {{$department->name}}</td>

</code>```

```<code>@foreach($departments->name as $department)
<td> {{$department}}</td>
@endforeach
</code>```

答:
Try changing the User model to have the following relation:

```<code>public function department()
{
    return $this->belongsTo(Department::class);
}
</code>```

In DashboardController change it to the following:

```<code>class DashboardController extends Controller
{
   public function index()
   {
     $users= User::all();
     foreach($users as $user)
     {
       echo $user->department->name;
       echo $user->name;
     }
  }
}
</code>```

And update the associated route:

```<code>Route::get('/dashboard', "Admin\DashboardController@index");
</code>```

Title: Departments not showing in Laravel

Body:
I have two tables ,departments and users.One department has many users.One user belongs to one department.Im trying to write a foreach loop to display the names of the departments with its users but i get this error.

Facade\Ignition\Exceptions\ViewException
  Undefined variable: departments (View: C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.blade.php)

create_users_table

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }

create_departments_table

public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

Department.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function department()
{
    return $this->belongsTo(Department::class);
}

}

User.php

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     public function department()
    {
        return $this->belongsTo(Department::class);
    }

}

dashboard.blade.php

 @extends ('layouts.master')

@section('title')
DASHBOARD | Admin
@endsection

@section('content')

      @if (session('status'))

        {{ session('status') }}

      @endif

 DASHBOARD

              ID
              Name
              Last Name
              Department

            @foreach($departments as $department)
               {{$department->name}}
              @endforeach

  @endsection

  @section('scripts')

  @endsection

DashboardController.php

class DashboardController extends Controller
{  public function index()
    {
      $users= User::all();
      foreach($users as $user)
      {
        echo $user->department->name;
        echo $user->name;
      }
   }
}

web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['middleware' => ['auth','admin']], function  () {

    Route::get('/dashboard', function () {
        $users= User::all();
        $departments = Department::with('users')->get();
        dd($departments);
        return view('admin.dashboard',compact('departments','users'));
    });
    //Route::get('/dashboard', "Admin\DashboardController@index");
   // Route::get('/dashboard{id}', "Admin\DashboardController@index");
    Route::get('/role-register','Admin\DashboardController@registered');
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');

});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

I have tried this too but still the same.

 {{$department->name}}

@foreach($departments->name as $department)
 {{$department}}
@endforeach

Body:
Try changing the User model to have the following relation:

public function department()
{
    return $this->belongsTo(Department::class);
}

In DashboardController change it to the following:

class DashboardController extends Controller
{
   public function index()
   {
     $users= User::all();
     foreach($users as $user)
     {
       echo $user->department->name;
       echo $user->name;
     }
  }
}

And update the associated route:

Route::get('/dashboard', "Admin\DashboardController@index");


问:
How to split a items inside a list, surrounded by brackets, seperated by ,
I have a string of plot ploints such as:

```<code>plots = [(0, 1), (0, 2), (1, 4), ... (0.4, 0.8) etc
</code>```

But I want to split them into respective x and y's:

```<code>x = (0, 0, 1, ... 0.4)
y = (1, 2, 4, ... 0.8)
</code>```

I am unsure how to do this.

答:
This could be an inline solution

plots = [(0, 1), (0, 2), (1, 4)]
x, y = [item[0] for item in plots], [item[1] for item in plots]
```

Body:
I have a string of plot ploints such as:

plots = [(0, 1), (0, 2), (1, 4), ... (0.4, 0.8) etc

But I want to split them into respective x and y's:

x = (0, 0, 1, ... 0.4)
y = (1, 2, 4, ... 0.8)

I am unsure how to do this.


问:
Compiler as a service: How to build Refactoring tools?
Lisa Feigenbaum from Microsoft talks here about "Compiler as a service". I have read this would make it easier to build refactoring tools. How? Mono's CAAS is great but if Microsoft version is similar I don't see how this specific use case is done.</p>

答:
My company's (Semantic Designs) offers a "compiler as a service": the DMS Software Reengineering Toolkit.

DMS is generic with respect to computer (any formal) languages.  Given an language descriptions (DMS has robust versions of these for C++, C#, Java, PHP, COBOL, and many other languages), DMS can parse source to ASTs, and regenerate valid source from those ASTs, including the orginal comments.

DMS provides various analyzer engines, both configurable attribute evaluations, flow analysis, iterative solvers, use-def analysis, local and global call graph construction, and global points-to anlaysis.   ASTs may be modifed by procedural code (classic compiler tree hacking) or by source-to-source transformations. The transformations may map ASTs in one language to that same language ("optimization") or to other langauges ("refinement/translation").   This is very mature infrastructure with 15+ years of continuous engineering behind it.

You use DMS by selecting/defining the set of input/output languages you want, and building custom code written in compiler-oriented DSLs (compiled by DMS to make your desired tool!) to invoke the various bits of DMS machinery that accomplish your purpose.

DMS has been used to build language migration tools (see B-2 Stealth Bomber mission software migration),  large-scale C++ re-architecting tools, code generation tools to run automobile factory assembly cells, and many classic software engineering tools (test coverage, profilers, clone detection, smart differencers).  It is a natural foundation for refactoring tools; we are working on these :-}


问:
How to display dynamic array of object in table under react native app?
I'm building a react native app, moving from home screen to setting screen.
 I need to load a dynamic array in table format.
 Right now i m using compoundDidMount() function to fetch data from an api.
 Everything is fine but i don't know how to render the output array i got from compoundDidMount() function.

```<code>import React from 'react';
import {
  StyleSheet,
  Text,
  TextInput,
  View,
  Button,
  ImageBackground,
  Dimensions,
  ActivityIndicator,
  Alert,
  ScrollView
} from 'react-native';

import { Table, TableWrapper, Row, Rows, Col, Cols, Cell } from 'react-native-table-component';

import { createAppContainer} from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import Icon from 'react-native-vector-icons/Ionicons';
import FormData from 'FormData';
import styles from "../css/styles";

export default class SettingsScreen extends React.Component {

   constructor(props) {
      super(props);
      this.state = {
        tableHead: ['Head', 'Head2', 'Head3'],
        widthArr: [40, 60, 80, 100, 120, 140, 160, 180, 200]
      }
    }
    componentDidMount(){

      return fetch('http://45.33.123.173:3000/query/get-history/Org2MSP.'+this.props.navigation.state.params.id)
      .then((response)=> response.json())
      .then((responseJson)=>{
        console.log('meet history',JSON.stringify(responseJson));
        console.log('meet history',responseJson[0]);
        console.log('meet history',responseJson.length);

      })

      .catch((error)=>{
          console.log(error)
      });
    }

    render() {

      const state = this.state;
      const tableData = [];
      for (let i = 0; i < state.myArray.length; i += 1) {
         state.myArray[i].username
        const rowData = [];
        for (let j = 0; j < 9; j += 1) {
          rowData.push(`${state.myArray[i].username}${state.myArray[i].balance}`);
        }
        tableData.push(rowData);
      }

      return (
        <View style={styles1.container}>
          <ScrollView horizontal={true}>
            <View>
              <Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
                <Row data={state.tableHead} widthArr={state.widthArr} style={styles1.header} textStyle={styles.text}/>
              </Table>
              <ScrollView style={styles1.dataWrapper}>
                <Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
                  {
                    tableData.map((rowData, index) => (
                      <Row
                        key={index}
                        data={rowData}
                        widthArr={state.widthArr}
                        style={[styles1.row, index%2 && {backgroundColor: '#F7F6E7'}]}
                        textStyle={styles1.text}
                      />
                    ))
                  }
                </Table>
              </ScrollView>
            </View>
          </ScrollView>
        </View>
      )
    }
  }

  const styles1 = StyleSheet.create({
    container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
    header: { height: 50, backgroundColor: '#537791' },
    text: { textAlign: 'center', fontWeight: '100' },
    dataWrapper: { marginTop: -1 },
    row: { height: 40, backgroundColor: '#E7E6E1' }
  });

  SettingsScreen.navigationOptions={
    tabBarIcon:({tintColor, focused})=>(
        <Icon
            name={focused ? 'ios-settings' : 'md-settings'}
            color={tintColor}
            size={25}
        />
    )
}

</code>```

答:
So as you said you are getting data in fetch but not in table. Because you have not saved data in state as you will need in table.

I am pasting same code you have written with some modifications.

```<code>import React, {Component} from 'react';
import { StyleSheet, View, ScrollView} from 'react-native';
import { Table, Row} from 'react-native-table-component';

class SettingsScreen  extends Component {
  constructor(props) {
    super(props);
    this.state = {
      myArray: [],
      tableHead: ['ID', 'Name', 'Number'],
      widthArr: [40, 100, 80, 100, 120, 140, 160, 180, 200]
    }
  }

  componentDidMount(){
    fetch('https://5df47c4bf9e7ae0014801983.mockapi.io/tabletest')
        .then(response=>response.json())
        .then(myArray=>{
          this.setState({myArray})
        })
  }

  render() {
    const tableData = this.state.myArray.map(record=>([record.id, record.name, record.mobile]));
        return (
        <View style={styles1.container}>
          <ScrollView horizontal={true}>
            <View>
              <Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
                <Row data={this.state.tableHead} widthArr={this.state.widthArr} style={styles1.header} textStyle={styles1.text}/>
              </Table>
              <ScrollView style={styles1.dataWrapper}>
                <Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
                  {
                    tableData.map((rowData, index) => (
                        <Row
                            key={index}
                            data={rowData}
                            widthArr={this.state.widthArr}
                            style={[styles1.row, index%2 && {backgroundColor: '#F7F6E7'}]}
                            textStyle={styles1.text}
                        />
                    ))
                  }
                </Table>
              </ScrollView>
            </View>
          </ScrollView>
        </View>
    )
  }
}

const styles1 = StyleSheet.create({
  container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
  header: { height: 50, backgroundColor: '#537791' },
  text: { textAlign: 'center', fontWeight: '100' },
  dataWrapper: { marginTop: -1 },
  row: { height: 40, backgroundColor: '#E7E6E1' }
});

export default SettingsScreen ;
</code>```

Output:

Body:
I'm building a react native app, moving from home screen to setting screen.
 I need to load a dynamic array in table format.
 Right now i m using compoundDidMount() function to fetch data from an api.
 Everything is fine but i don't know how to render the output array i got from compoundDidMount() function.

import React from 'react';
import {
  StyleSheet,
  Text,
  TextInput,
  View,
  Button,
  ImageBackground,
  Dimensions,
  ActivityIndicator,
  Alert,
  ScrollView
} from 'react-native';

import { Table, TableWrapper, Row, Rows, Col, Cols, Cell } from 'react-native-table-component';

import { createAppContainer} from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import Icon from 'react-native-vector-icons/Ionicons';
import FormData from 'FormData';
import styles from "../css/styles";

export default class SettingsScreen extends React.Component {

   constructor(props) {
      super(props);
      this.state = {
        tableHead: ['Head', 'Head2', 'Head3'],
        widthArr: [40, 60, 80, 100, 120, 140, 160, 180, 200]
      }
    }
    componentDidMount(){

      return fetch('http://45.33.123.173:3000/query/get-history/Org2MSP.'+this.props.navigation.state.params.id)
      .then((response)=> response.json())
      .then((responseJson)=>{
        console.log('meet history',JSON.stringify(responseJson));
        console.log('meet history',responseJson[0]);
        console.log('meet history',responseJson.length);

      })

      .catch((error)=>{
          console.log(error)
      });
    }

    render() {

      const state = this.state;
      const tableData = [];
      for (let i = 0; i < state.myArray.length; i += 1) {
         state.myArray[i].username
        const rowData = [];
        for (let j = 0; j < 9; j += 1) {
          rowData.push(`${state.myArray[i].username}${state.myArray[i].balance}`);
        }
        tableData.push(rowData);
      }

      return (
        <View style={styles1.container}>
          <ScrollView horizontal={true}>
            <View>

                <Row data={state.tableHead} widthArr={state.widthArr} style={styles1.header} textStyle={styles.text}/>

              <ScrollView style={styles1.dataWrapper}>

                  {
                    tableData.map((rowData, index) => (
                      <Row
                        key={index}
                        data={rowData}
                        widthArr={state.widthArr}
                        style={[styles1.row, index%2 && {backgroundColor: '#F7F6E7'}]}
                        textStyle={styles1.text}
                      />
                    ))
                  }

              </ScrollView>
            </View>
          </ScrollView>
        </View>
      )
    }
  }

  const styles1 = StyleSheet.create({
    container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
    header: { height: 50, backgroundColor: '#537791' },
    text: { textAlign: 'center', fontWeight: '100' },
    dataWrapper: { marginTop: -1 },
    row: { height: 40, backgroundColor: '#E7E6E1' }
  });

  SettingsScreen.navigationOptions={
    tabBarIcon:({tintColor, focused})=>(
        <Icon
            name={focused ? 'ios-settings' : 'md-settings'}
            color={tintColor}
            size={25}
        />
    )
}

Body:
So as you said you are getting data in fetch but not in table. Because you have not saved data in state as you will need in table.

I am pasting same code you have written with some modifications.

import React, {Component} from 'react';
import { StyleSheet, View, ScrollView} from 'react-native';
import { Table, Row} from 'react-native-table-component';

class SettingsScreen  extends Component {
  constructor(props) {
    super(props);
    this.state = {
      myArray: [],
      tableHead: ['ID', 'Name', 'Number'],
      widthArr: [40, 100, 80, 100, 120, 140, 160, 180, 200]
    }
  }

  componentDidMount(){
    fetch('https://5df47c4bf9e7ae0014801983.mockapi.io/tabletest')
        .then(response=>response.json())
        .then(myArray=>{
          this.setState({myArray})
        })
  }

  render() {
    const tableData = this.state.myArray.map(record=>([record.id, record.name, record.mobile]));
        return (
        <View style={styles1.container}>
          <ScrollView horizontal={true}>
            <View>
              <Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
                <Row data={this.state.tableHead} widthArr={this.state.widthArr} style={styles1.header} textStyle={styles1.text}/>
              </Table>
              <ScrollView style={styles1.dataWrapper}>
                <Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
                  {
                    tableData.map((rowData, index) => (
                        <Row
                            key={index}
                            data={rowData}
                            widthArr={this.state.widthArr}
                            style={[styles1.row, index%2 && {backgroundColor: '#F7F6E7'}]}
                            textStyle={styles1.text}
                        />
                    ))
                  }
                </Table>
              </ScrollView>
            </View>
          </ScrollView>
        </View>
    )
  }
}

const styles1 = StyleSheet.create({
  container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
  header: { height: 50, backgroundColor: '#537791' },
  text: { textAlign: 'center', fontWeight: '100' },
  dataWrapper: { marginTop: -1 },
  row: { height: 40, backgroundColor: '#E7E6E1' }
});

export default SettingsScreen ;

Output:


问:
Android SMS Broadcast Receiver doesn't work
Hi I'm trying to catch the sms content and use in my app, so I made a BroadcastReceiver with Permission and Manifests But when the device receive sms, my code doesn't run which means that the BroadcastReceiver doesn't fire.
I also checked many Articles inside and outside here, there're some:

Android Sms Receiver Result to Main Activity
SMS receiver didn't work

Android SMS Receiver not working

Broadcast Receiver not working for SMS

Here is a part of my Manifest:

```<code><uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application.
...
...
<receiver android:name="com.example.android.receiver.SmsReceiver"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
</application>
</code>```

And This is my Receiver

```<code>public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "SMS Received!", Toast.LENGTH_LONG).show();
    }
}
</code>```

I also tried to register the receiver dynamically inside activity onCreate() but nothing changed

```<code>IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(2147483647);
registerReceiver(new SmsReceiver(), intentFilter);
</code>```

Does anyone know where is the problem? It should just Toast that a message is recieved so I can continue work but the receiver doesn't seem to even fire

答:
You should request runtime permission to receive SMS(Android 6.0 and higher).

https://developer.android.com/guide/topics/permissions/overview

Body:
Hi I'm trying to catch the sms content and use in my app, so I made a BroadcastReceiver with Permission and Manifests But when the device receive sms, my code doesn't run which means that the BroadcastReceiver doesn't fire.
I also checked many Articles inside and outside here, there're some:

Android Sms Receiver Result to Main Activity
SMS receiver didn't work

Android SMS Receiver not working

Broadcast Receiver not working for SMS

Here is a part of my Manifest:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application.
...
...
<receiver android:name="com.example.android.receiver.SmsReceiver"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
</application>

And This is my Receiver

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "SMS Received!", Toast.LENGTH_LONG).show();
    }
}

I also tried to register the receiver dynamically inside activity onCreate() but nothing changed

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(2147483647);
registerReceiver(new SmsReceiver(), intentFilter);

Does anyone know where is the problem? It should just Toast that a message is recieved so I can continue work but the receiver doesn't seem to even fire


问:
Bootswatch - dropdown menu is not working
I'm trying to integrate a custom theme for bootstrap

the theme i want to use is bootswatch

the only problem i'm currently facing is that the dropdown menu in the navigation bar is not working.

this is my code.

<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css" rel="stylesheet" integrity="sha384-+ENW/yibaokMnme+vBLnHMphUYxHs34h9lpdbSLuAwGkOKFRl4C34WkjazBtb7eT" crossorigin="anonymous">

              Bootswatch
              <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

              </button>

                  Themes

Default

Cerulean

Cosmo

Cyborg

Darkly

Flatly

Journal

Lumen

Paper

Readable

Sandstone

Simplex

Slate

Spacelab

Superhero

United

Yeti

                  Help

                  Blog

                  Flatly

Open Sandbox

bootstrap.min.css

bootstrap.css

variables.less

bootswatch.less

_variables.scss

_bootswatch.scss

Built With Bootstrap

WrapBootstrap

```

答:
I use bootstrap 4.3.1 instead of 3.3.7 to fix this problem.

https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js

Maybe you can try it.


问:
Replace Text with jQuery if text exists
What I am trying to do in jQuery is to take the first comment, out of a group that is all hidden until the user clicks on a button, and output that first comment so it is visible.  I have this working, to a point.  I want it to happen when the page loads, so I have it in the document.ready, but it won't work.  So I attached it to a mousemove event, and it works.

But what I want to do now is if there is a comment, take the comment and show it like I have previously.  But if there isn't a comment, then show the words 'No Comment'.  Below is the code I'm using.

```<code>if ( jQuery('.dsq-commenter-name').length ){
          jQuery(document).mousemove(function() {
            jQuery('#comments p strong').text( jQuery('.dsq-commenter-name').text() );
            jQuery('#comments p span.comment_excerpt').text( jQuery('.dsq-comment-text').text() );
        });
      }
</code>```

This code isn't working.  If I take away the if statement, it works fine to replace the text, but if no comments at all, it just puts empty space instead of leaving the words 'No Comments'.  If I put the code directly into the console, it works.  So I'm not sure why it won't work when the page loads.  I'm assuming it has to be something with the if statement, but I've tried all kinds of things and can't get it to work.

EDIT:
Not shown in this code but I have everything in a jQuery(document).ready(function() {
and that doesn't seem to help.  But the comments are handled by Disqus, and so I'm thinking they are loaded later, so how would I go about attaching an event to them?

SECOND EDIT:
Okay I've fixed it, not sure if it is the best way to do it though.  Thanks to @Jacob, I decided the comments were loading after the code had already executed.  So I added on to the code using setTimeout, and so the function will run a second or so after the page loads, which works.  Again, not sure if this is the way to do it or not, so please correct me if I'm wrong or if you want to see the code.

答:
jQuery('.dsq-commenter-name') will return the jQuery selector locating the desired element. .length will always be true unless the element does not exist, regardless of content. If you care for text you want to do a .text() on the output. It will return null if no elements were found by the query.

Probably

```<code>if (jQuery('.dsq-commenter-name').text()) { // checks for "", null, undefined
</code>```

Title: Replace Text with jQuery if text exists

Body:
What I am trying to do in jQuery is to take the first comment, out of a group that is all hidden until the user clicks on a button, and output that first comment so it is visible.  I have this working, to a point.  I want it to happen when the page loads, so I have it in the document.ready, but it won't work.  So I attached it to a mousemove event, and it works.

But what I want to do now is if there is a comment, take the comment and show it like I have previously.  But if there isn't a comment, then show the words 'No Comment'.  Below is the code I'm using.

if ( jQuery('.dsq-commenter-name').length ){
          jQuery(document).mousemove(function() {
            jQuery('#comments p strong').text( jQuery('.dsq-commenter-name').text() );
            jQuery('#comments p span.comment_excerpt').text( jQuery('.dsq-comment-text').text() );
        });
      }

This code isn't working.  If I take away the if statement, it works fine to replace the text, but if no comments at all, it just puts empty space instead of leaving the words 'No Comments'.  If I put the code directly into the console, it works.  So I'm not sure why it won't work when the page loads.  I'm assuming it has to be something with the if statement, but I've tried all kinds of things and can't get it to work.

EDIT:
Not shown in this code but I have everything in a jQuery(document).ready(function() {
and that doesn't seem to help.  But the comments are handled by Disqus, and so I'm thinking they are loaded later, so how would I go about attaching an event to them?

SECOND EDIT:
Okay I've fixed it, not sure if it is the best way to do it though.  Thanks to @Jacob, I decided the comments were loading after the code had already executed.  So I added on to the code using setTimeout, and so the function will run a second or so after the page loads, which works.  Again, not sure if this is the way to do it or not, so please correct me if I'm wrong or if you want to see the code.

Body:
jQuery('.dsq-commenter-name') will return the jQuery selector locating the desired element. .length will always be true unless the element does not exist, regardless of content. If you care for text you want to do a .text() on the output. It will return null if no elements were found by the query.

Probably

if (jQuery('.dsq-commenter-name').text()) { // checks for "", null, undefined


问:
How to do this as mysql query
I need help with a mysql query. I have a table like this
I have "type" 1 to 15. I would like help with a query to automatically change the "type"</p>

答:
If you are happy storing your logic in the table itself, then you could use a calculated column.

```<code>CREATE TABLE members (
 points INT,
 type DOUBLE AS
   (CASE
     WHEN points < 1600 THEN 1
     WHEN points < 14000 THEN 2
     -- TODO: implement other cases
     ELSE 3
    END))

</code>```

So when the points column is updated, there is no need to "update" the type column - the type is automatically calculated from the points whenever the table is read.

https://www.db-fiddle.com/f/fqEL2jtNio1Srt5xLkyLy2/0

Edit:

As Caius Jard mentions in their answer, the performance of selects would start to degrade at scale, but how you optimize depends on how volatile the points are, and how frequent your reads are.

Title: How to do this as mysql query

Body:
If you are happy storing your logic in the table itself, then you could use a calculated column.

CREATE TABLE members (
 points INT,
 type DOUBLE AS
   (CASE
     WHEN points < 1600 THEN 1
     WHEN points < 14000 THEN 2
     -- TODO: implement other cases
     ELSE 3
    END))

So when the points column is updated, there is no need to "update" the type column - the type is automatically calculated from the points whenever the table is read.

https://www.db-fiddle.com/f/fqEL2jtNio1Srt5xLkyLy2/0

Edit:

As Caius Jard mentions in their answer, the performance of selects would start to degrade at scale, but how you optimize depends on how volatile the points are, and how frequent your reads are.


问:
Can you attach Amazon EBS to multiple instances?
We currently  use multiple webservers accessing one mysql server and fileserver.  Looking at moving to the cloud, can I use this same setup and attach the EBS to multiple machine instances or what's another solution? </p>

答: Although EBS has previously only allowed a single EC2 instance to be attached to a given volume, multi-attach is now possible, at least for io1 volumes. For more information, see this AWS blog post.</p>


问:
how to I get value of excel using C#, if a cell has error
For e.g., a cell with =1-b would have #Name error, but if I use .Value, it would return -2146826259, if I use .Text, it would return #Name, how could I get =1-b? Thanks in prior.</p>

答:
Assuming you are using ExcelInterop Reference you can do this to get Formula value

var cellValue = (xlWorksheet.Cells[1, 1] as Range).Formula;

Main

```<code>string pathToExcelFile = @"C:\Users\MyPC\Documents\Book1.xlsx";

Application xlApp = new Application();
Workbook xlWorkbook = xlApp.Workbooks.Open(pathToExcelFile, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

_Worksheet xlWorksheet = (_Worksheet)xlWorkbook.Sheets[1];

var cellValue = (xlWorksheet.Cells[1, 1] as Range).Formula;

</code>```

Output

=1-b

Body:
Assuming you are using ExcelInterop Reference you can do this to get Formula value

var cellValue = (xlWorksheet.Cells[1, 1] as Range).Formula;

Main

string pathToExcelFile = @"C:\Users\MyPC\Documents\Book1.xlsx";

Application xlApp = new Application();
Workbook xlWorkbook = xlApp.Workbooks.Open(pathToExcelFile, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

_Worksheet xlWorksheet = (_Worksheet)xlWorkbook.Sheets[1];

var cellValue = (xlWorksheet.Cells[1, 1] as Range).Formula;

Output

=1-b


问:
java.lang.NoClassDefFoundError: org/apache/http/concurrent/FutureCallback
I am trying to use Unirest-Mashape to build java applications.

This is my code:

```<code>import com.mashape.unirest.http.*;
public class PAskMe
{
  public static void main(String args[]) throws Exception
  {
        HttpResponse<JsonNode> response = Unirest.get("https://montanaflynn-dictionary.p.mashape.com/define?word=irony").
                                                                                header("X-Mashape-Key", "KEY").
                                                                                asJson();
        System.out.println(response.toString());
  }
}
</code>```

When I compile my code, It shows no error. But when I run it, it shows the following runtime error :

```<code>java.lang.NoClassDefFoundError: org/apache/http/concurrent/FutureCallback
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at PAskMe.PAskMe.main(PAskMe.java:14)
at PAskMe.__SHELL0.run(__SHELL0.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at bluej.runtime.ExecServer$3.run(ExecServer.java:725)

Caused by: java.lang.ClassNotFoundException: org.apache.http.concurrent.FutureCallback
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 8 more
</code>```

I have included these jars in my project :

But still I am getting the error. Please help me.

答:
Along with httpcore-4.4.12.jar you also need to add below dependencies to avoid runtime error

httpclient-4.5.6.jar

httpmime-4.5.6.jar

also make sure that all dependencies are compatible with each other

Body:
I am trying to use Unirest-Mashape to build java applications.

This is my code:

import com.mashape.unirest.http.*;
public class PAskMe
{
  public static void main(String args[]) throws Exception
  {
        HttpResponse<JsonNode> response = Unirest.get("https://montanaflynn-dictionary.p.mashape.com/define?word=irony").
                                                                                header("X-Mashape-Key", "KEY").
                                                                                asJson();
        System.out.println(response.toString());
  }
}

When I compile my code, It shows no error. But when I run it, it shows the following runtime error :

java.lang.NoClassDefFoundError: org/apache/http/concurrent/FutureCallback
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at PAskMe.PAskMe.main(PAskMe.java:14)
at PAskMe.__SHELL0.run(__SHELL0.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at bluej.runtime.ExecServer$3.run(ExecServer.java:725)

Caused by: java.lang.ClassNotFoundException: org.apache.http.concurrent.FutureCallback
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 8 more

I have included these jars in my project :

But still I am getting the error. Please help me.


问:
Best approach to deploy multiple less usable applications in single infrastructure to optimize cost on Cloud
Requirement: Cost optimization on Cloud resources

Current Scenario: I am having multiple applications that have their own infrastructure on consists of App Service, MySQL database, function, etc.

Considering these applications will be used by a few people.

My thinking is:
 Containerizing all these web applications' servers

```<code> 1. Use a VM to deploy all the servers
 2. Use a Container Instanceto deploy all the servers
 3. Use Kubernetes Services to deploy all the servers
</code>```

Questions: Which approach would be preferable and so that I can expose different IP of servers and map it to its own domain.

For Database,
  Apart from using Elastic Pool,
  I have no idea how to optimize these databases

I would be glad to have any suggestions thanks.

答:
AKS would be the way to host everything on the same platform and cut costs, but at the same time you'd need to maintain everything you host in AKS.

Elastic Pools do not work for MySQL (only Azure SQL). But you can host MySQL in AKS. To replace functions in AKS you can use KEDA. You'd be able to use host based routing (preferably) or IP based routing to expose your services

Body:
Requirement: Cost optimization on Cloud resources

Current Scenario: I am having multiple applications that have their own infrastructure on consists of App Service, MySQL database, function, etc.

Considering these applications will be used by a few people.

My thinking is:
 Containerizing all these web applications' servers

 1. Use a VM to deploy all the servers
 2. Use a Container Instanceto deploy all the servers
 3. Use Kubernetes Services to deploy all the servers

Questions: Which approach would be preferable and so that I can expose different IP of servers and map it to its own domain.

For Database,
  Apart from using Elastic Pool,
  I have no idea how to optimize these databases

I would be glad to have any suggestions thanks.


问:
Is Heroku dependable?
I have been hosting a site on Heroku for a few months that is very soon to go into production.

Since I began with them, there have been at least three significant outages, one of which was the disastrous Amazon outage last month and another of which is a multi-hour outage happening today.

I believe in Heroku's vision and I think they are a great company, but I am faced with the ultimate problem: if they can't keep sites up and running, everything I like about them doesn't really matter.

Is Heroku a reliable provider to run a production site on Rails?

Are there any other providers I might look into that have a better reputation for reliability than Heroku?

答:
I have seem Heroku to be reliable. I highly recommended it for starting out and validating your idea. I believe when you start your project you want get it out quickly (to customer or to public).

As mentioned in other comments at some point you might need to switch over to EC2 as you might need zone redundancy and it might actually become cheaper to run of EC2 especially if you already have an SA in the company.

Title: Is Heroku dependable?


问:
How to find growth rate of function?
I have three functions, and I have to order them according to their relative growth rates (in increasing order). Following are the functions given:

f(x)=

f(x)=

f(x)=

I am not understanding that how do I find growth rate?

答:
To find the growth rate, you could use a spreadsheet and draw graphs for different values.

Once you've done that, take a graph and look at the shape and place them in order of how they grow. Here's a clue 20 * n^18 is much much bigger than log20(n^18).

Title: How to find growth rate of function?


问:
Install and Refence Tao Framework on Visual Studio 2010
I'm Trying to get the Tao Framework going in my system. I have Windows 7 64bit With Visual Studio 2010.

I have downloaded the file "taoframework-2.1.0-setup.exe" and installed it, leaving everything as it was.

As far as I understand now i should be able to add either a "Tool" in the toolbox that will be called simpleOpen GL or to add a "Reference" in a specific project.

The problem is that nothing related to Tao Framework is showing in my visual studio.

I've been reading around and haven't found any solid answers, a tutorial would be nice, any info will help!

Thanks!

答:
What about OpenTK? Apparently Tao has been superseded by OpenTK. The last release of Tao was in 2008.

http://www.opentk.com/


问:
extract characters from second occurrence of dash in a string
I have a string "apple-rose-orange-21-X-84"; I need to extract the string after the second occurrence of "-" using shell script.

The answer should be orange-21-X-84.

How would I do this in shell script, I have tried several ways, couldn't find an answer.

答:
shell only solution:

```<code>string='apple-rose-orange-21-X-84'
echo ${string#*-*-}
</code>```

See Shell Parameter Expansion

${parameter#word}

${parameter##word}

The word is expanded to produce a
  pattern and matched according to the rules described below (see
  Pattern Matching). If the pattern matches the beginning of the
  expanded value of parameter, then the result of the expansion is the
  expanded value of parameter with the shortest matching pattern (the
  ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If
  parameter is ‘@’ or ‘’, the pattern removal operation is applied to
  each positional parameter in turn, and the expansion is the resultant
  list. If parameter is an array variable subscripted with ‘@’ or ‘’,
  the pattern removal operation is applied to each member of the array
  in turn, and the expansion is the resultant list.

Body:
shell only solution:

string='apple-rose-orange-21-X-84'
echo ${string#*-*-}

See Shell Parameter Expansion

${parameter#word}

${parameter##word}

The word is expanded to produce a
  pattern and matched according to the rules described below (see
  Pattern Matching). If the pattern matches the beginning of the
  expanded value of parameter, then the result of the expansion is the
  expanded value of parameter with the shortest matching pattern (the
  ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If
  parameter is ‘@’ or ‘’, the pattern removal operation is applied to
  each positional parameter in turn, and the expansion is the resultant
  list. If parameter is an array variable subscripted with ‘@’ or ‘’,
  the pattern removal operation is applied to each member of the array
  in turn, and the expansion is the resultant list.


问:
failed to develop login page with ajax
I have been trying to develop a login page using ajax and servlet. But I haven't successfully created one. The results are always different from what I expected. I even tried referring to a previously successful file but I still failed.

These are my codes:

index.html

```<code> <form id="loginFrm">
                <div class="imgcontainer">
                    <img src="img_avatar2.png" alt="Avatar" class="avatar">
                </div>

                <div class="container">

                    <input type="radio" value="Urusetia" name="loginRole">Urusetia<br>
                    <input type="radio" value="Penyelaras PITA" name="loginRole">Penyelaras PITA<br>
                    <input type="radio" value="Penyelia" name="loginRole">Penyelia<br>
                    <input type="radio" value="Penilai" name="loginRole">Penilai<br>
                    <input type="radio" value="Pelajar" name="loginRole">Pelajar<br>

                    <label for="uname"><b>Username</b></label>
                    <input type="text" placeholder="Enter Username" id="username" required>

                    <label for="psw"><b>Password</b></label>
                    <input type="password" placeholder="Enter Password" id="password" required>

                    <button type="submit">Login</button>
                    <label>
                        <input type="checkbox" checked="checked" name="remember"> Remember me
                    </label>
                </div>

                <div class="container" style="background-color:#f1f1f1">
                    <button type="button" class="cancelbtn">Cancel</button>
                    <span class="psw">Forgot <a href="#">password?</a></span>
                </div>
            </form>
</code>```

index.js

```<code>$(function(){
$("#loginFrm").submit(function(e){
        e.preventDefault();
        e.stopPropagation();
        var username = $("#username").val();
        var password = $("#password").val();

        var datalist = "username="+username+"&password="+password;

        $.ajax({
           type:"post",
           url:"LogMasuk",
           data:datalist,
           cache: false,
           success: function(mydata){

               var myData = JSON.parse(mydata);
               if(myData.status === 1){
                   alert("Success");
                   sessionStorage.token = username;
                   location.href = "dashboard.html";
               }else if(myData.status === 0){
                   alert("User not found.");
               }
           },
           error: function(){
               console.log("AJAX error.");
           }
        });
    });
});
</code>```

LogMasuk.java

```<code>public class LogMasuk extends HttpServlet {
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {

     JSONObject jo = new JSONObject();
     response.setContentType("text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();
     try {
         /* TODO output your page here. You may use following sample code. */
         String username = request.getParameter("username");
         String password = request.getParameter("password");

         jo = dbAPI.LogMasuk(username, password);

     } finally {
         out.print(jo);
         out.close();
     }
 }
</code>```

and the file to refer to database

```<code>public static JSONObject LogMasuk(String username, String password){
        JSONObject jo = new JSONObject();
        boolean exist = false;

        try{
            con = conMan.getConnection();
            String sql = "SELECT * FROM pelajar WHERE username=? AND password=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();

            while(rs.next()){
                exist = true;
            }
            if(exist){
                jo.put("status", 1);
            }
            else
                jo.put("status", 0);
        }
        catch(SQLException e){
            jo.put("status", -1);
        }
        return jo;
</code>```

Every time I always hit {} response in the browser's console under the network tab even the status code is ok.

Thanks in advance.

答:
Your problem is caused by bad exception handling.

Your code threw an exception, most likely a ClassNotFoundException on the JDBC driver, but you're basically completely suppressing it by forcing the close of the response body in the finally block.

```<code>try {
    // ...
} finally {
    out.print(jo);
    out.close(); // BAD! Remove this line!
}
</code>```

This way you're basically preventing the server from showing its default error response which usually contains a stack trace and thus effectively the answer to your real problem.

Better yet, do not handle exceptions like that in a servlet. Remove the try-finally block altogether.

```<code>// ...
out.print(jo);
</code>```

If any, you should be rethrowing any checked exception as a ServletException in a catch block.

```<code>try {
    // ...
    out.print(jo);
} catch (SomeCheckedException e) {
    throw new ServletException(e);
}
</code>```

This way the server will be able to properly deal with it and you can configure the error response body in web.xml.

See also:

Submitting form to Servlet which interacts with database results in blank page

How should I connect to JDBC database / datasource in a servlet based application?

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Title: failed to develop login page with ajax

Body:
I have been trying to develop a login page using ajax and servlet. But I haven't successfully created one. The results are always different from what I expected. I even tried referring to a previously successful file but I still failed.

These are my codes:

index.html

 <form id="loginFrm">

                    <input type="radio" value="Urusetia" name="loginRole">Urusetia

                    <input type="radio" value="Penyelaras PITA" name="loginRole">Penyelaras PITA

                    <input type="radio" value="Penyelia" name="loginRole">Penyelia

                    <input type="radio" value="Penilai" name="loginRole">Penilai

                    <input type="radio" value="Pelajar" name="loginRole">Pelajar

                    Username
                    <input type="text" placeholder="Enter Username" id="username" required>

                    Password
                    <input type="password" placeholder="Enter Password" id="password" required>

                    <button type="submit">Login</button>

                        <input type="checkbox" checked="checked" name="remember"> Remember me

                    <button type="button" class="cancelbtn">Cancel</button>
                    Forgot password?

            </form>

index.js

$(function(){
$("#loginFrm").submit(function(e){
        e.preventDefault();
        e.stopPropagation();
        var username = $("#username").val();
        var password = $("#password").val();

        var datalist = "username="+username+"&password="+password;

        $.ajax({
           type:"post",
           url:"LogMasuk",
           data:datalist,
           cache: false,
           success: function(mydata){

               var myData = JSON.parse(mydata);
               if(myData.status === 1){
                   alert("Success");
                   sessionStorage.token = username;
                   location.href = "dashboard.html";
               }else if(myData.status === 0){
                   alert("User not found.");
               }
           },
           error: function(){
               console.log("AJAX error.");
           }
        });
    });
});

LogMasuk.java

public class LogMasuk extends HttpServlet {
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {

     JSONObject jo = new JSONObject();
     response.setContentType("text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();
     try {
         /* TODO output your page here. You may use following sample code. */
         String username = request.getParameter("username");
         String password = request.getParameter("password");

         jo = dbAPI.LogMasuk(username, password);

     } finally {
         out.print(jo);
         out.close();
     }
 }

and the file to refer to database

public static JSONObject LogMasuk(String username, String password){
        JSONObject jo = new JSONObject();
        boolean exist = false;

        try{
            con = conMan.getConnection();
            String sql = "SELECT * FROM pelajar WHERE username=? AND password=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();

            while(rs.next()){
                exist = true;
            }
            if(exist){
                jo.put("status", 1);
            }
            else
                jo.put("status", 0);
        }
        catch(SQLException e){
            jo.put("status", -1);
        }
        return jo;

Every time I always hit {} response in the browser's console under the network tab even the status code is ok.

Thanks in advance.

Body:
Your problem is caused by bad exception handling.

Your code threw an exception, most likely a ClassNotFoundException on the JDBC driver, but you're basically completely suppressing it by forcing the close of the response body in the finally block.

try {
    // ...
} finally {
    out.print(jo);
    out.close(); // BAD! Remove this line!
}

This way you're basically preventing the server from showing its default error response which usually contains a stack trace and thus effectively the answer to your real problem.

Better yet, do not handle exceptions like that in a servlet. Remove the try-finally block altogether.

// ...
out.print(jo);

If any, you should be rethrowing any checked exception as a ServletException in a catch block.

try {
    // ...
    out.print(jo);
} catch (SomeCheckedException e) {
    throw new ServletException(e);
}

This way the server will be able to properly deal with it and you can configure the error response body in web.xml.

See also:

Submitting form to Servlet which interacts with database results in blank page

How should I connect to JDBC database / datasource in a servlet based application?

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception


问:
how to get a fragment added in an XML layout
I have a layout which includes a fragment as follows:

```<code><fragment
        android:id="@+id/mainImagesList"
        android:name="com.guc.project.ImagesList"
        android:layout_width="match_parent"
        android:layout_height="62dp"
        android:layout_below="@+id/addimagebutton"
        android:layout_weight="1"
        android:paddingTop="55dp" />
</code>```

now, I need to get this fragment and cast it so I can manipulate it and the updates appear. How can i do so ?!

EDIT: I think I've managed to get the fragment, but when I change some variables, the changes don't appear !

答:
If Fragment is included inside the layout file of Activity then it can be referenced by SupportFragmentManager like...

```<code>MyFragment myFragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.FRAGMENTID)
</code>```

If Fragment is included inside the layout file of another Fragment then it can be referenced by ChildFragmentManager like...

```<code> MyFragment myFragment= (MyFragment)getChildFragmentManager().findFragmentById(R.id.FRAGMENTID)
</code>```

Body:
I have a layout which includes a fragment as follows:

<fragment
        android:id="@+id/mainImagesList"
        android:name="com.guc.project.ImagesList"
        android:layout_width="match_parent"
        android:layout_height="62dp"
        android:layout_below="@+id/addimagebutton"
        android:layout_weight="1"
        android:paddingTop="55dp" />

now, I need to get this fragment and cast it so I can manipulate it and the updates appear. How can i do so ?!

EDIT: I think I've managed to get the fragment, but when I change some variables, the changes don't appear !

Body:
If Fragment is included inside the layout file of Activity then it can be referenced by SupportFragmentManager like...

MyFragment myFragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.FRAGMENTID)

If Fragment is included inside the layout file of another Fragment then it can be referenced by ChildFragmentManager like...

 MyFragment myFragment= (MyFragment)getChildFragmentManager().findFragmentById(R.id.FRAGMENTID)


问:
SELECT all (but one column as null)
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

```<code>SELECT *, id AS (SELECT '') FROM my_table WHERE 1
</code>```

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

答:
So, there is no way to use SELECT * and replace one of the columns with another value.

If you don't want to use the select statement provided in your application code, you can create a view with those fields populated and the ID nulled out.  You'll still have to name all the columns at least once.

```<code>select NULL as ID, t.col2, t.col3, t.col4 from mytable t where col2 = 1
</code>```

Here is the easy way to get all of your column names:

```<code>SELECT column_name FROM information_schema.columns WHERE table_name = mytable
</code>```

Title: SELECT all (but one column as null)

Body:
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

SELECT *, id AS (SELECT '') FROM my_table WHERE 1

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

Body:
So, there is no way to use SELECT * and replace one of the columns with another value.

If you don't want to use the select statement provided in your application code, you can create a view with those fields populated and the ID nulled out.  You'll still have to name all the columns at least once.

select NULL as ID, t.col2, t.col3, t.col4 from mytable t where col2 = 1

Here is the easy way to get all of your column names:

SELECT column_name FROM information_schema.columns WHERE table_name = mytable


问:
How to make dynamic variables with less in a CSS file?
Actually I want to use a CSS variable in less...

```<code>:root {
    --header: #6B66A4;
}

@header: #6B66A4;
</code>```

How?

答:
Less compiles the following

```<code>:root {
  --header: #6B66A4;
}

@header: var(--header);

body {
  color: @header;
}
</code>```

to this CSS being generated at build time:

:root {
  --header: #6B66A4;
}

body {
  color: var(--header);
}
```

Of course Less doesn't know anything about what var(--header) means or is - it's just a string to Less.

Body:
Actually I want to use a CSS variable in less...

:root {
    --header: #6B66A4;
}

@header: #6B66A4;

How?

Body:
Less compiles the following

:root {
  --header: #6B66A4;
}

@header: var(--header);

body {
  color: @header;
}

to this CSS being generated at build time:

:root {
  --header: #6B66A4;
}

body {
  color: var(--header);
}

Of course Less doesn't know anything about what var(--header) means or is - it's just a string to Less.


问:
Lambda Calculus vs Category theory in FP
Trying to learn functional programming approach I was faced with both lambda calculus and Category theory terms.

Could you please explain in layman's terms what are the differences between them, in the scope of FP.

What do they mean for FP?

Thank you!

答:
It's hard to fully answer such a broad question. Below, I tried to provide some insights, but I can not describe these vast topics in only a few paragraphs.

The lambda calculus is the mathematical core of any functional programming language. It can be seen as a very minimalistic programming language, where the key properties of FP can be studied without being distracted by an heavy syntax.

Any programmer, especially if they are FP programmers, should be able to learn the basics of lambda calculus within a few hours of study. Note that, even if the basics are rather simple, the underlying theory is incredibly vast: there's a huge amount of scientific literature dedicated to the lambda calculus. One does not need to know all of this for everyday FP, but reading a few results here and there once in a while can provide some insights on FP. For instance, reading about Church encodings can make one realize how powerful can be a lambda abstraction.

Category theory is one of the most abstract parts of mathematics. Compared with the lambda calculus, it is much harder to study. It can be very challenging.

CT is connected with the lambda calculus mostly because it provides a nice way to understand types. Types in FP have an underlying algebraic structure which can be best understood by categorical means. For instance, in Haskell the types (A, Either B C) and Either (A,B) (A,C) are isomorphic (ignoring bottoms, at least;  because a*(b+c) = (a*b)+(a*c) ), roughly meaning that they carry the same amount of information. As another example, currying and uncurrying form the fundamental idea of cartesian closed categories, the "standard" way to interpret simple types.

If you have a programmer's background, you can try Bartosz Milewski's online book Category Theory for Programmers. Still, I would recommend to start from learning some FP and the lambda calculus first.


问:
How to get all the agents in the surrounding area in GISMap
I have this one target agent, I want to get all the other agents that are within like 100 meters in GISMap.
Is there a way that you do not need to iterate through every agent in your environment and calculate their distances to the target agent to achieve the task, because If I have 5000 agents and I want to know who are within the area every second, the calculation burden will just be too much I think.
Thanks!</p>

答:
You can turn the logic around. Make the other agents register with your target agent when they are close enough.

Depending on the situation, this could be more efficient (but there is no guarantee).

Apart from that, there is no different logic to achieve this. So you would need to think differently: check less frequently or use a different (non GIS) condition