问:
Transform data from fetch with React
I have retrieved data from an API, and now trying to transform the data to send a POST request. I want to group two User ID's that match, and POST their common cities in a array instead of separate objects.

For example, data I retrieve looks like this:

```<code>{
    "events": [
         {
             "city": "city-1",
             "user": "d1177368-2310-11e8-9e2a-9b860a0d9039"
         },
         {
             "city": "city-2",
            "user": "d1177368-2310-11e8-9e2a-9b860a0d9039"
         }
]}
</code>```

I want my POST request data to look similar to this:

```<code>{
    "user": {
        "d1177368-2310-11e8-9e2a-9b860a0d9039": [
            {
                "city": [
                    "city-1",
                    "city-2"
                ]
            }]}}
</code>```

So far this is my React component for the request:

```<code>import React, { useEffect, useState } from "react";
import axios from "../data/axios";

export default function Events({ fetchEvents }) {
  const [events, setEvents] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const requests = await axios.get(fetchEvents);
      setEvents(requests.data.events);
      return requests;
    }
    fetchData();
  }, [fetchEvents]);

//here is my issue:
  function createSessions(user, city) {
    if (user === user) {

    }
  }
</code>```

Thank you

答:
Iterate over the events array, reducing it into an object with a user object property. The user object has the user values from the events array elements as key and the cities are pushed into a city array property.

```<code>events.reduce(
  (result, el) => {
    if (!result.user[el.user]) {
      result.user[el.user] = [{ city: [] }];
    }
    result.user[el.user][0].city.push(el.city);
    return result;
  },
  { user: {} }
);
</code>```

const data = {
  events: [
    {
      city: "city-1",
      user: "d1177368-2310-11e8-9e2a-9b860a0d9039"
    },
    {
      city: "city-2",
      user: "d1177368-2310-11e8-9e2a-9b860a0d9039"
    }
  ]
};

const data2 = data.events.reduce(
  (result, el) => {
    if (!result.user[el.user]) {
      result.user[el.user] = [{ city: [] }];
    }
    result.user[el.user][0].city.push(el.city);
    return result;
  },
  { user: {} }
);

console.log(data2);```

Title: Transform data from fetch with React

Body:
I have retrieved data from an API, and now trying to transform the data to send a POST request. I want to group two User ID's that match, and POST their common cities in a array instead of separate objects.

For example, data I retrieve looks like this:

{
    "events": [
         {
             "city": "city-1",
             "user": "d1177368-2310-11e8-9e2a-9b860a0d9039"
         },
         {
             "city": "city-2",
            "user": "d1177368-2310-11e8-9e2a-9b860a0d9039"
         }
]}

I want my POST request data to look similar to this:

{
    "user": {
        "d1177368-2310-11e8-9e2a-9b860a0d9039": [
            {
                "city": [
                    "city-1",
                    "city-2"
                ]
            }]}}

So far this is my React component for the request:

import React, { useEffect, useState } from "react";
import axios from "../data/axios";

export default function Events({ fetchEvents }) {
  const [events, setEvents] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const requests = await axios.get(fetchEvents);
      setEvents(requests.data.events);
      return requests;
    }
    fetchData();
  }, [fetchEvents]);

//here is my issue:
  function createSessions(user, city) {
    if (user === user) {

    }
  }

Thank you

Body:
Iterate over the events array, reducing it into an object with a user object property. The user object has the user values from the events array elements as key and the cities are pushed into a city array property.

events.reduce(
  (result, el) => {
    if (!result.user[el.user]) {
      result.user[el.user] = [{ city: [] }];
    }
    result.user[el.user][0].city.push(el.city);
    return result;
  },
  { user: {} }
);

const data = {
  events: [
    {
      city: "city-1",
      user: "d1177368-2310-11e8-9e2a-9b860a0d9039"
    },
    {
      city: "city-2",
      user: "d1177368-2310-11e8-9e2a-9b860a0d9039"
    }
  ]
};

const data2 = data.events.reduce(
  (result, el) => {
    if (!result.user[el.user]) {
      result.user[el.user] = [{ city: [] }];
    }
    result.user[el.user][0].city.push(el.city);
    return result;
  },
  { user: {} }
);

console.log(data2);


来源: stackexchange

问:
TypeError: order is undefined
I'm very new to react-redux following this tutorial to create ecomme website ,so here's a order screen to place a payment after hitting the place order button but it is showing error saying 'order' is undefined
this is my OrderScreen.js i've tried adding order && in front of order but to no avail it return screen with no listed order items

```<code>import React ,{useEffect,useState}from 'react'
import { Link } from 'react-router-dom'
import { useDispatch,useSelector } from 'react-redux'
import { Row,Col,ListGroup,Image,Card,Button } from 'react-bootstrap'
import Loader from '../components/Loader'
import Message from '../components/Message'
import { getOrderDetails } from '../actions/orderActions'
//import axios from 'axios'
function OrderScreen({match}) {
    const orderId=match.params.id
    const orderDetails=useSelector(state=>state.orderDetails)
    const{order,error,loading}=orderDetails

    const dispatch = useDispatch()

    if (!loading && !error){
        order.itemsPrice=order.orderItems.reduce((acc,item)=>acc+item.price*item.qty,0).toFixed(2)

    }

    useEffect(()=>{

        if ( !order || order._id !== Number(orderId)){
            dispatch (getOrderDetails(orderId))
        }

    },[dispatch,order,orderId])

    return (
        <div>

            <Col md={8}>
                <ListGroup variant='flush'>
                    <ListGroup.Item>
                        <h2>Shipping</h2>
                        <p>
                            <strong>Shipping:</strong>
                            { order.shippingAddress.address},{ order.shippingAddress.city}
                            {' '}
                            { order.shippingAddress.postalCode},
                            {' '}
                            { order.shippingAddress.country}
                        </p>
                    </ListGroup.Item>

                    <ListGroup.Item>
                        <h2>Payment Method</h2>
                        <p>
                            <strong>Method:</strong>
                            { order.paymentMethod}

                        </p>
                    </ListGroup.Item>

                    <ListGroup.Item>
                        <h2>Order Items</h2>
                       {order.orderItems.length===0 ?
                      <h3>Your order is empty</h3>
                    :(
                        <ListGroup varaint='flush'>
                            { order.orderItems.map((item,index)=>
                                <ListGroup.Item key={index}>
                                    <Row>
                                        <Col md={2}>
                                        <Image src={item.image} alt={item.name} fluid rounded/>
                                        </Col>

                                        <Col>
                                        <Link to={`/product/${item.product}`}>{item.name}</Link>
                                        </Col>
                                        <Col md={4}>
                                            {item.qty} X ${item.price}=${(item.qty*item.price).toFixed(2)}
                                        </Col>
                                    </Row>
                                </ListGroup.Item>
                            )}
                        </ListGroup>
                    )}
                    </ListGroup.Item>
                </ListGroup>
            </Col>

            <Col md={4}>
                <Card>
                    <ListGroup variant='flush'>
                                <ListGroup.Item>
                                    <h2>Order Summary</h2>
                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Item:</Col>
                                        <Col>${  order.itemsPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Shipping:</Col>
                                        <Col>${ order.shippingPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Shipping:</Col>
                                        <Col>${ order.taxPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Total:</Col>
                                        <Col>${ order.totalPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                    </ListGroup>
                </Card>
            </Col>
        </div>
    )
}

export default OrderScreen
</code>```

heres my reducer for order:

```<code>export const orderDetailsReducer = (state = { loading: true, orderItems: [], shippingAddress: {} }, action) => {
    switch (action.type) {
        case ORDER_DETAILS_REQUEST:
            return {
                ...state,
                loading: true
            }

        case ORDER_DETAILS_SUCCESS:
            return {
                loading: false,
                order: action.payload
            }

        case ORDER_DETAILS_FAIL:
            return {
                loading: false,
                error: action.payload
            }
        default:
            return state
    }
}
</code>```

here's my action for order:

```<code>export const getOrderDetails = (id) => async (dispatch, getState) => {
    try {
        dispatch({
            type: ORDER_DETAILS_REQUEST
        })

        const {
            userLogin: { userInfo },
        } = getState()

        const config = {
            headers: {
                'Content-type': 'application/json',
                Authorization: `Bearer ${userInfo.token}`
            }
        }

        const { data } = await axios.get(
            `/api/orders/${id}/`,
            config
        )

        dispatch({
            type: ORDER_DETAILS_SUCCESS,
            payload: data
        })

    } catch (error) {
        dispatch({
            type: ORDER_DETAILS_FAIL,
            payload: error.response && error.response.data.detail
                ? error.response.data.detail
                : error.message,
        })
    }
}
</code>```

here's my django view to get orders by id:

```<code>@api_view(['GET'])
@permission_classes([IsAuthenticated])
def getOrderById(request, pk):

    user = request.user

    try:
        order = Order.objects.get(_id=pk)
        if user.is_staff or order.user == user:
            serializer = OrderSerializer(order, many=False)
            return Response(serializer.data)
        else:
            Response({'detail': 'Not authorized to view this order'},
                     status=status.HTTP_400_BAD_REQUEST)
    except:
        return Response({'detail': 'Order does not exist'}, status=status.HTTP_400_BAD_REQUEST)
</code>```

i've used the combine reducer to combine the remaining reducer the one that ive used in this que is :

```<code>orderDetails: orderDetailsReducer,
</code>```

constants i've used for state:

```<code>export const ORDER_DETAILS_REQUEST = 'ORDER_DETAILS_REQUEST'
export const ORDER_DETAILS_SUCCESS = 'ORDER_DETAILS_SUCCESS'
export const ORDER_DETAILS_FAIL = 'ORDER_DETAILS_FAIL'
</code>```

django url path:

```<code>path('<str:pk>/', views.getOrderById, name='user-order'),
</code>```

enter image description here

答: I solved my issue with change "order.shippingAddress" to "order.ShippingAddress", I just check out the file models.py in the base folder and find out the exact name that is ShippingAddress, then try to run makemigrations and migrate. hope it's help.</p>

ContentLicense: CC BY-SA 4.0

Title: TypeError: order is undefined

Body:
I'm very new to react-redux following this tutorial to create ecomme website ,so here's a order screen to place a payment after hitting the place order button but it is showing error saying 'order' is undefined
this is my OrderScreen.js i've tried adding order && in front of order but to no avail it return screen with no listed order items

import React ,{useEffect,useState}from 'react'
import { Link } from 'react-router-dom'
import { useDispatch,useSelector } from 'react-redux'
import { Row,Col,ListGroup,Image,Card,Button } from 'react-bootstrap'
import Loader from '../components/Loader'
import Message from '../components/Message'
import { getOrderDetails } from '../actions/orderActions'
//import axios from 'axios'
function OrderScreen({match}) {
    const orderId=match.params.id
    const orderDetails=useSelector(state=>state.orderDetails)
    const{order,error,loading}=orderDetails

    const dispatch = useDispatch()

    if (!loading && !error){
        order.itemsPrice=order.orderItems.reduce((acc,item)=>acc+item.price*item.qty,0).toFixed(2)

    }

    useEffect(()=>{

        if ( !order || order._id !== Number(orderId)){
            dispatch (getOrderDetails(orderId))
        }

    },[dispatch,order,orderId])

    return (

            <Col md={8}>
                <ListGroup variant='flush'>
                    <ListGroup.Item>

Shipping

                            Shipping:
                            { order.shippingAddress.address},{ order.shippingAddress.city}
                            {' '}
                            { order.shippingAddress.postalCode},
                            {' '}
                            { order.shippingAddress.country}

                    </ListGroup.Item>

                    <ListGroup.Item>

Payment Method

                            Method:
                            { order.paymentMethod}

                    </ListGroup.Item>

                    <ListGroup.Item>

Order Items

                       {order.orderItems.length===0 ?

Your order is empty

                    :(
                        <ListGroup varaint='flush'>
                            { order.orderItems.map((item,index)=>
                                <ListGroup.Item key={index}>
                                    <Row>
                                        <Col md={2}>
                                        <Image src={item.image} alt={item.name} fluid rounded/>
                                        </Col>

                                        <Col>
                                        <Link to={`/product/${item.product}`}>{item.name}</Link>
                                        </Col>
                                        <Col md={4}>
                                            {item.qty} X ${item.price}=${(item.qty*item.price).toFixed(2)}
                                        </Col>
                                    </Row>
                                </ListGroup.Item>
                            )}
                        </ListGroup>
                    )}
                    </ListGroup.Item>
                </ListGroup>
            </Col>

            <Col md={4}>
                <Card>
                    <ListGroup variant='flush'>
                                <ListGroup.Item>

Order Summary

                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Item:</Col>
                                        <Col>${  order.itemsPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Shipping:</Col>
                                        <Col>${ order.shippingPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Shipping:</Col>
                                        <Col>${ order.taxPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                                <ListGroup.Item>
                                    <Row>
                                        <Col>Total:</Col>
                                        <Col>${ order.totalPrice}</Col>
                                    </Row>
                                </ListGroup.Item>

                    </ListGroup>
                </Card>
            </Col>

    )
}

export default OrderScreen

heres my reducer for order:

export const orderDetailsReducer = (state = { loading: true, orderItems: [], shippingAddress: {} }, action) => {
    switch (action.type) {
        case ORDER_DETAILS_REQUEST:
            return {
                ...state,
                loading: true
            }

        case ORDER_DETAILS_SUCCESS:
            return {
                loading: false,
                order: action.payload
            }

        case ORDER_DETAILS_FAIL:
            return {
                loading: false,
                error: action.payload
            }
        default:
            return state
    }
}

here's my action for order:

export const getOrderDetails = (id) => async (dispatch, getState) => {
    try {
        dispatch({
            type: ORDER_DETAILS_REQUEST
        })

        const {
            userLogin: { userInfo },
        } = getState()

        const config = {
            headers: {
                'Content-type': 'application/json',
                Authorization: `Bearer ${userInfo.token}`
            }
        }

        const { data } = await axios.get(
            `/api/orders/${id}/`,
            config
        )

        dispatch({
            type: ORDER_DETAILS_SUCCESS,
            payload: data
        })

    } catch (error) {
        dispatch({
            type: ORDER_DETAILS_FAIL,
            payload: error.response && error.response.data.detail
                ? error.response.data.detail
                : error.message,
        })
    }
}

here's my django view to get orders by id:

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def getOrderById(request, pk):

    user = request.user

    try:
        order = Order.objects.get(_id=pk)
        if user.is_staff or order.user == user:
            serializer = OrderSerializer(order, many=False)
            return Response(serializer.data)
        else:
            Response({'detail': 'Not authorized to view this order'},
                     status=status.HTTP_400_BAD_REQUEST)
    except:
        return Response({'detail': 'Order does not exist'}, status=status.HTTP_400_BAD_REQUEST)

i've used the combine reducer to combine the remaining reducer the one that ive used in this que is :

orderDetails: orderDetailsReducer,

constants i've used for state:

export const ORDER_DETAILS_REQUEST = 'ORDER_DETAILS_REQUEST'
export const ORDER_DETAILS_SUCCESS = 'ORDER_DETAILS_SUCCESS'
export const ORDER_DETAILS_FAIL = 'ORDER_DETAILS_FAIL'

django url path:

path('<str:pk>/', views.getOrderById, name='user-order'),

enter image description here


问:
Write svg latex into a canvas html
My goal is to record maths scripts running on the canvas and at the same time record sound from the mic (I am a math teacher). I would like very much to allow latex formulas. Of course latex formulas do not write directly to canvas. MathJax can produce SVG elements. I wonder if it is possible to go from SVG->image->canvas, using javascript. I don't care if the obtained image on canvas is a little blured.
I couldn't find good examples of this yet on the internet.
Thanks!</p>

答:
Indeed that's possible. The trick here is to grab the SVG output of MathJax and draw it to a temporary  element, which in-turn is drawn to an on-screen canvas afterwards.

The actual <svg> element is a children of the <mjx-container> element returned by a call to MathJax's tex2svg() method.

Here's an example:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let equation = "x = \\sin \\left( \\frac{\\pi}{2} \\right)";
let svg = MathJax.tex2svg(equation).firstElementChild;

let img = document.createElement('img');
img.onload = (e) => {
  let tempWidth = e.target.naturalWidth;
  let tempHeight = e.target.naturalHeight;
  ctx.drawImage(e.target, canvas.width / 2 - tempWidth / 2, canvas.height / 2 - tempHeight / 2, tempWidth, tempHeight)
}
img.src = 'data:image/svg+xml;base64,' + btoa('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n' + svg.outerHTML);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  background-color: #eeeeee;
}</code>```

<canvas id="canvas"></canvas>```

Title: Write svg latex into a canvas html

Body:
Indeed that's possible. The trick here is to grab the SVG output of MathJax and draw it to a temporary <img> element, which in-turn is drawn to an on-screen canvas afterwards.

The actual <svg> element is a children of the <mjx-container> element returned by a call to MathJax's tex2svg() method.

Here's an example:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let equation = "x = \\sin \\left( \\frac{\\pi}{2} \\right)";
let svg = MathJax.tex2svg(equation).firstElementChild;

let img = document.createElement('img');
img.onload = (e) => {
  let tempWidth = e.target.naturalWidth;
  let tempHeight = e.target.naturalHeight;
  ctx.drawImage(e.target, canvas.width / 2 - tempWidth / 2, canvas.height / 2 - tempHeight / 2, tempWidth, tempHeight)
}
img.src = 'data:image/svg+xml;base64,' + btoa('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n' + svg.outerHTML);

#canvas {
  background-color: #eeeeee;
}

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js" type="text/javascript"></script>
<canvas id="canvas"></canvas>


问:
Android: How To: mark the current location into a map (still image) - SOURCE CODE,TESTCASE,ACTUAL,EXPECTED OUTPUT ADDED
I have created another question (How to display a map (still image file) with a moving current location)

But it contains 2 (two) questions, so i need to segregate it.

I am trying to create a prototype that could guide a person to his destination place.

place is a wide building with several floors.

i can obtain/retrieve the maps (still images). e.g. current:1F destination:5F; so I can get the still images of 1st,2nd...5th floors (5 image files).

Scenario:

start the application

input the current location (or may automatically set using current location) & destination

click the search route button to search the maps to use (still images) & mark the current location & destination

update the current location upon moving/going to destination

Problem:
I can get the current location coordinate via WiFi/cell tower/ip address but don't know how to put it into still image to mark the current location.

Would you share the concepts/ideas or include the code snippets. Big Help with my thesis.

Any guidance on the right direction is appreciated.

UPDATE

Actual Example with Actual,Expected Output,Test Case
(parcel of codes here has gotten from mapsforge)

MercatorProjectionClass.java

```<code>/**
 * A performance optimized implementation of the spherical Mercator projection.
 */
class MercatorProjectionClass {
    /**
     * Width and height of a map tile in pixel.
     */
    static final int TILE_SIZE = 256;

    /**
     * Converts a latitude coordinate (in degrees) to a pixel Y coordinate at a certain zoom level.
     *
     * @param latitude
     *            the latitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the pixel Y coordinate of the latitude value.
     */
    static double latitudeToPixelY(double latitude, byte zoom) {
        double sinLatitude = Math.sin(latitude * (Math.PI / 180));
        return (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI))
                * ((long) TILE_SIZE << zoom);
    }

    /**
     * Converts a latitude coordinate (in degrees) to a tile Y number at a certain zoom level.
     *
     * @param latitude
     *            the latitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile Y number of the latitude value.
     */
    static long latitudeToTileY(double latitude, byte zoom) {
        return pixelYToTileY(latitudeToPixelY(latitude, zoom), zoom);
    }

    /**
     * Converts a longitude coordinate (in degrees) to a pixel X coordinate at a certain zoom level.
     *
     * @param longitude
     *            the longitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the pixel X coordinate of the longitude value.
     */
    static double longitudeToPixelX(double longitude, byte zoom) {
        return (longitude + 180) / 360 * ((long) TILE_SIZE << zoom);
    }

    /**
     * Converts a longitude coordinate (in degrees) to the tile X number at a certain zoom level.
     *
     * @param longitude
     *            the longitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile X number of the longitude value.
     */
    static long longitudeToTileX(double longitude, byte zoom) {
        return pixelXToTileX(longitudeToPixelX(longitude, zoom), zoom);
    }

    /**
     * Converts a pixel X coordinate at a certain zoom level to a longitude coordinate.
     *
     * @param pixelX
     *            the pixel X coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the longitude value of the pixel X coordinate.
     */
    static double pixelXToLongitude(double pixelX, byte zoom) {
        return 360 * ((pixelX / ((long) TILE_SIZE << zoom)) - 0.5);
    }

    /**
     * Converts a pixel X coordinate to the tile X number.
     *
     * @param pixelX
     *            the pixel X coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile X number.
     */
    static long pixelXToTileX(double pixelX, byte zoom) {
        return (long) Math.min(Math.max(pixelX / TILE_SIZE, 0), Math.pow(2, zoom) - 1);
    }

    /**
     * Converts a pixel Y coordinate at a certain zoom level to a latitude coordinate.
     *
     * @param pixelY
     *            the pixel Y coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the latitude value of the pixel Y coordinate.
     */
    static double pixelYToLatitude(double pixelY, byte zoom) {
        double y = 0.5 - (pixelY / ((long) TILE_SIZE << zoom));
        return 90 - 360 * Math.atan(Math.exp(-y * (2 * Math.PI))) / Math.PI;
    }

    /**
     * Converts a pixel Y coordinate to the tile Y number.
     *
     * @param pixelY
     *            the pixel Y coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile Y number.
     */
    static long pixelYToTileY(double pixelY, byte zoom) {
        return (long) Math.min(Math.max(pixelY / TILE_SIZE, 0), Math.pow(2, zoom) - 1);
    }

    private static final byte ZOOM_LEVEL = 14;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // Pixel Coordinate of Chicago,IL
        double pixel_y = 1559345;
        double pixel_x = 1075954;
        // Lat Lng of Chicago,IL
        double lat_y = 41.850033;
        double lng_x = -87.65005229999997;

        testPixelXYToLatitude(pixel_y, pixel_x, lat_y, lng_x);
        testLatLngToPixelXY(pixel_y, pixel_x, lat_y, lng_x);
    }

    private static void testPixelXYToLatitude(
            double pixel_y, double pixel_x,
            double lat_y, double lng_x) {

        double actual_lat_y = MercatorProjectionClass.pixelYToLatitude(pixel_y, ZOOM_LEVEL);
        double actual_lng_x = MercatorProjectionClass.pixelXToLongitude(pixel_x, ZOOM_LEVEL);

        String expectedstr_lat_y = Double.toString(lat_y).substring(0, 5);
        String expectedstr_lng_x = Double.toString(lng_x).substring(0, 6);

        String actualstr_lat_y = Double.toString(actual_lat_y).substring(0, 5);
        String actualstr_lng_x = Double.toString(actual_lng_x).substring(0, 6);

        String result = (actualstr_lat_y.equals(expectedstr_lat_y) && actualstr_lng_x.equals(expectedstr_lng_x))?"PASSED":"FAILED";
        System.out.println("PixelXYToLatitude test result:" + result);
    }

    private static void testLatLngToPixelXY(
            double pixel_y, double pixel_x,
            double lat_y, double lng_x) {

        double actual_pixel_y = MercatorProjectionClass.latitudeToPixelY(lat_y, ZOOM_LEVEL);
        double actual_pixel_x = MercatorProjectionClass.longitudeToPixelX(lng_x, ZOOM_LEVEL);

        String expectedstr_pixel_y = Integer.toString((Double.valueOf(pixel_y).intValue()));
        String expectedstr_pixel_x = Integer.toString((Double.valueOf(pixel_x).intValue()));

        String actualstr_pixel_y = Integer.toString(Double.valueOf(actual_pixel_y).intValue());
        String actualstr_pixel_x = Integer.toString(Double.valueOf(actual_pixel_x).intValue());

        String result = (actualstr_pixel_y.equals(expectedstr_pixel_y) && actualstr_pixel_x.equals(expectedstr_pixel_x))?"PASSED":"FAILED";
        System.out.println("LatLngToPixelXY test result:" + result);
    }
}
</code>```

Output of the above code:

PixelXYToLatitude test result:PASSED

LatLngToPixelXY test result:PASSED

I have already the projection class to convert LatLng to Pixel.
My Problem now is on how to mark into still image of a given LatLng using the above class.

Here's my still image (Chicago,IL):

I want to put a mark (here's the example but later on need to change the balloon to smaller pointer)

答:
From what I understood, you are facing a few problems here.

Use a map controller with offline tiles

Mark the current location on the map

Route the user from point A to point B

Map controller

Basically, the location providers on Android will be feeding your application with some global positioning coordinates (longitude and latitude) and you want to put a background behind it so that the user has a visual on his location. Your idea to put a still image there is right, but a correction I would suggest (and this is the way it works on every commercial, or non-commercial, product) is to split the large images into smaller parts, so that the map controller wouldn't have to load a large image into memory. 512 x 512 sounds like a reasonable size (Google maps uses 256 x 256). These chunks of larger images are called tiles.

With Google maps it's impossible to use offline tiles. I've written a post on how to do that for Google maps with OSMDroid (this is the best open source alternative) and another post with ArcGIS (free map controller for Android, commercial map tiles; everything is awesome with this controller but in my opinion it's too loaded for a thesis project).

So, the steps to reproduce here are:

chunk big files into smaller parts

find the exact coordinates of the edges of your big images to know exactly how to name the tiles (map controllers find tiles required to cover a portion of the viewport by names)

implement an offline tile provider with your images

Location provider

This, in my opinion is the hardest part. How exactly are you going to find the exact position of a device in a building? GPS can be of a help to a certain extent, but it can't be precise in a building anyway. ArcGIS provides you with a very nice built-in location provider, on any other solution you'll have to implement it on your own. As soon as you manage to overcome this problem you can also use the altitude provided by the location providers to switch between the floors automatically.

Routing

To represent a routing line with OSMDroid (well, with ArcGIS as well) is a piece of chocolate cake: create an array of turn points, draw a line from one point to another and put that line on the map. The hard part is to create a routing algorithm, good luck with that!

ContentLicense: CC BY-SA 3.0

Body:
I have created another question (How to display a map (still image file) with a moving current location)

But it contains 2 (two) questions, so i need to segregate it.

I am trying to create a prototype that could guide a person to his destination place.

place is a wide building with several floors.

i can obtain/retrieve the maps (still images). e.g. current:1F destination:5F; so I can get the still images of 1st,2nd...5th floors (5 image files).

Scenario:

start the application

input the current location (or may automatically set using current location) & destination

click the search route button to search the maps to use (still images) & mark the current location & destination

update the current location upon moving/going to destination

Problem:
I can get the current location coordinate via WiFi/cell tower/ip address but don't know how to put it into still image to mark the current location.

Would you share the concepts/ideas or include the code snippets. Big Help with my thesis.

Any guidance on the right direction is appreciated.

UPDATE

Actual Example with Actual,Expected Output,Test Case
(parcel of codes here has gotten from mapsforge)

MercatorProjectionClass.java

/**
 * A performance optimized implementation of the spherical Mercator projection.
 */
class MercatorProjectionClass {
    /**
     * Width and height of a map tile in pixel.
     */
    static final int TILE_SIZE = 256;

    /**
     * Converts a latitude coordinate (in degrees) to a pixel Y coordinate at a certain zoom level.
     *
     * @param latitude
     *            the latitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the pixel Y coordinate of the latitude value.
     */
    static double latitudeToPixelY(double latitude, byte zoom) {
        double sinLatitude = Math.sin(latitude * (Math.PI / 180));
        return (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI))
                * ((long) TILE_SIZE << zoom);
    }

    /**
     * Converts a latitude coordinate (in degrees) to a tile Y number at a certain zoom level.
     *
     * @param latitude
     *            the latitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile Y number of the latitude value.
     */
    static long latitudeToTileY(double latitude, byte zoom) {
        return pixelYToTileY(latitudeToPixelY(latitude, zoom), zoom);
    }

    /**
     * Converts a longitude coordinate (in degrees) to a pixel X coordinate at a certain zoom level.
     *
     * @param longitude
     *            the longitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the pixel X coordinate of the longitude value.
     */
    static double longitudeToPixelX(double longitude, byte zoom) {
        return (longitude + 180) / 360 * ((long) TILE_SIZE << zoom);
    }

    /**
     * Converts a longitude coordinate (in degrees) to the tile X number at a certain zoom level.
     *
     * @param longitude
     *            the longitude coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile X number of the longitude value.
     */
    static long longitudeToTileX(double longitude, byte zoom) {
        return pixelXToTileX(longitudeToPixelX(longitude, zoom), zoom);
    }

    /**
     * Converts a pixel X coordinate at a certain zoom level to a longitude coordinate.
     *
     * @param pixelX
     *            the pixel X coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the longitude value of the pixel X coordinate.
     */
    static double pixelXToLongitude(double pixelX, byte zoom) {
        return 360 * ((pixelX / ((long) TILE_SIZE << zoom)) - 0.5);
    }

    /**
     * Converts a pixel X coordinate to the tile X number.
     *
     * @param pixelX
     *            the pixel X coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile X number.
     */
    static long pixelXToTileX(double pixelX, byte zoom) {
        return (long) Math.min(Math.max(pixelX / TILE_SIZE, 0), Math.pow(2, zoom) - 1);
    }

    /**
     * Converts a pixel Y coordinate at a certain zoom level to a latitude coordinate.
     *
     * @param pixelY
     *            the pixel Y coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the latitude value of the pixel Y coordinate.
     */
    static double pixelYToLatitude(double pixelY, byte zoom) {
        double y = 0.5 - (pixelY / ((long) TILE_SIZE << zoom));
        return 90 - 360 * Math.atan(Math.exp(-y * (2 * Math.PI))) / Math.PI;
    }

    /**
     * Converts a pixel Y coordinate to the tile Y number.
     *
     * @param pixelY
     *            the pixel Y coordinate that should be converted.
     * @param zoom
     *            the zoom level at which the coordinate should be converted.
     * @return the tile Y number.
     */
    static long pixelYToTileY(double pixelY, byte zoom) {
        return (long) Math.min(Math.max(pixelY / TILE_SIZE, 0), Math.pow(2, zoom) - 1);
    }

    private static final byte ZOOM_LEVEL = 14;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // Pixel Coordinate of Chicago,IL
        double pixel_y = 1559345;
        double pixel_x = 1075954;
        // Lat Lng of Chicago,IL
        double lat_y = 41.850033;
        double lng_x = -87.65005229999997;

        testPixelXYToLatitude(pixel_y, pixel_x, lat_y, lng_x);
        testLatLngToPixelXY(pixel_y, pixel_x, lat_y, lng_x);
    }

    private static void testPixelXYToLatitude(
            double pixel_y, double pixel_x,
            double lat_y, double lng_x) {

        double actual_lat_y = MercatorProjectionClass.pixelYToLatitude(pixel_y, ZOOM_LEVEL);
        double actual_lng_x = MercatorProjectionClass.pixelXToLongitude(pixel_x, ZOOM_LEVEL);

        String expectedstr_lat_y = Double.toString(lat_y).substring(0, 5);
        String expectedstr_lng_x = Double.toString(lng_x).substring(0, 6);

        String actualstr_lat_y = Double.toString(actual_lat_y).substring(0, 5);
        String actualstr_lng_x = Double.toString(actual_lng_x).substring(0, 6);

        String result = (actualstr_lat_y.equals(expectedstr_lat_y) && actualstr_lng_x.equals(expectedstr_lng_x))?"PASSED":"FAILED";
        System.out.println("PixelXYToLatitude test result:" + result);
    }

    private static void testLatLngToPixelXY(
            double pixel_y, double pixel_x,
            double lat_y, double lng_x) {

        double actual_pixel_y = MercatorProjectionClass.latitudeToPixelY(lat_y, ZOOM_LEVEL);
        double actual_pixel_x = MercatorProjectionClass.longitudeToPixelX(lng_x, ZOOM_LEVEL);

        String expectedstr_pixel_y = Integer.toString((Double.valueOf(pixel_y).intValue()));
        String expectedstr_pixel_x = Integer.toString((Double.valueOf(pixel_x).intValue()));

        String actualstr_pixel_y = Integer.toString(Double.valueOf(actual_pixel_y).intValue());
        String actualstr_pixel_x = Integer.toString(Double.valueOf(actual_pixel_x).intValue());

        String result = (actualstr_pixel_y.equals(expectedstr_pixel_y) && actualstr_pixel_x.equals(expectedstr_pixel_x))?"PASSED":"FAILED";
        System.out.println("LatLngToPixelXY test result:" + result);
    }
}

Output of the above code:

PixelXYToLatitude test result:PASSED

LatLngToPixelXY test result:PASSED

I have already the projection class to convert LatLng to Pixel.
My Problem now is on how to mark into still image of a given LatLng using the above class.

Here's my still image (Chicago,IL):

I want to put a mark (here's the example but later on need to change the balloon to smaller pointer)


问:
Docker Desktop installation on WIndows causes InetAddress.getLocalhost().getCanonicalHostname() to return host.docker.internal
I'm using a Windows machine with Docker Desktop installed. My project does not live inside a docker container.

But as evident to https://youtrack.jetbrains.com/issue/IDEA-263484, it seems that Docker Desktop has overridden my host file to function properly, and the following code now returns an incorrect hostname.

InetAddress.getLocalhost().getCanonicalHostname() // host.docker.internal
```
<p>This is my host file</p>
```#...
# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost
# Added by Docker Desktop
192.168.128.75 host.docker.internal
192.168.128.75 gateway.docker.internal
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
```

Is there another standard method (that is cross-platform) to detect real machine hostname that works with Docker Desktop installations?

As mentioned in the linked issue and in Rob's answer, I could probably add an entry in my host file to mitigate this issue, but this might not work too well if the IP gets changed, and requires additional setup.

答: It looks like getCanonicalHostname() takes the first entry for your IP address. It's not the best solution, but if you add an entry for 192.168.128.75 above the one for host.docker.internal, that one gets picked up.

Body:
I'm using a Windows machine with Docker Desktop installed. My project does not live inside a docker container.

But as evident to https://youtrack.jetbrains.com/issue/IDEA-263484, it seems that Docker Desktop has overridden my host file to function properly, and the following code now returns an incorrect hostname.

InetAddress.getLocalhost().getCanonicalHostname() // host.docker.internal

This is my host file

#...
# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost
# Added by Docker Desktop
192.168.128.75 host.docker.internal
192.168.128.75 gateway.docker.internal
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section

Is there another standard method (that is cross-platform) to detect real machine hostname that works with Docker Desktop installations?

As mentioned in the linked issue and in Rob's answer, I could probably add an entry in my host file to mitigate this issue, but this might not work too well if the IP gets changed, and requires additional setup.


问:
Laravel : method is not supported for this route
the error is : The GET method is not supported for this route. Supported methods: POST.
although the website works on localhost but on the server doesnt work ?? any solutions

```<code>
 protected function methodNotAllowed(array $others, $method)
    {
        throw new MethodNotAllowedHttpException(
            $others,
            sprintf(
                'The %s method is not supported for this route. Supported methods: %s.',
                $method,
                implode(', ', $others)
            )
        );
    }

</code>```

layout

```<code>@extends('install.layout')

@section('content')
<div class="panel panel-default">
  <div class="panel-heading text-center">Login Details</div>
    <div class="panel-body">
       <div class="col-md-12">
            @if ($errors->any())
                <div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    @foreach ($errors->all() as $error)
                       <p>{{ $error }}</p>
                    @endforeach
                </div>
            @endif
            <form action="{{ url('install/store_user') }}" method="post" autocomplete="off">
                {{ csrf_field() }}
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name" value="{{ old('name') }}" required>
                </div>

                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" name="email" value="{{ old('email') }}" required>
                </div>

                <div class="form-group">
                    <label>Password</label>
                    <input type="password" class="form-control" name="password" required>
                </div>
                <button type="submit" class="btn btn-install">Next</button>
            </form>
       </div>
    </div>
</div>
@endsection

</code>```

########################################################################################################################################################
Web Route

```<code><?php
Route::post('install/store_user', 'Install\InstallController@store_user');
?>
</code>```

installController

```<code>    public function store_user(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191',
            'email' => 'required|string|email|max:191|unique:users',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
                return redirect()->back()
                            ->withErrors($validator)
                            ->withInput();
        }

        $name = $request->name;
        $email = $request->email;
        $password = Hash::make($request->password);

        Installer::createUser($name, $email, $password);

        return redirect('install/system_settings');
    }

</code>```

答:
most likely it's because of your URL in the form change your form

from

```<code><form action="{{ url('install/store_user') }}" method="post" autocomplete="off">
</code>```

to

```<code><form action="{{ url('install,store_user') }}" method="post" autocomplete="off">
</code>```

Body:
the error is : The GET method is not supported for this route. Supported methods: POST.
although the website works on localhost but on the server doesnt work ?? any solutions

 protected function methodNotAllowed(array $others, $method)
    {
        throw new MethodNotAllowedHttpException(
            $others,
            sprintf(
                'The %s method is not supported for this route. Supported methods: %s.',
                $method,
                implode(', ', $others)
            )
        );
    }

layout

@extends('install.layout')

@section('content')

Login Details

            @if ($errors->any())

                    ×
                    @foreach ($errors->all() as $error)

{{ $error }}

                    @endforeach

            @endif
            <form action="{{ url('install/store_user') }}" method="post" autocomplete="off">
                {{ csrf_field() }}

                    Name
                    <input type="text" class="form-control" name="name" value="{{ old('name') }}" required>

                    Email
                    <input type="email" class="form-control" name="email" value="{{ old('email') }}" required>

                    Password
                    <input type="password" class="form-control" name="password" required>

                <button type="submit" class="btn btn-install">Next</button>
            </form>

@endsection

########################################################################################################################################################
Web Route

<?php
Route::post('install/store_user', 'Install\InstallController@store_user');
?>

installController

    public function store_user(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191',
            'email' => 'required|string|email|max:191|unique:users',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
                return redirect()->back()
                            ->withErrors($validator)
                            ->withInput();
        }

        $name = $request->name;
        $email = $request->email;
        $password = Hash::make($request->password);

        Installer::createUser($name, $email, $password);

        return redirect('install/system_settings');
    }

Body:
most likely it's because of your URL in the form change your form

from

<form action="{{ url('install/store_user') }}" method="post" autocomplete="off">

to

<form action="{{ url('install,store_user') }}" method="post" autocomplete="off">


问:
CMD search for specific line in output
I'm trying to make a little progrmm in c# which runs commands in CMD.
Everything is fine and in the output of the command is a list with a lot of useless information. Exept one line. This line, I want to 'filter' out and only display this.
So is ther a way I can make this happen?
Thanks for any suggestions.</p>

答:
Just launch your program in commandline and add | findstr "pattern" after it.

By "pattern", I mean something you can use to find that line, e.g. if your program prints a list of cats (ocelot, puma, lion, tiger) and you want to see the lion, you punt | findstr "lion". Don't forget that findstr is case sensitive, you might need the /I switch, like this: | findstr /I "LION".

For more information, type findstr /? in your commandline.

Title: CMD search for specific line in output


问:
Failed to load resource: the server responded with a status of 500. Deployed react app with vercel
Hello I have error on deployed version of max app. App is deployed with vercel and when I click login in button in application I receive this error "Server error There is a problem with the server configuration. Check the server logs for more information."error1

When I check console in console can see this message "Failed to load resource: the server responded with a status of 500 ()"

My code for authentication is this

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
  pages: {
    signIn: "/auth/signin",
  },
  callbacks: {
    async session({ session, token, user }) {
      session.user.username = session.user.name
        .split(" ")
        .join("")
        .toLocaleLowerCase();

      session.user.uid = token.sub;
      return session;
    },
  },
});```
</div>
</div>
</p>
<p>Code for login page is this</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { getProviders, signIn as SignIntoProvider } from "next-auth/react";
import Header from "../../components/Header";

function signIn({ providers }) {
  return (
    <>
      <Header />
      <div className="flex flex-col items-center justify-center min-h-screen py-2 -mt-55 px-14 text-center">
        <img className="w-80" src="http://links.papareact.com/ocw" alt="" />
        <p className="font-xs italic">
          This is not a REAL app, it is built for educational purposes only
        </p>

        <div className="mt-40">
          {Object.values(providers).map((provider) => (
            <div key={provider.name}>
              <button
                className="p-3 bg-blue-500 rounded-lg text-white"
                onClick={() => SignIntoProvider(provider.id, { callbackUrl: "/"})}
              >
                Sign in with {provider.name}
              </button>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

export async function getServerSideProps() {
  const providers = await getProviders();
  return {
    props: {
      providers,
    },
  };
}

export default signIn;</code>```

In localhost everything is good but in deployed version I receiving error.

Vercel log is

[GET] /api/auth/error
14:16:09:08
2021-12-22T13:16:09.140Z    e3d29912-86c7-49c8-91a9-ecb87758e1a9    ERROR   [next-auth][error][NO_SECRET]
https://next-auth.js.org/errors#no_secret Please define a `secret` in production. MissingSecret [MissingSecretError]: Please define a `secret` in production.
    at assertConfig (/var/task/node_modules/next-auth/core/lib/assert.js:24:14)
    at NextAuthHandler (/var/task/node_modules/next-auth/core/index.js:34:52)
    at NextAuthNextHandler (/var/task/node_modules/next-auth/next/index.js:16:51)
    at /var/task/node_modules/next-auth/next/index.js:52:38
    at Object.apiResolver (/var/task/node_modules/next/dist/server/api-utils.js:102:15)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async Server.handleApiRequest (/var/task/node_modules/next/dist/server/next-server.js:1064:9)
    at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:951:37)
    at async Router.execute (/var/task/node_modules/next/dist/server/router.js:222:32)
    at async Server.run (/var/task/node_modules/next/dist/server/next-server.js:1135:29) {
  code: 'NO_SECRET'
}```

答:
You should generate a NEXTAUTH_SECRET using this command 'openssl rand -base64 32' , add your NEXTAUTH_SECRET=generatedSecret to .env file and update your nextauth.js file.

```<code>import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
   providers: [
     GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
     }),
   ],
  secret: process.env.NEXTAUTH_SECRET,
});
</code>```

Check https://next-auth.js.org/configuration/options#secret for more information

Body:
Hello I have error on deployed version of max app. App is deployed with vercel and when I click login in button in application I receive this error "Server error There is a problem with the server configuration. Check the server logs for more information."error1

When I check console in console can see this message "Failed to load resource: the server responded with a status of 500 ()"

My code for authentication is this

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
  pages: {
    signIn: "/auth/signin",
  },
  callbacks: {
    async session({ session, token, user }) {
      session.user.username = session.user.name
        .split(" ")
        .join("")
        .toLocaleLowerCase();

      session.user.uid = token.sub;
      return session;
    },
  },
});

Code for login page is this

import { getProviders, signIn as SignIntoProvider } from "next-auth/react";
import Header from "../../components/Header";

function signIn({ providers }) {
  return (
    <>

          This is not a REAL app, it is built for educational purposes only

          {Object.values(providers).map((provider) => (

              <button
                className="p-3 bg-blue-500 rounded-lg text-white"
                onClick={() => SignIntoProvider(provider.id, { callbackUrl: "/"})}
              >
                Sign in with {provider.name}
              </button>

          ))}

    </>
  );
}

export async function getServerSideProps() {
  const providers = await getProviders();
  return {
    props: {
      providers,
    },
  };
}

export default signIn;

In localhost everything is good but in deployed version I receiving error.

Vercel log is

[GET] /api/auth/error
14:16:09:08
2021-12-22T13:16:09.140Z    e3d29912-86c7-49c8-91a9-ecb87758e1a9    ERROR   [next-auth][error][NO_SECRET]
https://next-auth.js.org/errors#no_secret Please define a `secret` in production. MissingSecret [MissingSecretError]: Please define a `secret` in production.
    at assertConfig (/var/task/node_modules/next-auth/core/lib/assert.js:24:14)
    at NextAuthHandler (/var/task/node_modules/next-auth/core/index.js:34:52)
    at NextAuthNextHandler (/var/task/node_modules/next-auth/next/index.js:16:51)
    at /var/task/node_modules/next-auth/next/index.js:52:38
    at Object.apiResolver (/var/task/node_modules/next/dist/server/api-utils.js:102:15)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async Server.handleApiRequest (/var/task/node_modules/next/dist/server/next-server.js:1064:9)
    at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:951:37)
    at async Router.execute (/var/task/node_modules/next/dist/server/router.js:222:32)
    at async Server.run (/var/task/node_modules/next/dist/server/next-server.js:1135:29) {
  code: 'NO_SECRET'
}

Body:
You should generate a NEXTAUTH_SECRET using this command 'openssl rand -base64 32' , add your NEXTAUTH_SECRET=generatedSecret to .env file and update your nextauth.js file.

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
   providers: [
     GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
     }),
   ],
  secret: process.env.NEXTAUTH_SECRET,
});

Check https://next-auth.js.org/configuration/options#secret for more information


问:
How to create a new text file on button click
Here is my problem:

I am developing a windows application

I am converting an image into text format, and saving it into a system location.

This is my code:

```<code>if (!System.IO.Directory.Exists("D:\\SaveImageOutPutFolder"))
{
    System.IO.Directory.CreateDirectory("D:\\SaveImageOutPutFolder");
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] +@"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("folder created and image output saved");
}
else
{
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + @"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}
</code>```

The problem is that it is not creating a new text file every time the button is clicked. It is writing to the same file. I want to create to a new txt file for every click.

Can anyboy help in this, and give me some sample code?

答:
To answer your immediate question -  you need to dynamically name the file. Since you're statically naming it with the "\Mytxtfile.txt" name, it's always going to be the same.

One option you could do is something like:

```<code>ConfigurationSettings.AppSettings["SaveImagefolderPath"] + "\\" + Guid.NewGuid().ToString() + ".txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
</code>```

Body:
Here is my problem:

I am developing a windows application

I am converting an image into text format, and saving it into a system location.

This is my code:

if (!System.IO.Directory.Exists("D:\\SaveImageOutPutFolder"))
{
    System.IO.Directory.CreateDirectory("D:\\SaveImageOutPutFolder");
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] +@"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("folder created and image output saved");
}
else
{
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + @"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}

The problem is that it is not creating a new text file every time the button is clicked. It is writing to the same file. I want to create to a new txt file for every click.

Can anyboy help in this, and give me some sample code?

Body:
To answer your immediate question -  you need to dynamically name the file. Since you're statically naming it with the "\Mytxtfile.txt" name, it's always going to be the same.

One option you could do is something like:

ConfigurationSettings.AppSettings["SaveImagefolderPath"] + "\\" + Guid.NewGuid().ToString() + ".txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);


问:
how to control tab key between buttons in react, javascript?
I have 3 buttons Cancel, Back, Continue respectively. when press tab key that should be going to Continue, Cancel, Back buttons.
 How can we do that in React, Javascript?
Please refer https://codesandbox.io/s/crazy-ishizaka-cnr5k?file=/src/App.js

```<code>export default function App() {
  return (
    <div className="App">
      <button tabIndex="2">submit 1</button>
      <button tabIndex="3">submit 2</button>
      <button tabIndex="1">submit 3</button>
    </div>
  );
}
</code>```

this above code is'nt working as I expected. Please suggest efficient solution for this.

答:
The first thing about the tabIndex is it would act weird for use if you want to jump directly to the buttons and inputs.
After some researches about your problem, I have found out you have to do two things:

The first one is you have to add all:initial to the root in your project style. for example in your case that the project is React, you have to add this to the index.html and change that like this:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />

    <title>React App</title>

      You need to enable JavaScript to run this app.

```
</div>
</div>
</p>
<p><em>I have changed the HTML tag and added the style in the second line</em></p>
<ol start="2">
<li>the second thing that you have to d is that you need to consider a side for the buttons that the index can go through it at first and then it can follow your order.
in my case, I have added this: (and know that the first tab would do nothing)</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export default function App() {
  return (
    <div className="App" tabIndex={1}>
      <button tabIndex={3}>submit 1</button>
      <button tabIndex={4}>submit 2</button>
      <button tabIndex={2}>submit 3</button>
    </div>
  );</code>```

I have forked your codesandbox and you can access it with this link:
https://codesandbox.io/s/dawn-hill-1br66?file=/src/App.js

Body:
I have 3 buttons Cancel, Back, Continue respectively. when press tab key that should be going to Continue, Cancel, Back buttons.
 How can we do that in React, Javascript?
Please refer https://codesandbox.io/s/crazy-ishizaka-cnr5k?file=/src/App.js

export default function App() {
  return (

      <button tabIndex="2">submit 1</button>
      <button tabIndex="3">submit 2</button>
      <button tabIndex="1">submit 3</button>

  );
}

this above code is'nt working as I expected. Please suggest efficient solution for this.

Body:
The first thing about the tabIndex is it would act weird for use if you want to jump directly to the buttons and inputs.
After some researches about your problem, I have found out you have to do two things:

The first one is you have to add all:initial to the root in your project style. for example in your case that the project is React, you have to add this to the index.html and change that like this:

<!DOCTYPE html>
<html lang="en" style="all: initial;">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />

    <title>React App</title>
  </head>

  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>

  </body>
</html>

I have changed the HTML tag and added the style in the second line

the second thing that you have to d is that you need to consider a side for the buttons that the index can go through it at first and then it can follow your order.
in my case, I have added this: (and know that the first tab would do nothing)

export default function App() {
  return (
    <div className="App" tabIndex={1}>
      <button tabIndex={3}>submit 1</button>
      <button tabIndex={4}>submit 2</button>
      <button tabIndex={2}>submit 3</button>
    </div>
  );

I have forked your codesandbox and you can access it with this link:
https://codesandbox.io/s/dawn-hill-1br66?file=/src/App.js


问:
Stop automatic change of updatedAt timestamp while using .save() in mongoose
I have a collection in which the documents have an autogenerated createdAt and updatedAt fields. Of course while updating any document, the updateAt timestamp also changes. I am aware of the { timestamps: false } flag that I can pass to my update query from mongoose 5.9.3 onwards, but I cannot use an update query for my current needs.

For certain computations I have to find the element first, make changes to some fields and then manually use document.save() method to update the document (Yes I am aware of the concurrency issues that I will face, I have taken care of that separately). My only issue here is that I don't want to update the updateAt timestamp when I'm doing a .save(). Can anybody tell me what's the correct way of doing it?

答:
Well I guess I should've read the documentation more carefully! You can actually pass in the same { timestamps: false } option in .save() as well and it will work just the way it does in an update query!

Mongoose is smart enough to track exact changes in your document and is able to construct an update query in the background for your operations, thus at the end of the day it's still a normal update

This piece of code should do the trick:

```<code>document.save({ timestamps: false })
</code>```

Body:
Well I guess I should've read the documentation more carefully! You can actually pass in the same { timestamps: false } option in .save() as well and it will work just the way it does in an update query!

Mongoose is smart enough to track exact changes in your document and is able to construct an update query in the background for your operations, thus at the end of the day it's still a normal update

This piece of code should do the trick:

document.save({ timestamps: false })


问:
Laravel Eloquent join if column null
I have two tables users/invoices in 1:n relation. When someone creats an invoice it saves the user_id. Also it's possible (optional) to set a manager (column: project_management_user_id). If there is no manager set (NULL), I want to get the user, who created the record. So for now I have this query. It gives me all invoices with the manager (but not that ones with manager = null.

```<code>$query = Invoice::join('users', 'invoices.project_management_user_id', '=', 'users.id')
                ->select('users.name as name', 'users.color as color',  DB::raw("count(invoices.id) as count"))
                ->get();
</code>```

Is it possible to add some if-clause like "if project_management_user_id is null, take the user_id"? I read about the whereNull() function, but it filters my whole query

答: Use leftJoin instead of join in the query.</p>

Title: Laravel Eloquent join if column null

Body:
I have two tables users/invoices in 1:n relation. When someone creats an invoice it saves the user_id. Also it's possible (optional) to set a manager (column: project_management_user_id). If there is no manager set (NULL), I want to get the user, who created the record. So for now I have this query. It gives me all invoices with the manager (but not that ones with manager = null.

$query = Invoice::join('users', 'invoices.project_management_user_id', '=', 'users.id')
                ->select('users.name as name', 'users.color as color',  DB::raw("count(invoices.id) as count"))
                ->get();

Is it possible to add some if-clause like "if project_management_user_id is null, take the user_id"? I read about the whereNull() function, but it filters my whole query


问:
During state change in React, is it possible to append values to URL
I was wondering, if, on state change, I can add something like this to URL

www.abc.com/?state=on

without page reloading.

答:
```<code>history.push({
  pathname: '/',
  search: '?state=on'
})
</code>```

You can use history.push and don't worry about your page reload.

https://v5.reactrouter.com/web/api/history

Body:
history.push({
  pathname: '/',
  search: '?state=on'
})

You can use history.push and don't worry about your page reload.

https://v5.reactrouter.com/web/api/history


问:
Flutter async/await doesn't work inside forEach
I don't know what is missing here.. This is a function which is suppose to place orders from customers. The whole logic is quite simple :

If 1 single item in the cart , just executes once. If there are more, appends the order to the first order number. But for some reason its not waiting till the orderRepo.addOrder execution is complete initially.

```<code>  dynamic firstOrderNumber = 0;
  var existingOrder = false;

  void addOrder(List<Cart> carts) async {        --> Coming to add the list of orders
    carts.forEach((_cart) async {                --> Going to add each items in cart

             x += 1;
  print("\nVALUE of x inside addOrder = $x");     -> Adding X flag here to check
      Order _order = new Order();

      _order.productOrders = new List<ProductOrder>();
      _order.tax = _cart.product.store.defaultTax;
      _order.deliveryFee = payment.method == 'Pay on Pickup'
          ? 0
          : _cart.product.store.deliveryFee;
      OrderStatus _orderStatus = new OrderStatus();
      _orderStatus.id = '1';
      _order.orderStatus = _orderStatus;
      _order.deliveryAddress = payment.method == 'Pay on Pickup'
          ? new Address()
          : settingRepo.deliveryAddress.value;
      _order.hint = ' ';
      ProductOrder _productOrder = new ProductOrder();
      _productOrder.quantity = _cart.quantity;
      _productOrder.price = _cart.product.price;
      _productOrder.id = _cart.product.id;
      _productOrder.product = _cart.product;
      _productOrder.options = _cart.options;

      _order.productOrders.add(_productOrder);
      print("Current value of EXISTING : $existingOrder");
      if (!existingOrder) {
        print("\n\nEntering not existing order....\n");
        await orderRepo.addOrder(_order, this.payment).then((value) {      ---> Doesn't wait. PROBLEM
          if (value is Order) {
            print("The value is now $value");
            firstOrderNumber =
                value.id.toString(); //catching order number to append
            print("FIRSTORDERNUMBER : $firstOrderNumber");
            setState(() {
              loading = false;
            });
          }
        });
        print("Settting value of existing order now...");
        existingOrder = true;
        print("Existing order is now $existingOrder");
      }
      // print("Existing order is now $existingOrder");
      else {
        print("\n\nEntering existing order....\n");
        orderRepo
            .addAdditionalOrder(
                _productOrder, _cart, _order, firstOrderNumber, this.payment)
            .then((value) {
          if (value is Order) {
            setState(() {
              loading = false;
            });
          }
        });
      }
    });
  }
</code>```

OUTPUT from console :

```<code>I/flutter ( 6925): VALUE of x inside addOrder = 1
I/flutter ( 6925): Current value of EXISTING : false
I/flutter ( 6925): Entering not existing order....
I/flutter ( 6925): VALUE of x inside addOrder = 2    ---> See the problem. It came back to increment X before the await is complete.
I/flutter ( 6925): Current value of EXISTING : false
I/flutter ( 6925): Entering not existing order....
</code>```

//Now it is giving the result of the AWAIT which it should have waited for before.....

```<code>I/flutter ( 6925): The response of first order is : <JSON RESPONSE from first addOrder execution...coming late..>
I/flutter ( 6925): The value is now Instance of 'Order'
I/flutter ( 6925): FIRSTORDERNUMBER : 141
I/flutter ( 6925): Settting value of existing order now...
I/flutter ( 6925): Existing order is now true
I/flutter ( 6925): The response of first order is :
</code>```

Any hints ? How can i NOT EXECUTE ANYTHING ELSE UNTILL  await orderRepo.addOrder(_order, this.payment).then((value) { is complete ??? Been doing trial n error for good few days

答:
that solved my issue.</p>
```<code>for (var item in items) {
  await function(item);
}
</code>```

Body:
I don't know what is missing here.. This is a function which is suppose to place orders from customers. The whole logic is quite simple :

If 1 single item in the cart , just executes once. If there are more, appends the order to the first order number. But for some reason its not waiting till the orderRepo.addOrder execution is complete initially.

  dynamic firstOrderNumber = 0;
  var existingOrder = false;

  void addOrder(List<Cart> carts) async {        --> Coming to add the list of orders
    carts.forEach((_cart) async {                --> Going to add each items in cart

             x += 1;
  print("\nVALUE of x inside addOrder = $x");     -> Adding X flag here to check
      Order _order = new Order();

      _order.productOrders = new List<ProductOrder>();
      _order.tax = _cart.product.store.defaultTax;
      _order.deliveryFee = payment.method == 'Pay on Pickup'
          ? 0
          : _cart.product.store.deliveryFee;
      OrderStatus _orderStatus = new OrderStatus();
      _orderStatus.id = '1';
      _order.orderStatus = _orderStatus;
      _order.deliveryAddress = payment.method == 'Pay on Pickup'
          ? new Address()
          : settingRepo.deliveryAddress.value;
      _order.hint = ' ';
      ProductOrder _productOrder = new ProductOrder();
      _productOrder.quantity = _cart.quantity;
      _productOrder.price = _cart.product.price;
      _productOrder.id = _cart.product.id;
      _productOrder.product = _cart.product;
      _productOrder.options = _cart.options;

      _order.productOrders.add(_productOrder);
      print("Current value of EXISTING : $existingOrder");
      if (!existingOrder) {
        print("\n\nEntering not existing order....\n");
        await orderRepo.addOrder(_order, this.payment).then((value) {      ---> Doesn't wait. PROBLEM
          if (value is Order) {
            print("The value is now $value");
            firstOrderNumber =
                value.id.toString(); //catching order number to append
            print("FIRSTORDERNUMBER : $firstOrderNumber");
            setState(() {
              loading = false;
            });
          }
        });
        print("Settting value of existing order now...");
        existingOrder = true;
        print("Existing order is now $existingOrder");
      }
      // print("Existing order is now $existingOrder");
      else {
        print("\n\nEntering existing order....\n");
        orderRepo
            .addAdditionalOrder(
                _productOrder, _cart, _order, firstOrderNumber, this.payment)
            .then((value) {
          if (value is Order) {
            setState(() {
              loading = false;
            });
          }
        });
      }
    });
  }

OUTPUT from console :

I/flutter ( 6925): VALUE of x inside addOrder = 1
I/flutter ( 6925): Current value of EXISTING : false
I/flutter ( 6925): Entering not existing order....
I/flutter ( 6925): VALUE of x inside addOrder = 2    ---> See the problem. It came back to increment X before the await is complete.
I/flutter ( 6925): Current value of EXISTING : false
I/flutter ( 6925): Entering not existing order....

//Now it is giving the result of the AWAIT which it should have waited for before.....

I/flutter ( 6925): The response of first order is : <JSON RESPONSE from first addOrder execution...coming late..>
I/flutter ( 6925): The value is now Instance of 'Order'
I/flutter ( 6925): FIRSTORDERNUMBER : 141
I/flutter ( 6925): Settting value of existing order now...
I/flutter ( 6925): Existing order is now true
I/flutter ( 6925): The response of first order is :

Any hints ? How can i NOT EXECUTE ANYTHING ELSE UNTILL  await orderRepo.addOrder(_order, this.payment).then((value) { is complete ??? Been doing trial n error for good few days

Body:
that solved my issue.

for (var item in items) {
  await function(item);
}


问:
Valid Mapbox Token is required but I don't work
I try to set up an react app with an integrated map of mapbox.
When I start the app, it says that the access token isn't valid. But I used the public token on the website.

```<code>VM68 react_devtools_backend.js:4061 Error: **A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/**
    at $t.errorCb (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32679:240)
    at $t.getSessionAPI (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:900:22)
    at Map._authenticate (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32676:13)
    at Map._render (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32645:91)
    at Map.map._render (bundle.js:34693:17)
    at vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32737:73
overrideMethod @ VM68 react_devtools_backend.js:4061
onError @ bundle.js:33707
Mapbox._onEvent @ bundle.js:34564
fire @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:1203
_fireEvent @ bundle.js:34996
(anonymous) @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32679
getSessionAPI @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:900
_authenticate @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32676
_render @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32645
map._render @ bundle.js:34693
(anonymous) @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32737
</code>```

I created an .env.local and connected it with my App.js. So I don't understand why this is not working. Here is my App.js:

```<code>import React, {useState} from "react";
import ReactMapGL from "react-map-gl";

export default function App() {
  const [viewport,setViewport] = useState ({
    longitude:-9.993682,
    latitude: 53.551086,
    zoom: 9,
    width: '100vw',
    height: '100 vh',
  });

  return (
    <div>
      <ReactMapGL
        {...viewport} mapboxApiAccessToken= {process.env.REACT_APP_MAPBOX_TOKEN}>
      </ReactMapGL>
    </div>
  );
}

</code>```

On the website happens only one thing: A little grey square that hovers on click but I was supposed to show a map...

Anyone here who can help?

This is my .env.local:

```<code>REACT_APP_MAPBOX_TOKEN="pk.eyJ1IjoibG91c2NoYSIsImEiOiJja3pibmZsZTYwbm1nMm9zNmdpdmJwYW5lIn0.qy5kQf2SjEf4CkSg4JcY1Q"
</code>```

This is my Folder structure:

Folderstructure

答:
You have to provide the REACT_APP_MAPBOX_TOKEN without the quotation marks: REACT_APP_MAPBOX_TOKEN=pk.eyJ1IjoibG91c2NoYSIsImEiOiJja3pibmZsZTYwbm1nMm9zNmdpdmJwYW5lIn0.qy5kQf2SjEf4CkSg4JcY1Q

For people not to abuse your Mapbox Token, you should consider generating a new one.

Body:
I try to set up an react app with an integrated map of mapbox.
When I start the app, it says that the access token isn't valid. But I used the public token on the website.

VM68 react_devtools_backend.js:4061 Error: **A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/**
    at $t.errorCb (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32679:240)
    at $t.getSessionAPI (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:900:22)
    at Map._authenticate (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32676:13)
    at Map._render (vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32645:91)
    at Map.map._render (bundle.js:34693:17)
    at vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32737:73
overrideMethod @ VM68 react_devtools_backend.js:4061
onError @ bundle.js:33707
Mapbox._onEvent @ bundle.js:34564
fire @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:1203
_fireEvent @ bundle.js:34996
(anonymous) @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32679
getSessionAPI @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:900
_authenticate @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32676
_render @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32645
map._render @ bundle.js:34693
(anonymous) @ vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:32737

I created an .env.local and connected it with my App.js. So I don't understand why this is not working. Here is my App.js:

import React, {useState} from "react";
import ReactMapGL from "react-map-gl";

export default function App() {
  const [viewport,setViewport] = useState ({
    longitude:-9.993682,
    latitude: 53.551086,
    zoom: 9,
    width: '100vw',
    height: '100 vh',
  });

  return (

      <ReactMapGL
        {...viewport} mapboxApiAccessToken= {process.env.REACT_APP_MAPBOX_TOKEN}>
      </ReactMapGL>

  );
}

On the website happens only one thing: A little grey square that hovers on click but I was supposed to show a map...

Anyone here who can help?

This is my .env.local:

REACT_APP_MAPBOX_TOKEN="pk.eyJ1IjoibG91c2NoYSIsImEiOiJja3pibmZsZTYwbm1nMm9zNmdpdmJwYW5lIn0.qy5kQf2SjEf4CkSg4JcY1Q"

This is my Folder structure:

Folderstructure


问:
initializing a UIBarButtonItem with a UIImage and resizing the image in iOS
I am trying to initialize a UIBarButtonItem with an Image. The available method is initWithImage. When I do this, the image is just a block of color. I want to be able to resize this image. How do I do that?</p>

答: Internal UIBarButtonItem images need to be one solid color (system turns it into white if you don't) with an alpha channel for transparency. </p>


问:
How can you encode a string to Base64 in JavaScript?
I have a PHP script that can encode a PNG image to a Base64 string.

I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.

答:
2022 deprecation warning update

I saw deprecation warning on my vscode

```<code>This function is only provided for compatibility with legacy web platform APIs and should never be used in new code,
because they use strings to represent binary data and predate the introduction of typed arrays in JavaScript.
For code running using Node.js APIs,
converting between base64-encoded strings and binary data should be performed using Buffer.from(str, 'base64') andbuf.toString('base64').
</code>```

After searching a bit more, I found this issue that says it isn't deprecated

https://github.com/microsoft/TypeScript/issues/45566

so the solution to the deprecation warning on web JS, use window.btoa
and the warning will disappear.

OwnerDisplayName: username

Body:
2022 deprecation warning update

I saw deprecation warning on my vscode

This function is only provided for compatibility with legacy web platform APIs and should never be used in new code,
because they use strings to represent binary data and predate the introduction of typed arrays in JavaScript.
For code running using Node.js APIs,
converting between base64-encoded strings and binary data should be performed using Buffer.from(str, 'base64') andbuf.toString('base64').

After searching a bit more, I found this issue that says it isn't deprecated

https://github.com/microsoft/TypeScript/issues/45566

so the solution to the deprecation warning on web JS, use window.btoa
and the warning will disappear.


问:
Julia - Metaprogramming for using several modules
I'm using Julia to autograde students' work. I have all of their files Student1.jl, Student2.jl, etc. as separate modules Student1, Student2, etc in a directory that is part of LOAD_PATH. What I want to be able to do works completely fine in the REPL, but fails in a file.

```<code>macro Student(number)
    return Meta.parse("Main.Student$number")
end

using Student1
@Student(1).call_function(inputs)
</code>```

works completely fine in the REPL. However, since I'm running this in a script, I need to be able to include the modules with more metaprogramming that is currently not working. I would have thought that the exact same script above would have worked in a file Autograder.jl by calling

```<code>@eval(using Student1)
@Student(1).call_function(inputs)
</code>```

in a module Autograder. But I get either an UndefVarError: Student1 not defined or LoadError: cannot replace module Student1 during compilation depending on how I tweak things.

Is there something small in Julia metaprogramming I'm missing here to make this autograding system work out? Thanks for any advice.

答:
The code just as you have written works for me on julia versions 1.1.0, 1.3.1, 1.5.1, 1.6.0 and 1.7.0. By that I mean, if I add an inputs variable and put your first code block in a file Autograder.jl and run JULIA_LOAD_PATH="modules:$JULIA_LOAD_PATH" julia Autograder.jl with the student modules in the modules directory I get the output of the call_function function in the Student1 module.

However if Autograder.jl actually contains a module then the Student$number module is not required into Main and your macro needs to be modified accordingly:

```<code>module Autograder
macro Student(number)
    return Meta.parse("Student$number") # or "Autograder.Student$number"
end

inputs = []
@eval(using Student1)
@Student(1).call_function(inputs)
end
</code>```

Personally I wouldn't use a macro to accomplish this, here is one possible alternative:

```<code>student(id) = Base.require(Main, Symbol("Student$(id)"))
let student_module = student(1)
    student_module.call_function(inputs)
end
</code>```

or without modifying the LOAD_PATH:

```<code>student(id) = include("modules/Student$(id).jl")
let student_module = student(1)
    student_module.call_function(inputs)
end
</code>```

Body:
I'm using Julia to autograde students' work. I have all of their files Student1.jl, Student2.jl, etc. as separate modules Student1, Student2, etc in a directory that is part of LOAD_PATH. What I want to be able to do works completely fine in the REPL, but fails in a file.

macro Student(number)
    return Meta.parse("Main.Student$number")
end

using Student1
@Student(1).call_function(inputs)

works completely fine in the REPL. However, since I'm running this in a script, I need to be able to include the modules with more metaprogramming that is currently not working. I would have thought that the exact same script above would have worked in a file Autograder.jl by calling

@eval(using Student1)
@Student(1).call_function(inputs)

in a module Autograder. But I get either an UndefVarError: Student1 not defined or LoadError: cannot replace module Student1 during compilation depending on how I tweak things.

Is there something small in Julia metaprogramming I'm missing here to make this autograding system work out? Thanks for any advice.

Body:
The code just as you have written works for me on julia versions 1.1.0, 1.3.1, 1.5.1, 1.6.0 and 1.7.0. By that I mean, if I add an inputs variable and put your first code block in a file Autograder.jl and run JULIA_LOAD_PATH="modules:$JULIA_LOAD_PATH" julia Autograder.jl with the student modules in the modules directory I get the output of the call_function function in the Student1 module.

However if Autograder.jl actually contains a module then the Student$number module is not required into Main and your macro needs to be modified accordingly:

module Autograder
macro Student(number)
    return Meta.parse("Student$number") # or "Autograder.Student$number"
end

inputs = []
@eval(using Student1)
@Student(1).call_function(inputs)
end

Personally I wouldn't use a macro to accomplish this, here is one possible alternative:

student(id) = Base.require(Main, Symbol("Student$(id)"))
let student_module = student(1)
    student_module.call_function(inputs)
end

or without modifying the LOAD_PATH:

student(id) = include("modules/Student$(id).jl")
let student_module = student(1)
    student_module.call_function(inputs)
end


问:
How to exclude a folder in a working git repository (Visual Studio Code)
I am using Visual Studio Code version 0.7.10. I want to use version control. I figured this was a good time to start teaching myself to use git. I have never used it before.

How do I make git ignore my "node_modules" folder? Every item in this folder is listed for possible commits and that is cluttering up my workspace. I don't want to upload all the packages. I figure whoever runs the package.json can do that on their own computer.

Thought: I found under File > Preferences > User Settings that there is a configuration file called "settings.json" that will overwrite the default settings. I see a "Git configuration" in the default settings but I can't find any documentation on my possible options here. I would think I could do a "git.exclude" but where do I begin. This is only a guess at a solution. I am sure the real answer is something completely different.

I am looking for any documentation you could point me to. Thanks!

UPDATE: I made a change to the ".git/info/exclude" file and my Git repository view cleared up instantly. Here is a link that talks about the exclude file and why it worked for my VS Code editor. (https://help.github.com/articles/ignoring-files/)

答:
For those who want to exclude a file vie private ignore using .git/info/exclude. In my case VSCode still kept it as tracked and listed. Even git rm -f --cached <filename> didn't helped at all.

What helped instantly was the extension named GIT-EXCLUDE
Just had to install it and as I had the file alredy in the exclude file it disappeared right in the moment when the extension started.

It also allows you to use RMB in VSCode file explorer to exclude files conveniently.


问:
rtUpload Failed sending usage report to Artifactory: java.io.IOException: Could not get Artifactory version
I have the pipe running and doing all his needs basically.
There is the jenkins file; the job succeeds, but there is a failure in one of the stages.

On stage helm ('push helm to registry')

```<code>stages {
            stage("Push to Helm registry") {
                steps {
                    script {
                        rtServer (
                            id: 'helm-registry',
                            url: '-----------------',
                            credentialsId: 'sys-bm-artifactory'
                        )

                        rtUpload (
                            serverId: 'helm-registry',
                            spec: """{
                                "files": [
                                    {
                                    "pattern": "${app_name}-*.tgz",
                                    "target": "${app_name}/"
                                    }
                                ]
                            }"""
                        )
                    }
                }
            }
</code>```

credentials works ok.
helm chart pushed correctly to jFrog repository.
the error relates to version of artifactory version.
Using rtServer and rtUpload for connection between helm chart to Jfrog registry.

Error (in the middle of the log):

```<code>11:08:13  Failed sending usage report to Artifactory: java.io.IOException: Could not get Artifactory version.
</code>```

Why am I getting this error? Where does it come from?

Still I see all artifacts stored in registry.

答:
Ok, the problem with this error appearing in the CI was probably because we override the same version every time.

So, to avoid this exception just increase the version and every push make sure you don't override the same file.

Note: make sure credentials + JFrog URL are correct.

Body:
I have the pipe running and doing all his needs basically.
There is the jenkins file; the job succeeds, but there is a failure in one of the stages.

On stage helm ('push helm to registry')

stages {
            stage("Push to Helm registry") {
                steps {
                    script {
                        rtServer (
                            id: 'helm-registry',
                            url: '-----------------',
                            credentialsId: 'sys-bm-artifactory'
                        )

                        rtUpload (
                            serverId: 'helm-registry',
                            spec: """{
                                "files": [
                                    {
                                    "pattern": "${app_name}-*.tgz",
                                    "target": "${app_name}/"
                                    }
                                ]
                            }"""
                        )
                    }
                }
            }

credentials works ok.
helm chart pushed correctly to jFrog repository.
the error relates to version of artifactory version.
Using rtServer and rtUpload for connection between helm chart to Jfrog registry.

Error (in the middle of the log):

11:08:13  Failed sending usage report to Artifactory: java.io.IOException: Could not get Artifactory version.

Why am I getting this error? Where does it come from?

Still I see all artifacts stored in registry.


问:
How to append the bootstrap 5 dropdown menu to a specific element. when the dropdown element is inside an element with overflow: hidden
I am use Bootstrap 5 dropdown menu inside owl-carousel. but dropdown is being cut off because has outer div overflow:hidden in owl-carousel.

Complete snippet here: jsfiddle

So, I have try to position a dropdown relatively to body, not parent with boundary option from Bootstrap Docs,

Bootstrap docs says that can only be done via javascript (not via data attributes),

so I have try below javascript methods code. but no luck.

```<code>var dropdownElementList = [].slice.call(document.querySelectorAll('.dropdown-toggle'))
    var dropdownList = dropdownElementList.map(function (dropdownToggleEl) {
      return new bootstrap.Dropdown(dropdownToggleEl, {
        boundary: document.querySelector('#main-wrapper')
      })
    })
</code>```

Any suggestions with proper solution for where I'm going wrong would be greatly appreciated.

Our HTML Code:

```<code><div id="main-wrapper">
<div class="owl-carousel owl-theme">
  <div class="item">
    <div class="d-flex align-items-center">
      <h4>Shilipp Sotocnik</h4>

      <div class="dropdown dropdown-lg d-inline-block ms-auto">
      <a href="#" role="button" id="dropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-ellipsis-h"></i></a>
        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenu1">
          <li><a class="dropdown-item" href="#">Link 1</a></li>
          <li><a class="dropdown-item" href="#">Link 2</a></li>
          <li><a class="dropdown-item" href="#">Link 3</a></li>
          <li><a class="dropdown-item" href="#">Link 4</a></li>
        </ul>
      </div>

    </div>
  </div>
</div>
</div>
</code>```

答:
Use jQuery to listen events on dropdown to toggle overflow class at element

.

$('a[data-bs-toggle="dropdown"]').on('show.bs.dropdown', function () {
    $(".owl-stage-outer").addClass("overflow_none");
})

$('a[data-bs-toggle="dropdown"]').on('hide.bs.dropdown', function () {
    $(".owl-stage-outer").removeClass("overflow_none");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overflow_none  {
  overflow: unset !important;
}</code>```

Body:
I am use Bootstrap 5 dropdown menu inside owl-carousel. but dropdown is being cut off because has outer div overflow:hidden in owl-carousel.

Complete snippet here: jsfiddle

So, I have try to position a dropdown relatively to body, not parent with boundary option from Bootstrap Docs,

Bootstrap docs says that can only be done via javascript (not via data attributes),

so I have try below javascript methods code. but no luck.

var dropdownElementList = [].slice.call(document.querySelectorAll('.dropdown-toggle'))
    var dropdownList = dropdownElementList.map(function (dropdownToggleEl) {
      return new bootstrap.Dropdown(dropdownToggleEl, {
        boundary: document.querySelector('#main-wrapper')
      })
    })

Any suggestions with proper solution for where I'm going wrong would be greatly appreciated.

Our HTML Code:

Shilipp Sotocnik

Link 1

Link 2

Link 3

Link 4

Body:
Use jQuery to listen events on dropdown to toggle overflow class at element

<div class="owl-stage-outer">.

$('a[data-bs-toggle="dropdown"]').on('show.bs.dropdown', function () {
    $(".owl-stage-outer").addClass("overflow_none");
})

$('a[data-bs-toggle="dropdown"]').on('hide.bs.dropdown', function () {
    $(".owl-stage-outer").removeClass("overflow_none");
})

.overflow_none  {
  overflow: unset !important;
}