问:
Logback appender to post message as HTTP message
As per my requirement I just wanted to post HTTP message to other end which is logged by org.slf4j.LoggerFactory.getLogger().

The following JSON string logged at INFO level.

```<code>{
  "studentName": "My Name",
  "Deratment": "Computer Science",
  "address": {
     "Address Line1": "My Address Line1",
     "Address Line2": "My Address Line2",
     "Address Line3": "My Address Line3"
  }
}
</code>```

Considerations,

Http message should post with MIME type application/json

should process only the particular log in INFO level not all.

Is there any built-in appender in Logback to achieve this?

If not, what is the best way to do it?

答:
I think the best way to post json message is using org.apache.logging.log4j .

Step 1: add maven dependency

```<code><dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.1</version>
</dependency>
</code>```

and any dependency for constructing json, like

```<code><dependency>
     <groupId>com.google.code.gson</groupId>
     <artifactId>gson</artifactId>
     <version>2.8.5</version>
</dependency>
</code>```

Step 2: write custom layout to create your json

```<code>@Plugin(name = "CustomJsonLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE)
public class CustomJsonLayout extends AbstractStringLayout {
    private static final Gson gson = new Gson();

    public CustomJsonLayout(Configuration config, Charset aCharset, Serializer headerSerializer, Serializer footerSerializer) {
        super(config, aCharset, headerSerializer, footerSerializer);
    }

    @PluginFactory
    public static CustomJsonLayout createLayout(@PluginConfiguration final Configuration config,
                                                @PluginAttribute(value = "charset", defaultString = "US-ASCII") final Charset charset) {
        return new CustomJsonLayout(config, charset, null, null);
    }

    @Override
    public String toSerializable(LogEvent event) {
        JsonObject jsonObject = new JsonObject();

        // as example
        jsonObject.addProperty("application_name", "MyApp");
        jsonObject.addProperty("timestamp", "" + System.currentTimeMillis());

        // some log Information
        jsonObject.addProperty("level", event.getLevel().name());
        jsonObject.addProperty("thread", event.getThreadName());
        jsonObject.addProperty("thread_id", event.getThreadId());
        jsonObject.addProperty("logger_name", event.getLoggerName());

        // extra information
        final StackTraceElement source = event.getSource();
        JsonObject sourceObject = new JsonObject();
        sourceObject.addProperty("class", source.getClassName());
        sourceObject.addProperty("method", source.getMethodName());
        sourceObject.addProperty("file", source.getFileName());
        sourceObject.addProperty("line", source.getLineNumber());
        jsonObject.add("source", sourceObject);

        // your log message
        jsonObject.addProperty("message", event.getMessage().getFormattedMessage());

        // Exceptions
        if (event.getThrownProxy() != null) {
            final ThrowableProxy thrownProxy = event.getThrownProxy();
            final Throwable throwable = thrownProxy.getThrowable();

            final String exceptionsClass = throwable.getClass().getCanonicalName();
            if (exceptionsClass != null) {
                jsonObject.addProperty("exception", exceptionsClass);
            }

            final String exceptionsMessage = throwable.getMessage();
            if (exceptionsMessage != null) {
                jsonObject.addProperty("cause", exceptionsMessage);
            }

            final String stackTrace = thrownProxy.getExtendedStackTraceAsString("");
            if (stackTrace != null) {
                jsonObject.addProperty("stacktrace", stackTrace);
            }
        }

        return gson.toJson(jsonObject).concat("\r\n");
    }

}
</code>```

Step 3: configure log4j2.xml where yourUrl - target url from application.properties if you use spring boot (yourUrl=http://....)

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="urlProp">${bundle:application:yourUrl}</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <Http name="Http" url="${urlProp}">
            <Property name="X-Java-Runtime" value="$${java:runtime}" />
            <CustomJsonLayout/>
        </Http>
        <File name="LogToFile" fileName="logs/app.log">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Http"/>
            <AppenderRef ref="Console"/>
            <AppenderRef ref="LogToFile"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

Step 4: So, finally you can use your logger in any classes

```<code>import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

private static final Logger logger = LogManager.getLogger(App.class);

logger.info("Application started");
</code>```

Body:
As per my requirement I just wanted to post HTTP message to other end which is logged by org.slf4j.LoggerFactory.getLogger().

The following JSON string logged at INFO level.

{
  "studentName": "My Name",
  "Deratment": "Computer Science",
  "address": {
     "Address Line1": "My Address Line1",
     "Address Line2": "My Address Line2",
     "Address Line3": "My Address Line3"
  }
}

Considerations,

Http message should post with MIME type application/json

should process only the particular log in INFO level not all.

Is there any built-in appender in Logback to achieve this?

If not, what is the best way to do it?

Body:
I think the best way to post json message is using org.apache.logging.log4j .

Step 1: add maven dependency

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.1</version>
</dependency>

and any dependency for constructing json, like

<dependency>
     <groupId>com.google.code.gson</groupId>
     <artifactId>gson</artifactId>
     <version>2.8.5</version>
</dependency>

Step 2: write custom layout to create your json

@Plugin(name = "CustomJsonLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE)
public class CustomJsonLayout extends AbstractStringLayout {
    private static final Gson gson = new Gson();

    public CustomJsonLayout(Configuration config, Charset aCharset, Serializer headerSerializer, Serializer footerSerializer) {
        super(config, aCharset, headerSerializer, footerSerializer);
    }

    @PluginFactory
    public static CustomJsonLayout createLayout(@PluginConfiguration final Configuration config,
                                                @PluginAttribute(value = "charset", defaultString = "US-ASCII") final Charset charset) {
        return new CustomJsonLayout(config, charset, null, null);
    }

    @Override
    public String toSerializable(LogEvent event) {
        JsonObject jsonObject = new JsonObject();

        // as example
        jsonObject.addProperty("application_name", "MyApp");
        jsonObject.addProperty("timestamp", "" + System.currentTimeMillis());

        // some log Information
        jsonObject.addProperty("level", event.getLevel().name());
        jsonObject.addProperty("thread", event.getThreadName());
        jsonObject.addProperty("thread_id", event.getThreadId());
        jsonObject.addProperty("logger_name", event.getLoggerName());

        // extra information
        final StackTraceElement source = event.getSource();
        JsonObject sourceObject = new JsonObject();
        sourceObject.addProperty("class", source.getClassName());
        sourceObject.addProperty("method", source.getMethodName());
        sourceObject.addProperty("file", source.getFileName());
        sourceObject.addProperty("line", source.getLineNumber());
        jsonObject.add("source", sourceObject);

        // your log message
        jsonObject.addProperty("message", event.getMessage().getFormattedMessage());

        // Exceptions
        if (event.getThrownProxy() != null) {
            final ThrowableProxy thrownProxy = event.getThrownProxy();
            final Throwable throwable = thrownProxy.getThrowable();

            final String exceptionsClass = throwable.getClass().getCanonicalName();
            if (exceptionsClass != null) {
                jsonObject.addProperty("exception", exceptionsClass);
            }

            final String exceptionsMessage = throwable.getMessage();
            if (exceptionsMessage != null) {
                jsonObject.addProperty("cause", exceptionsMessage);
            }

            final String stackTrace = thrownProxy.getExtendedStackTraceAsString("");
            if (stackTrace != null) {
                jsonObject.addProperty("stacktrace", stackTrace);
            }
        }

        return gson.toJson(jsonObject).concat("\r\n");
    }

}

Step 3: configure log4j2.xml where yourUrl - target url from application.properties if you use spring boot (yourUrl=http://....)

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="urlProp">${bundle:application:yourUrl}</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <Http name="Http" url="${urlProp}">
            <Property name="X-Java-Runtime" value="$${java:runtime}" />
            <CustomJsonLayout/>
        </Http>
        <File name="LogToFile" fileName="logs/app.log">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Http"/>
            <AppenderRef ref="Console"/>
            <AppenderRef ref="LogToFile"/>
        </Root>
    </Loggers>
</Configuration>

Step 4: So, finally you can use your logger in any classes

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

private static final Logger logger = LogManager.getLogger(App.class);

logger.info("Application started");


来源: stackexchange

问:
Python - Folium map don't show marker
I have this code in python and show map.

```<code>import folium
from IPython.display import HTML, display

city_location = [-23.6573395, -46.5322504]

mapa = folium.Map(location=city_location,  zoom_start=15)
mapa
</code>```

But, to add marker, don't show.

```<code>tooltip = 'Click me!'
folium.Marker([-23.6573395, -46.5322504], popup='<i>Teste</i>', tooltip=tooltip).add_to(mapa)
mapa
</code>```

Help me, please!

答:
I think you should add this line:</p>

```<code>mapa.save('path')
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python - Folium map don't show marker

Body:
I have this code in python and show map.

import folium
from IPython.display import HTML, display

city_location = [-23.6573395, -46.5322504]

mapa = folium.Map(location=city_location,  zoom_start=15)
mapa

But, to add marker, don't show.

tooltip = 'Click me!'
folium.Marker([-23.6573395, -46.5322504], popup='Teste', tooltip=tooltip).add_to(mapa)
mapa

Help me, please!

Body:
I think you should add this line:

mapa.save('path')


问:
Spring boot @Caching With Multiple Keys
```<code>public class Student {
    public int studentName;
    public String Addr1;
    public String Addr2;
    public String Addr2;
    //getter setter
}

I have one repository class which contains following methods
class StudentRepoImpl{
   @Cacheable(value = "Students")
   public List<Students> findAllStudents() {
     //fetching all cust and putting in the Students cache
   }

   @Cacheable(value = "Students")
   public List<Students> findStudentsBystudentNameAndAddresses() {
     //fetching all cust data by **Name/Address1/Address2/Address3** basis of field available studentName/Address1/Address2/Address3 and putting in Student table
   }

}
</code>```

Current Output :

Fetch All data from DB and adding in Students cache in findAllStudents() method

But while searching for data based on some criteria (Name/Address1/Address2/Address3) using findStudentsBystudentNameAndAddresses() method it is fetching data from DB instead of cache.

Note: Not added Key while caching because there are 4 fields in search criteria (Name/Address1/Address2/Address3) and these are conditional fields means some time only Address1 will be in search criteria or sometime Address1+Address2 or sometimes all Address1+Address2+Address3 fields and I want to fetch exact match on the basis of Name and available Addresses.

答: did you add @EnableCaching annotation in your configuration class</p>

Title: Spring boot @Caching With Multiple Keys

Body:
public class Student {
    public int studentName;
    public String Addr1;
    public String Addr2;
    public String Addr2;
    //getter setter
}

I have one repository class which contains following methods
class StudentRepoImpl{
   @Cacheable(value = "Students")
   public List<Students> findAllStudents() {
     //fetching all cust and putting in the Students cache
   }

   @Cacheable(value = "Students")
   public List<Students> findStudentsBystudentNameAndAddresses() {
     //fetching all cust data by **Name/Address1/Address2/Address3** basis of field available studentName/Address1/Address2/Address3 and putting in Student table
   }

}

Current Output :

Fetch All data from DB and adding in Students cache in findAllStudents() method

But while searching for data based on some criteria (Name/Address1/Address2/Address3) using findStudentsBystudentNameAndAddresses() method it is fetching data from DB instead of cache.

Note: Not added Key while caching because there are 4 fields in search criteria (Name/Address1/Address2/Address3) and these are conditional fields means some time only Address1 will be in search criteria or sometime Address1+Address2 or sometimes all Address1+Address2+Address3 fields and I want to fetch exact match on the basis of Name and available Addresses.


问:
CMake - how to block executing installation scripts during packaging?
My CMakeLists.txt file contains commands, which should be executed by make install, and all this works fine. The sample CMakeLists.txt below is a short excerpt from my actual CMake file (the tm0001.cpp content is not important here - it might be any C++ program):

```<code>cmake_minimum_required(VERSION 3.12)

project(tm0001)

set(CMAKE_CXX_STANDARD 11)
add_executable(${PROJECT_NAME} tm0001.cpp)

install(
  TARGETS ${PROJECT_NAME}
  DESTINATION /usr/local/bin
  PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
)

install(CODE "message(\"-- This must be called during installation only\")")

set(CPACK_PACKAGE_CONTACT "HEKTO")
set(CPACK_GENERATOR "DEB")
include(CPack)
</code>```

I see the message command is executed by make package as well, which is not I want.

How to tell CMake not to execute installation scripts by the make package command? I couldn't find any way to do that with the CMake if command.

答:
What I did was to specify install commands with CODE/SCRIPT as separate component e.g. install(CODE ... COMPONENT post-install).

Then also added other non-code install commands as a different component e.g. install(FILES ... COMPONENT files-install)

The CPack then needs to be configured to package only files-install component (solution to this can be found easily - hint: use CPACK_COMPONENTS_ALL_IN_ONE_PACKAGE, CPACK_COMPONENTS_ALL and CPACK_(RPM/DEB/...)_COMPONENT_INSTALL variables).

Of course then the resulting package won't run these CODE components during installing the package - they need to be added separately as a post install script.

Body:
My CMakeLists.txt file contains commands, which should be executed by make install, and all this works fine. The sample CMakeLists.txt below is a short excerpt from my actual CMake file (the tm0001.cpp content is not important here - it might be any C++ program):

cmake_minimum_required(VERSION 3.12)

project(tm0001)

set(CMAKE_CXX_STANDARD 11)
add_executable(${PROJECT_NAME} tm0001.cpp)

install(
  TARGETS ${PROJECT_NAME}
  DESTINATION /usr/local/bin
  PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
)

install(CODE "message(\"-- This must be called during installation only\")")

set(CPACK_PACKAGE_CONTACT "HEKTO")
set(CPACK_GENERATOR "DEB")
include(CPack)

I see the message command is executed by make package as well, which is not I want.

How to tell CMake not to execute installation scripts by the make package command? I couldn't find any way to do that with the CMake if command.


问:
JSON and Core Data on the iPhone
I have a core data object graph (consisting of two entities linked by a to-many relationship).

I was curious, as a relatively inexperienced iPhone developer, whether anyone could recommend an approach, and a suitable JSON implementation for the iPhone, which would allow me to:

convert the core data records into a JSON string (whilst maintaining the relationship between the entities); and

convert the JSON string back into core data objects (again preserving the relationship between entities).

I have searched, unsuccessfully, for a tutorial/code sample on this point so any assistance would be gratefully received.

答: There is a lib that does the JSON synchronization for you : https://github.com/sixdegrees/lidenbrock</p>

ContentLicense: CC BY-SA 3.0

Title: JSON and Core Data on the iPhone


问:
Returning the result of a node-postgres query
I am attempting to return the result of a node-postgres query and store it in a variable.  I can manage a console.log just fine, but cannot find a way to return the result so that it is accessible outside of the query method.  I'm at a loss, and know I must be missing something obvious (or multiple obvious things), because if it isn't possible to do this I don't understand the point of node-postgres since all I will ever be able to do is log my results to the console.

I have tried the code below, along with a version using promises, and both receive the same result, 'undefined.' A console.log within the else works fine, but a return does not make the result accessible to the rest of the function.  In the code below, my return comes back as 'undefined' as would a console.log in its place.

```<code>var selectFrom = function(data, table, condition) {
    var queryResult;
    pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
        if(err) { console.log(err); }
        else { queryResult = result.rows[0][data]; }
    })
    pool.end();
    return queryResult;
}

var result = selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
console.log(result);
</code>```

答:
This is what you are looking for:

```<code>async function selectFrom(data, table, condition) {
  try {
    const res = await pool.query(
      `SELECT ${data} FROM ${table} ${condition}`
    );
    return res.rows[0][data];
  } catch (err) {
    return err.stack;
  }
}
</code>```

Outside of the previous function:

```<code>async function whateverFuncName () {
   var result = await selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
   console.log(result);
}
</code>```

EDIT: I didn't run this code snippet but the main concept is pretty straightforward.

Body:
I am attempting to return the result of a node-postgres query and store it in a variable.  I can manage a console.log just fine, but cannot find a way to return the result so that it is accessible outside of the query method.  I'm at a loss, and know I must be missing something obvious (or multiple obvious things), because if it isn't possible to do this I don't understand the point of node-postgres since all I will ever be able to do is log my results to the console.

I have tried the code below, along with a version using promises, and both receive the same result, 'undefined.' A console.log within the else works fine, but a return does not make the result accessible to the rest of the function.  In the code below, my return comes back as 'undefined' as would a console.log in its place.

var selectFrom = function(data, table, condition) {
    var queryResult;
    pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
        if(err) { console.log(err); }
        else { queryResult = result.rows[0][data]; }
    })
    pool.end();
    return queryResult;
}

var result = selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
console.log(result);

Body:
This is what you are looking for:

async function selectFrom(data, table, condition) {
  try {
    const res = await pool.query(
      `SELECT ${data} FROM ${table} ${condition}`
    );
    return res.rows[0][data];
  } catch (err) {
    return err.stack;
  }
}

Outside of the previous function:

async function whateverFuncName () {
   var result = await selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
   console.log(result);
}

EDIT: I didn't run this code snippet but the main concept is pretty straightforward.


问:
Expanding a Map<String,String> to Map<String,Map> based on the key
If I have a map like:

```<code>Map.of("key1", "value1",
       "key2.subkey1", "subvalue1",
       "key2.subkey2", "subvalue2",
       "key2.subkey3.subsubkey", "subsubvalue");
</code>```

Then I would like to convert it to a map of (possibly) maps like this:

```<code>Map.of("key1", "value1",
       "key2", Map.of("subkey1", "subvalue1",
                      "subkey2", "subvalue2",
                      "subkey3", Map.of("subsubkey", "subsubvalue)));
</code>```

I figure I need to split the keys like so:

```<code>entry.getKey().split("\\.", 2);
</code>```

But I cant figure out what to do after that.

答:
I like to use recursion in these cases (cascaded keys):

public static Map<String, Object> covert(Map<String, String> map) {
    Map<String, Object> result = new HashMap<>();
    map.forEach((key, value) -> parseAndPut(result, key, value));
    return result;
}

@SuppressWarnings("unchecked")
private static void parseAndPut(Map<String, Object> map, String key, String value) {
    String[] keys = key.split("\\.");
    if (keys.length == 1) {
        map.put(key, value);
    } else if (keys.length > 1) {
        String subKey = keys[0];
        Map<String, Object> valueMap = (Map<String, Object>) map.computeIfAbsent(subKey, s -> new HashMap<>());
        int beginIndex = key.indexOf(subKey) + subKey.length() + 1;
        parseAndPut(valueMap, key.substring(beginIndex), value);
    }
}
```

<p>Output for your input data:</p>

```{key1=value1, key2={subkey1=subvalue1, subkey2=subvalue2, subkey3={subsubkey=subsubvalue}}}
```

Body:
If I have a map like:

Map.of("key1", "value1",
       "key2.subkey1", "subvalue1",
       "key2.subkey2", "subvalue2",
       "key2.subkey3.subsubkey", "subsubvalue");

Then I would like to convert it to a map of (possibly) maps like this:

Map.of("key1", "value1",
       "key2", Map.of("subkey1", "subvalue1",
                      "subkey2", "subvalue2",
                      "subkey3", Map.of("subsubkey", "subsubvalue)));

I figure I need to split the keys like so:

entry.getKey().split("\\.", 2);

But I cant figure out what to do after that.

Body:
I like to use recursion in these cases (cascaded keys):

public static Map<String, Object> covert(Map<String, String> map) {
    Map<String, Object> result = new HashMap<>();
    map.forEach((key, value) -> parseAndPut(result, key, value));
    return result;
}

@SuppressWarnings("unchecked")
private static void parseAndPut(Map<String, Object> map, String key, String value) {
    String[] keys = key.split("\\.");
    if (keys.length == 1) {
        map.put(key, value);
    } else if (keys.length > 1) {
        String subKey = keys[0];
        Map<String, Object> valueMap = (Map<String, Object>) map.computeIfAbsent(subKey, s -> new HashMap<>());
        int beginIndex = key.indexOf(subKey) + subKey.length() + 1;
        parseAndPut(valueMap, key.substring(beginIndex), value);
    }
}

Output for your input data:

{key1=value1, key2={subkey1=subvalue1, subkey2=subvalue2, subkey3={subsubkey=subsubvalue}}}


问:
How I insert a image data in a input element to generate a FIleList
I developed an image-cropper, which generates a base64 and after that creates an image file. But I have no idea how to insert image data into an entry to generate a FileList. Can someone help me?

答:
If i understand what you need is an input file to pass the event to image-cropper.

PS : the event have the files data.

Example :
HTML :

```<code><input id="input-files" type="file" (change)="onImageFileChanged($event)" accept="image/*" />

<image-cropper *ngIf="imageChangedEvent" [imageChangedEvent]="imageChangedEvent"></image-cropper>
</code>```

TS:

```<code>imageChangedEvent: any = '';

onImageFileChanged(event: any) {
   this.imageChangedEvent = event;
}
</code>```

Now inside this.imageChangedEvent a list of images that you have selected.

If you want to put back your files to input file then try this :

```<code>const data = new ClipboardEvent('').clipboardData || new DataTransfer();
data.items.add(new File(['foo'], 'image.png'));
  // replace new File(['foo'], 'image.png') with your file
document.getElementById("input-files").files = data.files;
</code>```

Source : stackoverflow-set-file-objects

Body:
If i understand what you need is an input file to pass the event to image-cropper.

PS : the event have the files data.

Example :
HTML :

<input id="input-files" type="file" (change)="onImageFileChanged($event)" accept="image/*" />

<image-cropper *ngIf="imageChangedEvent" [imageChangedEvent]="imageChangedEvent"></image-cropper>

TS:

imageChangedEvent: any = '';

onImageFileChanged(event: any) {
   this.imageChangedEvent = event;
}

Now inside this.imageChangedEvent a list of images that you have selected.

If you want to put back your files to input file then try this :

const data = new ClipboardEvent('').clipboardData || new DataTransfer();
data.items.add(new File(['foo'], 'image.png'));
  // replace new File(['foo'], 'image.png') with your file
document.getElementById("input-files").files = data.files;

Source : stackoverflow-set-file-objects


问:
value of useState not being set on initial render
I have the isDesktop boolean that should be set to true or false depending on the sceensize and this works however on initial render it doesn't set to true/false, how can I set this on intial render?

```<code> const [isVisible, setIsVisible] = useState(false)
  const [isDesktop, setIsDesktop] = useState(window.innerWidth)

  console.log(isDesktop)
  useEffect(() => {
    window.addEventListener("scroll", UpdateScrollPosition);
    window.addEventListener("resize", displayWindowSize);
    return () => window.removeEventListener("scroll", UpdateScrollPosition);
  }, []);

  const UpdateScrollPosition = () => {
    const scrollPos = window.scrollY
    if( scrollPos < 520) {
      return setIsVisible(false)
    }else if (scrollPos >= 520 && scrollPos <= 1350) {
      return setIsVisible(true)
    }else if (scrollPos > 1350) {
      return setIsVisible(false)
    }
  }

  const displayWindowSize = () => {
    let w = window.innerWidth;
    if(w >= 500) {
      return setIsDesktop(true)
    } else {
      return setIsDesktop(false)
    }
  }
</code>```

答:
window.innerWidth is not a boolean. If you intented to set it to true for a value other than 0 you can do:

```<code>const [isDesktop, setIsDesktop] = useState(!!window.innerWidth)
</code>```

You can also compare it to your breakpoint:

```<code>const [isDesktop, setIsDesktop] = useState(window.innerWidth >= 500);
</code>```

EDIT:

If you want to use isDesktop in the UpdateScrollPosition handler you need to unregister the old handler and register a new handler as a listener, when isDesktop has changed:

```<code>const UpdateScrollPosition = useCallback(() => {

    // this now depends on isDesktop
    console.log(isDesktop);

    // .... other code

}, [isDesktop]); // IMPORTANT: add isDesktop here as a dependency

useEffect(() => {
    window.addEventListener("scroll", UpdateScrollPosition);

    return () => window.removeEventListener("scroll", UpdateScrollPosition);
}, [UpdateScrollPosition]); // IMPORTANT: Add UpdateScrollPosition here as a dependency
</code>```

What does this?:

useCallback will recreate your handler when the isDesktop dependency changes. Your effect will re-bind the handlers when UpdateScrollPosition changes (which is always the case when isDesktop changes as we added it as a dependency there).

Body:
I have the isDesktop boolean that should be set to true or false depending on the sceensize and this works however on initial render it doesn't set to true/false, how can I set this on intial render?

 const [isVisible, setIsVisible] = useState(false)
  const [isDesktop, setIsDesktop] = useState(window.innerWidth)

  console.log(isDesktop)
  useEffect(() => {
    window.addEventListener("scroll", UpdateScrollPosition);
    window.addEventListener("resize", displayWindowSize);
    return () => window.removeEventListener("scroll", UpdateScrollPosition);
  }, []);

  const UpdateScrollPosition = () => {
    const scrollPos = window.scrollY
    if( scrollPos < 520) {
      return setIsVisible(false)
    }else if (scrollPos >= 520 && scrollPos <= 1350) {
      return setIsVisible(true)
    }else if (scrollPos > 1350) {
      return setIsVisible(false)
    }
  }

  const displayWindowSize = () => {
    let w = window.innerWidth;
    if(w >= 500) {
      return setIsDesktop(true)
    } else {
      return setIsDesktop(false)
    }
  }

Body:
window.innerWidth is not a boolean. If you intented to set it to true for a value other than 0 you can do:

const [isDesktop, setIsDesktop] = useState(!!window.innerWidth)

You can also compare it to your breakpoint:

const [isDesktop, setIsDesktop] = useState(window.innerWidth >= 500);

EDIT:

If you want to use isDesktop in the UpdateScrollPosition handler you need to unregister the old handler and register a new handler as a listener, when isDesktop has changed:

const UpdateScrollPosition = useCallback(() => {

    // this now depends on isDesktop
    console.log(isDesktop);

    // .... other code

}, [isDesktop]); // IMPORTANT: add isDesktop here as a dependency

useEffect(() => {
    window.addEventListener("scroll", UpdateScrollPosition);

    return () => window.removeEventListener("scroll", UpdateScrollPosition);
}, [UpdateScrollPosition]); // IMPORTANT: Add UpdateScrollPosition here as a dependency

What does this?:

useCallback will recreate your handler when the isDesktop dependency changes. Your effect will re-bind the handlers when UpdateScrollPosition changes (which is always the case when isDesktop changes as we added it as a dependency there).


问:
How do I add an environment variable for a windows user

I have a sheduling engine that runs
jobs on windows 2003 server.

It runs as a particular domain user.

I don't have access to log on as the
user but I have admin access.

I need to be able to script storing a
password in an environment variable
that is specific to the user

The user does not appear to have an
environment on the target platform
because HKU\SID does not exist in the
registry for the user. (SID is the
users domain SID)

but it has a profile

I cant add
HKU\SID\Environment\VAR_NAME ....
using reg.exe, it returns ERROR: The
parameter is incorrect.

Any ideas?

答: Can you use a login script with the SET command to create the environment variable?</p>


问:
Laravel route url and vuejs axious not working with unicode utf-8 issue
I use my project in slug . when i use English that work fine.But when i use unicode/bangla its show in this picture .<img src="https://i.stack.imgur.com/aGi6P.jpg" alt="enter image description here">
 axious not working </p>

答:
Change your request like this, it'll help

```<code> let url = http://127.0.0.1:8000/en/blog/${this.$route.params.id};
 axios.get(encodeURI(url))
</code>```

And in your controller just take it as usual

Body:
I use my project in slug . when i use English that work fine.But when i use unicode/bangla its show in this picture .
 axious not working

Body:
Change your request like this, it'll help

 let url = http://127.0.0.1:8000/en/blog/${this.$route.params.id};
 axios.get(encodeURI(url))

And in your controller just take it as usual


问:
Get base64 string from plotly.js from promise
I would like to get plot as image in base64 format from plotly.js

This is my code:

```<code>async myfunc() {
      return await Plotly.plot('teams-trace', dataSessions, layout).then((gd) => {
        return Plotly.toImage(gd, {format: 'png', height: 1080, width: 1920});
      }).then((dataURI) => {
        return dataURI;
      });
}
</code>```

I need to return dataURI as a string. But now it returns as an object.

答:
The reference for the toImage function can be found here

Try this refactor to your async func:

```<code>async function myfunc() {
  const gd = await Plotly.plot('teams-trace', dataSessions, layout);
  return await Plotly.toImage(gd, {format: 'png', height: 1080, width: 1920});
}
</code>```

Codepen link

Body:
I would like to get plot as image in base64 format from plotly.js

This is my code:

async myfunc() {
      return await Plotly.plot('teams-trace', dataSessions, layout).then((gd) => {
        return Plotly.toImage(gd, {format: 'png', height: 1080, width: 1920});
      }).then((dataURI) => {
        return dataURI;
      });
}

I need to return dataURI as a string. But now it returns as an object.

Body:
The reference for the toImage function can be found here

Try this refactor to your async func:

async function myfunc() {
  const gd = await Plotly.plot('teams-trace', dataSessions, layout);
  return await Plotly.toImage(gd, {format: 'png', height: 1080, width: 1920});
}

Codepen link


答:
You can create a collection data type:

CREATE TYPE stringlist IS TABLE OF VARCHAR2(200);
```

<p>And then split the strings into collections of words and compare the collections:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT left,
       right,
       CASE
       WHEN left = right THEN 'same'
       WHEN left_words = right_words THEN 'swapped'
       WHEN left_words SUBMULTISET OF right_words THEN 'contains'
       WHEN right_words SUBMULTISET OF left_words THEN 'contained in'
       ELSE 'not_same'
       END AS pattern
FROM   (
  SELECT left,
         right,
         ( SELECT CAST(
                    COLLECT( REGEXP_SUBSTR( left, '[^ ]+', 1, LEVEL ) )
                    AS stringlist
                  )
           FROM   DUAL
           CONNECT BY
                  LEVEL <= REGEXP_COUNT( left, '[^ ]+' )
         ) AS left_words,
         ( SELECT CAST(
                    COLLECT( REGEXP_SUBSTR( right, '[^ ]+', 1, LEVEL ) )
                    AS stringlist
                  )
           FROM   DUAL
           CONNECT BY
                  LEVEL <= REGEXP_COUNT( right, '[^ ]+' )
         ) AS right_words
  FROM   test_data t
)
</code>```

So for your test data:

CREATE TABLE test_data ( left, right ) AS
SELECT 'Kiki Cola 50 ml bottle', 'Kiki Cola 50 ml bottle' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', '50 ml Kiki Cola bottle' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', 'Kiki Cola 50 ml' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', 'Kiki Cola Light 50 ml bottle' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', 'Coca Cola 50 ml bottle' FROM DUAL;
```

<p>The query outputs:</p>

<blockquote>
```
LEFT                   | RIGHT                        | PATTERN
:--------------------- | :--------------------------- | :-----------
Kiki Cola 50 ml bottle | Kiki Cola 50 ml bottle       | same
Kiki Cola 50 ml bottle | 50 ml Kiki Cola bottle       | swapped
Kiki Cola 50 ml bottle | Kiki Cola 50 ml              | contained in
Kiki Cola 50 ml bottle | Kiki Cola Light 50 ml bottle | contains
Kiki Cola 50 ml bottle | Coca Cola 50 ml bottle       | not_same
```

db<>fiddle here

Title: Split and compare two Strings in Oracle SQL

Body:
I have a table with three columns structured as followed:

+------------------------+------------------------------+--------------+
| left                   | right                        | pattern      |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Kiki Cola 50 ml bottle       |              |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | 50 ml Kiki Cola bottle       |              |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Kiki Cola 50 ml              |              |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Kiki Cola Light bottle 50 ml |              |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Coca Cola 50 ml bottle       |              |
+------------------------+------------------------------+--------------+

Now I would like to perform an Oracle-SQL-query which gives me the edit-pattern of the two strings left and right. The result should be as followed:

+------------------------+------------------------------+--------------+
| left                   | right                        | pattern      |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Kiki Cola 50 ml bottle       | SAME         |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | 50 ml Kiki Cola bottle       | SWAPPED      |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Kiki Cola 50 ml              | CONTAINED_IN |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Kiki Cola Light bottle 50 ml | CONTAINS     |
+------------------------+------------------------------+--------------+
| Kiki Cola 50 ml bottle | Coca Cola 50 ml bottle       | NOT_SAME     |
+------------------------+------------------------------+--------------+

Al my tries with REGEX_SPLIT and CONNECT BY were not successful. Do you have any ideas how to solve that problem?

Body:
You can create a collection data type:

CREATE TYPE stringlist IS TABLE OF VARCHAR2(200);

And then split the strings into collections of words and compare the collections:

SELECT left,
       right,
       CASE
       WHEN left = right THEN 'same'
       WHEN left_words = right_words THEN 'swapped'
       WHEN left_words SUBMULTISET OF right_words THEN 'contains'
       WHEN right_words SUBMULTISET OF left_words THEN 'contained in'
       ELSE 'not_same'
       END AS pattern
FROM   (
  SELECT left,
         right,
         ( SELECT CAST(
                    COLLECT( REGEXP_SUBSTR( left, '[^ ]+', 1, LEVEL ) )
                    AS stringlist
                  )
           FROM   DUAL
           CONNECT BY
                  LEVEL <= REGEXP_COUNT( left, '[^ ]+' )
         ) AS left_words,
         ( SELECT CAST(
                    COLLECT( REGEXP_SUBSTR( right, '[^ ]+', 1, LEVEL ) )
                    AS stringlist
                  )
           FROM   DUAL
           CONNECT BY
                  LEVEL <= REGEXP_COUNT( right, '[^ ]+' )
         ) AS right_words
  FROM   test_data t
)

So for your test data:

CREATE TABLE test_data ( left, right ) AS
SELECT 'Kiki Cola 50 ml bottle', 'Kiki Cola 50 ml bottle' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', '50 ml Kiki Cola bottle' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', 'Kiki Cola 50 ml' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', 'Kiki Cola Light 50 ml bottle' FROM DUAL UNION ALL
SELECT 'Kiki Cola 50 ml bottle', 'Coca Cola 50 ml bottle' FROM DUAL;

The query outputs:

LEFT                   | RIGHT                        | PATTERN
:--------------------- | :--------------------------- | :-----------
Kiki Cola 50 ml bottle | Kiki Cola 50 ml bottle       | same
Kiki Cola 50 ml bottle | 50 ml Kiki Cola bottle       | swapped
Kiki Cola 50 ml bottle | Kiki Cola 50 ml              | contained in
Kiki Cola 50 ml bottle | Kiki Cola Light 50 ml bottle | contains
Kiki Cola 50 ml bottle | Coca Cola 50 ml bottle       | not_same

db<>fiddle here


问:
How to WordPess CRON auto run every 1 minutes in localhost
When i load page cron running good but we want auto run every 60 seconds in localhost.
Any one help me.</p>

```<code>add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
    $schedules['every_three_minutes'] = array(
            'interval'  => 60,
            'display'   => __( 'Every 1 Minutes', 'textdomain' )
    );
    return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
    wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}

// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func' );
function every_three_minutes_event_func() {
    $content = "some text here";
    $fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/wordpressrootfolder/".time()."-myText.txt","wb");
    fwrite($fp,$content);
    fclose($fp);
}
</code>```

答: Wordpress CronJobs work a little different then traditional CronJobs. They will only run when WordPress is loaded, if the interval time has passed. As such, on localhost, you would have to find a way for the page to be loaded regularly. </p>

Body:
When i load page cron running good but we want auto run every 60 seconds in localhost.
Any one help me.

add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
    $schedules['every_three_minutes'] = array(
            'interval'  => 60,
            'display'   => __( 'Every 1 Minutes', 'textdomain' )
    );
    return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
    wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}

// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func' );
function every_three_minutes_event_func() {
    $content = "some text here";
    $fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/wordpressrootfolder/".time()."-myText.txt","wb");
    fwrite($fp,$content);
    fclose($fp);
}


问:
PHP and Redirect with apache2.conf
I have an internal domain like

live.domain.com

which I defined in sites-available like so

```<code>ServerName live.domain.com

    ServerAdmin webmaster@localhost
    DocumentRoot /data/www/html/mydomainnamenodots

        <Directory /data/www/html/mydomainnamenodots>
           Require all granted
        </Directory>
</code>```

and the accordingly same for SSL conf.

I do have a folder /api which is in there like
/data/www/html/mydomainnamenodots/api

What I want is to catch all calls to
live.domain.com/api/*

and redirect them to something like
live.domain.com/api/index.php?url=*

So a real example would be

live.domain.com/api/statistics/getFTE/123/456

and I'd like that to be

live.domain.com/api/index.php?url=/statistics/getFTE/123/456

That would result in a $_REQUEST in index.php like so

array(1) {["url"]=>string(33) "/statistics/getFTE/123/456"}

mod_rewrite is enabled and loaded. Simple tests with file to file redirects work.

My rewrite rule which does not work as it does not redirect is

```<code><Directory "/data/www/html/mydomainnamenodots/api">
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*?mydomainnamenodots\/api(.*)$ /mydomainnamenodots/api/index.php?url=$1 [QSA,L]
</Directory>
</code>```

Any ideas why that does not work?
Am I missing the RewriteBase or something?

Thanks in advance

Alex

答:
As the subdomain already points to a subfolder, it has to be the the according subfolder below that one in the directory definition. In addition I changed the regexp as well.

Here is what worked for me:

```<code><Directory />
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^.*\/api(\/.*)$ /api/index.php?url=\/$1 [QSA,L]
</Directory>
</code>```

Title: PHP and Redirect with apache2.conf

Body:
I have an internal domain like

live.domain.com

which I defined in sites-available like so

ServerName live.domain.com

    ServerAdmin webmaster@localhost
    DocumentRoot /data/www/html/mydomainnamenodots

        <Directory /data/www/html/mydomainnamenodots>
           Require all granted
        </Directory>

and the accordingly same for SSL conf.

I do have a folder /api which is in there like
/data/www/html/mydomainnamenodots/api

What I want is to catch all calls to
live.domain.com/api/*

and redirect them to something like
live.domain.com/api/index.php?url=*

So a real example would be

live.domain.com/api/statistics/getFTE/123/456

and I'd like that to be

live.domain.com/api/index.php?url=/statistics/getFTE/123/456

That would result in a $_REQUEST in index.php like so

array(1) {["url"]=>string(33) "/statistics/getFTE/123/456"}

mod_rewrite is enabled and loaded. Simple tests with file to file redirects work.

My rewrite rule which does not work as it does not redirect is

<Directory "/data/www/html/mydomainnamenodots/api">
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*?mydomainnamenodots\/api(.*)$ /mydomainnamenodots/api/index.php?url=$1 [QSA,L]
</Directory>

Any ideas why that does not work?
Am I missing the RewriteBase or something?

Thanks in advance

Alex

Body:
As the subdomain already points to a subfolder, it has to be the the according subfolder below that one in the directory definition. In addition I changed the regexp as well.

Here is what worked for me:

<Directory />
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^.*\/api(\/.*)$ /api/index.php?url=\/$1 [QSA,L]
</Directory>


答:
PHP has usort, a function enabling you to sort via a user-provided comparison function. There's also uasort that maintains index association.

Here's an example:

```<code><?php
$array = Array(
  9 => Array(
            15.00 => 3.0,
            20.00 => 8.0,
            25.00 => 10.5
  ),
  2 => Array(
            15.00 => 2.0,
            20.00 => 5.0,
            25.00 => 2.5
  ),
  4 => Array(
            15.00 => 6.0,
            25.00 => 4.0,
            30.00 => 6.0
  )
);

function my_func($a, $b) {
   if ($a[15.00] == $b[15.00])
      return 0;
   return ($a[15.00] < $b[15.00]) ? 1 : -1; // backwards sorting
}

uasort($array, my_func);
var_dump($array);
?>
</code>```

And here's it working.

Hope this helps.

Title: Sort an array that has highest point?

Body:
How do I sort array that has highest point from 15.00 key?

I have an array look like this:

Array
(

    [9] => Array
        (
            [15.00] => 3.0
            [20.00] => 8.0
            [25.00] => 10.5
        )

    [2] => Array
        (
            [15.00] => 2.0
            [20.00] => 5.0
            [25.00] => 2.5
        )

    [4] => Array
        (
            [15.00] => 6.0
            [25.00] => 4.0
            [30.00] => 6.0
        )
)

In order it should be: 4, 9 and 2

Body:
PHP has usort, a function enabling you to sort via a user-provided comparison function. There's also uasort that maintains index association.

Here's an example:

<?php
$array = Array(
  9 => Array(
            15.00 => 3.0,
            20.00 => 8.0,
            25.00 => 10.5
  ),
  2 => Array(
            15.00 => 2.0,
            20.00 => 5.0,
            25.00 => 2.5
  ),
  4 => Array(
            15.00 => 6.0,
            25.00 => 4.0,
            30.00 => 6.0
  )
);

function my_func($a, $b) {
   if ($a[15.00] == $b[15.00])
      return 0;
   return ($a[15.00] < $b[15.00]) ? 1 : -1; // backwards sorting
}

uasort($array, my_func);
var_dump($array);
?>

And here's it working.

Hope this helps.


问:
php array_merge_recursive is replacing some key strings with numeric keys
I am experiencing unexpected behaviour with the php function array_merge_recursive. Any advice or work-around would be appreciated.

The problem is with unexpected replacement of string keys with numeric key during the array_merge_recursive.

Details:

I have three associative arrays ($birthdays,$custom,$natHolidays), to which these values are programmatically added:

```<code>$birthdays['0808'][] = 'John MacLoud';
$birthdays['0819'][] = 'Susan MacLoud';
$birthdays['0903'][] = 'Catherine MacLoud';
$birthdays['1008'][] = 'Daisy Simpson';
$birthdays['1015'][] = 'Phillip MacLoud';
$birthdays['1212'][] = 'Aloysius Simpson';
$natHolidays['0317'][] = 'St. Patrick's Day';
$natHolidays['0317'][] = 'la Saint-Patrick';
$natHolidays['0701'][] = 'Canada Day';
$natHolidays['0701'][] = 'la fête du Canada';
$natHolidays['1031'][] = 'Hallowe'en';
$natHolidays['1031'][] = 'l'Halloween';
$natHolidays['1031'][] = 'Hallowe'en';
$natHolidays['1031'][] = 'l'Halloween';
$natHolidays['1111'][] = 'Remembrance Day';
$natHolidays['1111'][] = 'jour du souvenir';
$natHolidays['1224'][] = 'Christmas Eve';
$natHolidays['1224'][] = 'la vielle de Noël';
$natHolidays['1225'][] = 'Christmas';
$natHolidays['1225'][] = 'Noël';
$natHolidays['1226'][] = 'Boxing Day';
$natHolidays['1226'][] = 'le lendemain de Noël';
$natHolidays['1231'][] = 'New Year's Eve';
$natHolidays['1231'][] = 'vielle du jour de 'an';
$natHolidays['0907'][] = 'Labour Day';
$natHolidays['0907'][] = 'la fête du Travail';
$natHolidays['0922'][] = 'Equinox';
$natHolidays['0922'][] = 'l'equinoxe';
$natHolidays['1012'][] = 'Thanksgiving';
$natHolidays['1012'][] = 'l'action de grace';
$natHolidays['1101'][] = 'Daylight Savings ends';
$natHolidays['1101'][] = 'fall back';
$natHolidays['1221'][] = 'Solstice';
$natHolidays['1221'][] = 'le solstice';
$custom['0922'][] = 'Test value 1';
$custom['1122'][] = 'Test value 2';
</code>```

I then merge the arrays: $dates = array_merge_recursive($birthdays,$custom,$natHolidays);

The resulting $dates array outputs:

```<code>["0808"]=>
  array(1) {
    [0]=>
    string(13) "John MacLoud"
  }
  ["0819"]=>
  array(1) {
    [0]=>
    string(13) "Susan MacLoud"
  }
  ["0903"]=>
  array(1) {
    [0]=>
    string(14) "Catherine MacLoud"
  }
  [0]=>
  array(1) {
    [0]=>
    string(15) "Daisy Simpson"
  }
  [1]=>
  array(1) {
    [0]=>
    string(14) "Phillip MacLoud"
  }
  [2]=>
  array(1) {
    [0]=>
    string(13) "Aloysius Simpson"
  }
  ["0317"]=>
  array(2) {
    [0]=>
    string(22) "St. Patrick's Day"
    [1]=>
    string(16) "la Saint-Patrick"
  }
  ["0701"]=>
  array(2) {
    [0]=>
    string(10) "Canada Day"
    [1]=>
    string(18) "la fête du Canada"
  }
  [3]=>
  array(2) {
    [0]=>
    string(15) "Hallowe'en"
    [1]=>
    string(16) "l'Halloween"
  }
  [4]=>
  array(2) {
    [0]=>
    string(15) "Remembrance Day"
    [1]=>
    string(16) "jour du souvenir"
  }
  [5]=>
  array(2) {
    [0]=>
    string(13) "Christmas Eve"
    [1]=>
    string(18) "la vielle de Noël"
  }
  [6]=>
  array(2) {
    [0]=>
    string(9) "Christmas"
    [1]=>
    string(5) "Noël"
  }
  [7]=>
  array(2) {
    [0]=>
    string(10) "Boxing Day"
    [1]=>
    string(21) "le lendemain de Noël"
  }
  [8]=>
  array(2) {
    [0]=>
    string(19) "New Year's Eve"
    [1]=>
    string(26) "vielle du jour de 'an"
  }
  ["0907"]=>
  array(2) {
    [0]=>
    string(10) "Labour Day"
    [1]=>
    string(19) "la fête du Travail"
  }
  ["0922"]=>
  array(3) {
    [0]=>
    string(14) "Test value 1"
    [1]=>
    string(7) "Equinox"
    [2]=>
    string(15) "l'equinoxe"
  }
  [9]=>
  array(1) {
    [0]=>
    string(15) "Test value 2"
  }
  [10]=>
  array(2) {
    [0]=>
    string(12) "Thanksgiving"
    [1]=>
    string(22) "l'action de grace"
  }
  [11]=>
  array(2) {
    [0]=>
    string(21) "Daylight Savings ends"
    [1]=>
    string(9) "fall back"
  }
  [12]=>
  array(2) {
    [0]=>
    string(8) "Solstice"
    [1]=>
    string(11) "le solstice"
  }
</code>```

The only pattern I have noticed is that any key string starting with a '0' (i.e. 0130) works as expected, and any key string starting with a '1' (i.e. 1022) replaces the string key with a sequential numeric key.

Thoughts?

Btw:

Creating the new tag 'array-merge-recursive' requires at least 1500
  reputation. Try something from the existing tags list instead.

答:
PHP is loosely typed, and it is casting your array keys.

You could use integer as keys to avoid the cast:

```<code>$arr[10] = 'foo';
</code>```

and not

```<code>$arr["10"] = 'foo';
</code>```

Updated answer:

The casting is treating keys starting with "0" as strings, and so far so good. The other keys are treated like integers, and array_merge will renumber them starting from 0 (as it is happening here).

I know you are using array_merge_recursive, but it appears to behave the same.

Body:
I am experiencing unexpected behaviour with the php function array_merge_recursive. Any advice or work-around would be appreciated.

The problem is with unexpected replacement of string keys with numeric key during the array_merge_recursive.

Details:

I have three associative arrays ($birthdays,$custom,$natHolidays), to which these values are programmatically added:

$birthdays['0808'][] = 'John MacLoud';
$birthdays['0819'][] = 'Susan MacLoud';
$birthdays['0903'][] = 'Catherine MacLoud';
$birthdays['1008'][] = 'Daisy Simpson';
$birthdays['1015'][] = 'Phillip MacLoud';
$birthdays['1212'][] = 'Aloysius Simpson';
$natHolidays['0317'][] = 'St. Patrick's Day';
$natHolidays['0317'][] = 'la Saint-Patrick';
$natHolidays['0701'][] = 'Canada Day';
$natHolidays['0701'][] = 'la fête du Canada';
$natHolidays['1031'][] = 'Hallowe'en';
$natHolidays['1031'][] = 'l'Halloween';
$natHolidays['1031'][] = 'Hallowe'en';
$natHolidays['1031'][] = 'l'Halloween';
$natHolidays['1111'][] = 'Remembrance Day';
$natHolidays['1111'][] = 'jour du souvenir';
$natHolidays['1224'][] = 'Christmas Eve';
$natHolidays['1224'][] = 'la vielle de Noël';
$natHolidays['1225'][] = 'Christmas';
$natHolidays['1225'][] = 'Noël';
$natHolidays['1226'][] = 'Boxing Day';
$natHolidays['1226'][] = 'le lendemain de Noël';
$natHolidays['1231'][] = 'New Year's Eve';
$natHolidays['1231'][] = 'vielle du jour de 'an';
$natHolidays['0907'][] = 'Labour Day';
$natHolidays['0907'][] = 'la fête du Travail';
$natHolidays['0922'][] = 'Equinox';
$natHolidays['0922'][] = 'l'equinoxe';
$natHolidays['1012'][] = 'Thanksgiving';
$natHolidays['1012'][] = 'l'action de grace';
$natHolidays['1101'][] = 'Daylight Savings ends';
$natHolidays['1101'][] = 'fall back';
$natHolidays['1221'][] = 'Solstice';
$natHolidays['1221'][] = 'le solstice';
$custom['0922'][] = 'Test value 1';
$custom['1122'][] = 'Test value 2';

I then merge the arrays: $dates = array_merge_recursive($birthdays,$custom,$natHolidays);

The resulting $dates array outputs:

["0808"]=>
  array(1) {
    [0]=>
    string(13) "John MacLoud"
  }
  ["0819"]=>
  array(1) {
    [0]=>
    string(13) "Susan MacLoud"
  }
  ["0903"]=>
  array(1) {
    [0]=>
    string(14) "Catherine MacLoud"
  }
  [0]=>
  array(1) {
    [0]=>
    string(15) "Daisy Simpson"
  }
  [1]=>
  array(1) {
    [0]=>
    string(14) "Phillip MacLoud"
  }
  [2]=>
  array(1) {
    [0]=>
    string(13) "Aloysius Simpson"
  }
  ["0317"]=>
  array(2) {
    [0]=>
    string(22) "St. Patrick's Day"
    [1]=>
    string(16) "la Saint-Patrick"
  }
  ["0701"]=>
  array(2) {
    [0]=>
    string(10) "Canada Day"
    [1]=>
    string(18) "la fête du Canada"
  }
  [3]=>
  array(2) {
    [0]=>
    string(15) "Hallowe'en"
    [1]=>
    string(16) "l'Halloween"
  }
  [4]=>
  array(2) {
    [0]=>
    string(15) "Remembrance Day"
    [1]=>
    string(16) "jour du souvenir"
  }
  [5]=>
  array(2) {
    [0]=>
    string(13) "Christmas Eve"
    [1]=>
    string(18) "la vielle de Noël"
  }
  [6]=>
  array(2) {
    [0]=>
    string(9) "Christmas"
    [1]=>
    string(5) "Noël"
  }
  [7]=>
  array(2) {
    [0]=>
    string(10) "Boxing Day"
    [1]=>
    string(21) "le lendemain de Noël"
  }
  [8]=>
  array(2) {
    [0]=>
    string(19) "New Year's Eve"
    [1]=>
    string(26) "vielle du jour de 'an"
  }
  ["0907"]=>
  array(2) {
    [0]=>
    string(10) "Labour Day"
    [1]=>
    string(19) "la fête du Travail"
  }
  ["0922"]=>
  array(3) {
    [0]=>
    string(14) "Test value 1"
    [1]=>
    string(7) "Equinox"
    [2]=>
    string(15) "l'equinoxe"
  }
  [9]=>
  array(1) {
    [0]=>
    string(15) "Test value 2"
  }
  [10]=>
  array(2) {
    [0]=>
    string(12) "Thanksgiving"
    [1]=>
    string(22) "l'action de grace"
  }
  [11]=>
  array(2) {
    [0]=>
    string(21) "Daylight Savings ends"
    [1]=>
    string(9) "fall back"
  }
  [12]=>
  array(2) {
    [0]=>
    string(8) "Solstice"
    [1]=>
    string(11) "le solstice"
  }

The only pattern I have noticed is that any key string starting with a '0' (i.e. 0130) works as expected, and any key string starting with a '1' (i.e. 1022) replaces the string key with a sequential numeric key.

Thoughts?

Btw:

Creating the new tag 'array-merge-recursive' requires at least 1500
  reputation. Try something from the existing tags list instead.

Body:
PHP is loosely typed, and it is casting your array keys.

You could use integer as keys to avoid the cast:

$arr[10] = 'foo';

and not

$arr["10"] = 'foo';

Updated answer:

The casting is treating keys starting with "0" as strings, and so far so good. The other keys are treated like integers, and array_merge will renumber them starting from 0 (as it is happening here).

I know you are using array_merge_recursive, but it appears to behave the same.


问:
CMake project compilation error on VisualStudio using external SDK toolchain file
I am using VisualStudio CMake project on Windows machine.

I am using an external SDK in order to cross compile my C++ program for Linux arm architecture.

I added the SDK toolchain to cmakeToolchain path which is :

/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake

and this is my CMakeLists.txt file :

```<code>set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED OFF)
set(Boost_USE_STATIC_RUNTIME OFF)
#list(APPEND CMAKE_PREFIX_PATH /home/ubuntu/linux4sam/poky/build-microchip/tmp/sysroots-components/cortexa5hf-neon/boost/usr/include/boost)
list(APPEND CMAKE_PREFIX_PATH /opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include)
Set(Boost_NO_BOOST_CMAKE ON)
#set(BOOST_ROOT "/home/ubuntu/linux4sam/poky/build-microchip/tmp/sysroots-components/cortexa5hf-neon/boost")

message(STATUS "CMAKE_TOOLCHAIN_FILE='${CMAKE_TOOLCHAIN_FILE}'")
set(CROSS_COMPILER_DIR /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr)
set(CMAKE_C_COMPILER ${CROSS_COMPILER_DIR}/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc)
set(CMAKE_CXX_COMPILER ${CROSS_COMPILER_DIR}/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc)

#set(CMAKE_SYSTEM_NAME Linux)

message(STATUS "CMAKE_C_COMPILER='${CMAKE_C_COMPILER}'")
message(STATUS "CMAKE_CXX_COMPILER='${CMAKE_CXX_COMPILER}'")

find_package(Boost 1.66.0)

if(Boost_FOUND)

    message (STATUS "success!")
    add_executable (CMakeProject4 "CMakeProject4.cpp" "CMakeProject4.h")
    include_directories(${Boost_INCLUDE_DIRS})
    target_link_libraries(CMakeProject4 ${Boost_LIBRARIES})

endif()
</code>```

As you can see I am setting my SDK compilers bin paths to CMAKE_C_COMPILER and CMAKE_CXX_COMPILER variables.

When I Debug, I find that :

```<code>1> Copying files to the remote machine.
1> Starting copying files to remote machine.
1> [rsync] rsync -t --delete --delete-excluded -v -r --exclude=.vs --exclude=.git --exclude=out  "." rsync://ubuntu@localhost:56934/-home-ubuntu-CMake-RemoteCML
1> [rsync] sending incremental file list
1> [rsync]
1> [rsync] sent 229 bytes  received 13 bytes  161.33 bytes/sec
1> [rsync] total size is 4,429  speedup is 18.30
1> Finished copying files (elapsed time 00h:00m:04s:043ms).
1> CMake generation started for configuration: 'Linux-Release'.
1> Found cmake executable at /home/ubuntu/.vs/cmake/bin/cmake.
1> /home/ubuntu/.vs/cmake/bin/cmake -G "Unix Makefiles"  -DCMAKE_BUILD_TYPE="RelWithDebInfo" -DBoost_INCLUDE_DIRS:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_LIBRARIES:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/lib" -DBoost_INCLUDE_DIR:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_DEBUG=ON -DCMAKE_CXX_COMPILER=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc -DCMAKE_TOOLCHAIN_FILE="/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake" -DCMAKE_INSTALL_PREFIX=/home/ubuntu/CMake/RemoteIL "/home/ubuntu/CMake/RemoteCML/CMakeLists.txt";
1> [CMake] -- The C compiler identification is GNU 7.4.0
1> [CMake] -- The CXX compiler identification is GNU 7.3.0
1> [CMake] -- Check for working C compiler: /usr/bin/cc
1> [CMake] -- Check for working C compiler: /usr/bin/cc -- works
1> [CMake] -- Detecting C compiler ABI info
1> [CMake] -- Detecting C compiler ABI info - done
1> [CMake] -- Detecting C compile features
1> [CMake] -- Detecting C compile features - done
1> [CMake] -- Check for working CXX compiler: /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc
1> [CMake] -- Check for working CXX compiler: /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc -- broken
1> [CMake] CMake Error at /home/ubuntu/.vs/cmake/share/cmake-3.15/Modules/CMakeTestCXXCompiler.cmake:53 (message):
1> [CMake]   The C++ compiler
1> [CMake]
1> [CMake]     "/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc"
1> [CMake]
1> [CMake]   is not able to compile a simple test program.
1> [CMake]
1> [CMake]   It fails with the following output:
1> [CMake]
1> [CMake]     Change Dir: /home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp
1> [CMake]
1> [CMake]     Run Build Command(s):/usr/bin/make cmTC_2cb5a/fast && /usr/bin/make -f CMakeFiles/cmTC_2cb5a.dir/build.make CMakeFiles/cmTC_2cb5a.dir/build
1> [CMake]     make[1]: Entering directory '/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp'
1> [CMake]     Building CXX object CMakeFiles/cmTC_2cb5a.dir/testCXXCompiler.cxx.o
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc     -o CMakeFiles/cmTC_2cb5a.dir/testCXXCompiler.cxx.o -c /home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
1> [CMake]     Linking CXX executable cmTC_2cb5a
1> [CMake]     /home/ubuntu/.vs/cmake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_2cb5a.dir/link.txt --verbose=1
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc       CMakeFiles/cmTC_2cb5a.dir/testCXXCompiler.cxx.o  -o cmTC_2cb5a
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crt1.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crti.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crtbegin.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc_s
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lc
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc_s
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crtend.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crtn.o: No such file or directory
1> [CMake]     collect2: error: ld returned 1 exit status
1> [CMake]     CMakeFiles/cmTC_2cb5a.dir/build.make:86: recipe for target 'cmTC_2cb5a' failed
1> [CMake]     make[1]: *** [cmTC_2cb5a] Error 1
1> [CMake]     make[1]: Leaving directory '/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp'
1> [CMake]     Makefile:121: recipe for target 'cmTC_2cb5a/fast' failed
1> [CMake]     make: *** [cmTC_2cb5a/fast] Error 2
1> [CMake]
1> [CMake]
1> [CMake]   CMake will not be able to correctly generate this project.
1> [CMake] Call Stack (most recent call first):
1> [CMake]   CMakeLists.txt:6 (project)
1> [CMake] -- Configuring incomplete, errors occurred!
1> [CMake] See also "/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeOutput.log".
1> [CMake] See also "/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeError.log".
1> cd "/home/ubuntu/CMake/RemoteBR";/home/ubuntu/.vs/cmake/bin/cmake -G "Unix Makefiles"  -DCMAKE_BUILD_TYPE="RelWithDebInfo" -DBoost_INCLUDE_DIRS:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_LIBRARIES:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/lib" -DBoost_INCLUDE_DIR:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_DEBUG=ON -DCMAKE_CXX_COMPILER=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc -DCMAKE_TOOLCHAIN_FILE="/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake" -DCMAKE_INSTALL_PREFIX=/home/ubuntu/CMake/RemoteIL "/home/ubuntu/CMake/RemoteCML" 2>&1; returned with exit code: 1
</code>```

I can see here that CMake can identify the SDK toolchain compiler which I want to use which is GNU 7.3.0 but it's broken!
 When I open CMakeCache.txt , I find this :

```<code>//No help, variable specified on the command line.
CMAKE_CXX_COMPILER:UNINITIALIZED=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc

//A wrapper around 'ar' adding the appropriate '--plugin' option
// for the GCC compiler
CMAKE_CXX_COMPILER_AR:FILEPATH=/usr/bin/gcc-ar-7

//A wrapper around 'ranlib' adding the appropriate '--plugin' option
// for the GCC compiler
CMAKE_CXX_COMPILER_RANLIB:FILEPATH=/usr/bin/gcc-ranlib-7

CMAKE_CXX_FLAGS:STRING=

//Flags used by the CXX compiler during DEBUG builds.
CMAKE_CXX_FLAGS_DEBUG:STRING=-g

//Flags used by the CXX compiler during MINSIZEREL builds.
CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG

//Flags used by the CXX compiler during RELEASE builds.
CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG

//Flags used by the CXX compiler during RELWITHDEBINFO builds.
CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG

//No help, variable specified on the command line.
CMAKE_TOOLCHAIN_FILE:UNINITIALIZED=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake
</code>```

This is my C++ .cpp file program :

```<code>#include "CMakeProject4.h"
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int main()
{
    typedef std::istream_iterator<int> in;

    std::cout << "Type in any number: ";

    std::for_each(
        in(std::cin), in(), std::cout
        << (boost::lambda::_1 * 10)
        << "\nType in another number: ");
}
</code>```

But when I try to run CMake in order to compile my program using :

```<code>cmake -DBoost_DEBUG=ON -DCMAKE_CXX_COMPILER=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc
</code>```

I have this error :

Error Compilation

Any help please ?

答:
When you use a toolchain file, you shouldn't set the compiler yourself. You should let it to the toolchain file, as it know how to cross compile. Things like CMAKE_SYSTEM_NAME and CMAKE_SYSTEM_PROCESSOR should be left to the toolchain file.

```<code>set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED OFF)
set(Boost_USE_STATIC_RUNTIME OFF)
set(Boost_NO_BOOST_CMAKE ON)

# I think the prefix should point to usr directly, not the include directory
list(APPEND CMAKE_PREFIX_PATH /opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr)

message(STATUS "CMAKE_TOOLCHAIN_FILE='${CMAKE_TOOLCHAIN_FILE}'")
message(STATUS "CMAKE_C_COMPILER='${CMAKE_C_COMPILER}'")
message(STATUS "CMAKE_CXX_COMPILER='${CMAKE_CXX_COMPILER}'")

project(whatever CXX)

# Better to fail fast when there's a package missing
find_package(Boost 1.66.0 REQUIRED)

add_executable (CMakeProject4 CMakeProject4.cpp CMakeProject4.h)
target_link_libraries(CMakeProject4 PRIVATE Boost::headers)
</code>```

And your CMake arguments should look like this:

```<code>cmake -DCMAKE_TOOLCHAIN_FILE=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake
</code>```

Body:
I am using VisualStudio CMake project on Windows machine.

I am using an external SDK in order to cross compile my C++ program for Linux arm architecture.

I added the SDK toolchain to cmakeToolchain path which is :

/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake

and this is my CMakeLists.txt file :

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)

set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED OFF)
set(Boost_USE_STATIC_RUNTIME OFF)
#list(APPEND CMAKE_PREFIX_PATH /home/ubuntu/linux4sam/poky/build-microchip/tmp/sysroots-components/cortexa5hf-neon/boost/usr/include/boost)
list(APPEND CMAKE_PREFIX_PATH /opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include)
Set(Boost_NO_BOOST_CMAKE ON)
#set(BOOST_ROOT "/home/ubuntu/linux4sam/poky/build-microchip/tmp/sysroots-components/cortexa5hf-neon/boost")

message(STATUS "CMAKE_TOOLCHAIN_FILE='${CMAKE_TOOLCHAIN_FILE}'")
set(CROSS_COMPILER_DIR /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr)
set(CMAKE_C_COMPILER ${CROSS_COMPILER_DIR}/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc)
set(CMAKE_CXX_COMPILER ${CROSS_COMPILER_DIR}/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc)

#set(CMAKE_SYSTEM_NAME Linux)

message(STATUS "CMAKE_C_COMPILER='${CMAKE_C_COMPILER}'")
message(STATUS "CMAKE_CXX_COMPILER='${CMAKE_CXX_COMPILER}'")

find_package(Boost 1.66.0)

if(Boost_FOUND)

    message (STATUS "success!")
    add_executable (CMakeProject4 "CMakeProject4.cpp" "CMakeProject4.h")
    include_directories(${Boost_INCLUDE_DIRS})
    target_link_libraries(CMakeProject4 ${Boost_LIBRARIES})

endif()

As you can see I am setting my SDK compilers bin paths to CMAKE_C_COMPILER and CMAKE_CXX_COMPILER variables.

When I Debug, I find that :

1> Copying files to the remote machine.
1> Starting copying files to remote machine.
1> [rsync] rsync -t --delete --delete-excluded -v -r --exclude=.vs --exclude=.git --exclude=out  "." rsync://ubuntu@localhost:56934/-home-ubuntu-CMake-RemoteCML
1> [rsync] sending incremental file list
1> [rsync]
1> [rsync] sent 229 bytes  received 13 bytes  161.33 bytes/sec
1> [rsync] total size is 4,429  speedup is 18.30
1> Finished copying files (elapsed time 00h:00m:04s:043ms).
1> CMake generation started for configuration: 'Linux-Release'.
1> Found cmake executable at /home/ubuntu/.vs/cmake/bin/cmake.
1> /home/ubuntu/.vs/cmake/bin/cmake -G "Unix Makefiles"  -DCMAKE_BUILD_TYPE="RelWithDebInfo" -DBoost_INCLUDE_DIRS:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_LIBRARIES:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/lib" -DBoost_INCLUDE_DIR:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_DEBUG=ON -DCMAKE_CXX_COMPILER=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc -DCMAKE_TOOLCHAIN_FILE="/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake" -DCMAKE_INSTALL_PREFIX=/home/ubuntu/CMake/RemoteIL "/home/ubuntu/CMake/RemoteCML/CMakeLists.txt";
1> [CMake] -- The C compiler identification is GNU 7.4.0
1> [CMake] -- The CXX compiler identification is GNU 7.3.0
1> [CMake] -- Check for working C compiler: /usr/bin/cc
1> [CMake] -- Check for working C compiler: /usr/bin/cc -- works
1> [CMake] -- Detecting C compiler ABI info
1> [CMake] -- Detecting C compiler ABI info - done
1> [CMake] -- Detecting C compile features
1> [CMake] -- Detecting C compile features - done
1> [CMake] -- Check for working CXX compiler: /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc
1> [CMake] -- Check for working CXX compiler: /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc -- broken
1> [CMake] CMake Error at /home/ubuntu/.vs/cmake/share/cmake-3.15/Modules/CMakeTestCXXCompiler.cmake:53 (message):
1> [CMake]   The C++ compiler
1> [CMake]
1> [CMake]     "/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc"
1> [CMake]
1> [CMake]   is not able to compile a simple test program.
1> [CMake]
1> [CMake]   It fails with the following output:
1> [CMake]
1> [CMake]     Change Dir: /home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp
1> [CMake]
1> [CMake]     Run Build Command(s):/usr/bin/make cmTC_2cb5a/fast && /usr/bin/make -f CMakeFiles/cmTC_2cb5a.dir/build.make CMakeFiles/cmTC_2cb5a.dir/build
1> [CMake]     make[1]: Entering directory '/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp'
1> [CMake]     Building CXX object CMakeFiles/cmTC_2cb5a.dir/testCXXCompiler.cxx.o
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc     -o CMakeFiles/cmTC_2cb5a.dir/testCXXCompiler.cxx.o -c /home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
1> [CMake]     Linking CXX executable cmTC_2cb5a
1> [CMake]     /home/ubuntu/.vs/cmake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_2cb5a.dir/link.txt --verbose=1
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc       CMakeFiles/cmTC_2cb5a.dir/testCXXCompiler.cxx.o  -o cmTC_2cb5a
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crt1.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crti.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crtbegin.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc_s
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lc
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find -lgcc_s
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crtend.o: No such file or directory
1> [CMake]     /opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/7.3.0/real-ld: cannot find crtn.o: No such file or directory
1> [CMake]     collect2: error: ld returned 1 exit status
1> [CMake]     CMakeFiles/cmTC_2cb5a.dir/build.make:86: recipe for target 'cmTC_2cb5a' failed
1> [CMake]     make[1]: *** [cmTC_2cb5a] Error 1
1> [CMake]     make[1]: Leaving directory '/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeTmp'
1> [CMake]     Makefile:121: recipe for target 'cmTC_2cb5a/fast' failed
1> [CMake]     make: *** [cmTC_2cb5a/fast] Error 2
1> [CMake]
1> [CMake]
1> [CMake]   CMake will not be able to correctly generate this project.
1> [CMake] Call Stack (most recent call first):
1> [CMake]   CMakeLists.txt:6 (project)
1> [CMake] -- Configuring incomplete, errors occurred!
1> [CMake] See also "/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeOutput.log".
1> [CMake] See also "/home/ubuntu/CMake/RemoteBR/CMakeFiles/CMakeError.log".
1> cd "/home/ubuntu/CMake/RemoteBR";/home/ubuntu/.vs/cmake/bin/cmake -G "Unix Makefiles"  -DCMAKE_BUILD_TYPE="RelWithDebInfo" -DBoost_INCLUDE_DIRS:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_LIBRARIES:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/lib" -DBoost_INCLUDE_DIR:PATH="/opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr/include" -DBoost_DEBUG=ON -DCMAKE_CXX_COMPILER=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc -DCMAKE_TOOLCHAIN_FILE="/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake" -DCMAKE_INSTALL_PREFIX=/home/ubuntu/CMake/RemoteIL "/home/ubuntu/CMake/RemoteCML" 2>&1; returned with exit code: 1

I can see here that CMake can identify the SDK toolchain compiler which I want to use which is GNU 7.3.0 but it's broken!
 When I open CMakeCache.txt , I find this :

//No help, variable specified on the command line.
CMAKE_CXX_COMPILER:UNINITIALIZED=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc

//A wrapper around 'ar' adding the appropriate '--plugin' option
// for the GCC compiler
CMAKE_CXX_COMPILER_AR:FILEPATH=/usr/bin/gcc-ar-7

//A wrapper around 'ranlib' adding the appropriate '--plugin' option
// for the GCC compiler
CMAKE_CXX_COMPILER_RANLIB:FILEPATH=/usr/bin/gcc-ranlib-7

CMAKE_CXX_FLAGS:STRING=

//Flags used by the CXX compiler during DEBUG builds.
CMAKE_CXX_FLAGS_DEBUG:STRING=-g

//Flags used by the CXX compiler during MINSIZEREL builds.
CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG

//Flags used by the CXX compiler during RELEASE builds.
CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG

//Flags used by the CXX compiler during RELWITHDEBINFO builds.
CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG

//No help, variable specified on the command line.
CMAKE_TOOLCHAIN_FILE:UNINITIALIZED=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake

This is my C++ .cpp file program :

#include "CMakeProject4.h"
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int main()
{
    typedef std::istream_iterator<int> in;

    std::cout << "Type in any number: ";

    std::for_each(
        in(std::cin), in(), std::cout
        << (boost::lambda::_1 * 10)
        << "\nType in another number: ");
}

But when I try to run CMake in order to compile my program using :

cmake -DBoost_DEBUG=ON -DCMAKE_CXX_COMPILER=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc

I have this error :

Error Compilation

Any help please ?

Body:
When you use a toolchain file, you shouldn't set the compiler yourself. You should let it to the toolchain file, as it know how to cross compile. Things like CMAKE_SYSTEM_NAME and CMAKE_SYSTEM_PROCESSOR should be left to the toolchain file.

set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED OFF)
set(Boost_USE_STATIC_RUNTIME OFF)
set(Boost_NO_BOOST_CMAKE ON)

# I think the prefix should point to usr directly, not the include directory
list(APPEND CMAKE_PREFIX_PATH /opt/poky-atmel/2.5.3/sysroots/cortexa5hf-neon-poky-linux-gnueabi/usr)

message(STATUS "CMAKE_TOOLCHAIN_FILE='${CMAKE_TOOLCHAIN_FILE}'")
message(STATUS "CMAKE_C_COMPILER='${CMAKE_C_COMPILER}'")
message(STATUS "CMAKE_CXX_COMPILER='${CMAKE_CXX_COMPILER}'")

project(whatever CXX)

# Better to fail fast when there's a package missing
find_package(Boost 1.66.0 REQUIRED)

add_executable (CMakeProject4 CMakeProject4.cpp CMakeProject4.h)
target_link_libraries(CMakeProject4 PRIVATE Boost::headers)

And your CMake arguments should look like this:

cmake -DCMAKE_TOOLCHAIN_FILE=/opt/poky-atmel/2.5.3/sysroots/x86_64-pokysdk-linux/usr/share/cmake/OEToolchainConfig.cmake


问:
Search function for JSON populated table
I am trying to implement a search feature which enables the user to search through this table which is being populated from a JSON from a public api.

My table:

```<code><input type="text" id="myInput" onkeyup="searchPlayers()" placeholder="Search for player">
<table id ="player_info">
<tr>
<th>ID</th>
<th>Full Name</th>
<th>Team</th>
<th>Position</th>
<th>Current Price</th>
<th>Value Season</th>
<th>Cost Change from Start</th>
<th>Percentage selected by</th>
<th>Transfers In</th>
<th>Transfers Out</th>
<th>Total Points</th>
<th>Points Per Game</th>
<th>Minutes</th>
<th>Goals Scored</th>
<th>Assists</th>
</tr>
</code>```

Populating the table from the JSON. Iterating through the JSON file and create a new table cell for each of the keys.

```<code>request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response);

if (request.status >= 200 && request.status < 400) {

    var table = document.getElementById('player_info');

    data.elements.forEach(elements => {

    var tr = document.createElement('tr');
    tr.innerHTML = '<td>' + elements.id + '</td>' +
        '<td>' + elements.first_name + '<p>' + '</p>' + elements.second_name + '</td>' +
        '<td>' + elements.team_code + '</td>' +
        '<td>' + elements.element_type + '</td>' +
        '<td>' + elements.now_cost + '</td>' +
        '<td>' + elements.value_season+ '</td>' +
        '<td>' + elements.cost_change_start + '</td>' +
        '<td>' + elements.selected_by_percent + '</td>' +
        '<td>' + elements.transfers_in + '</td>' +
        '<td>' + elements.transfers_out + '</td>' +
        '<td>' + elements.total_points + '</td>' +
        '<td>' + elements.points_per_game + '</td>' +
        '<td>' + elements.minutes + '</td>' +
        '<td>' + elements.goals_scored + '</td>' +
        '<td>' + elements.assists + '</td>';

    table.appendChild(tr);
    });
}
//append_json(data);
console.log(data);
}
</code>```

Search for players function

```<code>function searchPlayers() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("player_info");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
</code>```

Does anybody know why this is not working?

答:
Edit:

Using a locally downloaded copy of the data, I think your error is this line:

```<code>td = tr[i].getElementsByTagName("td")[0];
</code>```

Which is targetting the PlayerId column, not the PlayerName column which should be this:

```<code>td = tr[i].getElementsByTagName("td")[1];
</code>```

Seems like it works now, but your filter will need a bit of improvement to account for non-english characters like the Umlaut in Agüero.  Have fun, the Fantasy API is a great way to learn a bunch of stuff for Front-End development.

Edit 2:

I changed your loop to this:

```<code>for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      txtValue = td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "table-row";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
</code>```

I added a display type to the shown version to make sure they got updated, and also removed the || conditional from your txtValue var:

```<code>txtValue = td.innerText;
</code>```

Original answer below:

Been a few seasons since I've played with the api obviously.  There isn't necessarily an issue with your javascript (though your HTML table is missing thead and tbody elements), as I'm getting a CORS error:

```<code>CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
</code>```

I don't have time to figure out the workaround you'll need to implement here, but this answer from a similar problem might help you get started:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

You might be best off doing what my old app did, as this error is related to trying to get the data via an AJAX request from a remote resource that has the CORS No-Access thing is set by the website owners.

You can attempt to work around it with the above methods, but a better solution would be to use something like PHP or .NET (Or any other back-end language that supports CURL or some sort of HTTPGet) to download the json locally, then use AJAX to access the local .json files.  Added bonus of faster response times too.  I would have it cycle through the 600 or so player json files & download them to disk every hour on a timer.

Body:
I am trying to implement a search feature which enables the user to search through this table which is being populated from a JSON from a public api.

My table:

<input type="text" id="myInput" onkeyup="searchPlayers()" placeholder="Search for player">

ID
Full Name
Team
Position
Current Price
Value Season
Cost Change from Start
Percentage selected by
Transfers In
Transfers Out
Total Points
Points Per Game
Minutes
Goals Scored
Assists

Populating the table from the JSON. Iterating through the JSON file and create a new table cell for each of the keys.

request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response);

if (request.status >= 200 && request.status < 400) {

    var table = document.getElementById('player_info');

    data.elements.forEach(elements => {

    var tr = document.createElement('tr');
    tr.innerHTML = '' + elements.id + '	' +
        '' + elements.first_name + '
' + '
' + elements.second_name + '	' +
        '' + elements.team_code + '	' +
        '' + elements.element_type + '	' +
        '' + elements.now_cost + '	' +
        '' + elements.value_season+ '	' +
        '' + elements.cost_change_start + '	' +
        '' + elements.selected_by_percent + '	' +
        '' + elements.transfers_in + '	' +
        '' + elements.transfers_out + '	' +
        '' + elements.total_points + '	' +
        '' + elements.points_per_game + '	' +
        '' + elements.minutes + '	' +
        '' + elements.goals_scored + '	' +
        '' + elements.assists + '	';

    table.appendChild(tr);
    });
}
//append_json(data);
console.log(data);
}

Search for players function

function searchPlayers() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("player_info");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

Does anybody know why this is not working?

Body:
Edit:

Using a locally downloaded copy of the data, I think your error is this line:

td = tr[i].getElementsByTagName("td")[0];

Which is targetting the PlayerId column, not the PlayerName column which should be this:

td = tr[i].getElementsByTagName("td")[1];

Seems like it works now, but your filter will need a bit of improvement to account for non-english characters like the Umlaut in Agüero.  Have fun, the Fantasy API is a great way to learn a bunch of stuff for Front-End development.

Edit 2:

I changed your loop to this:

for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      txtValue = td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "table-row";
      } else {
        tr[i].style.display = "none";
      }
    }
  }

I added a display type to the shown version to make sure they got updated, and also removed the || conditional from your txtValue var:

txtValue = td.innerText;

Original answer below:

Been a few seasons since I've played with the api obviously.  There isn't necessarily an issue with your javascript (though your HTML table is missing thead and tbody elements), as I'm getting a CORS error:

CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I don't have time to figure out the workaround you'll need to implement here, but this answer from a similar problem might help you get started:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

You might be best off doing what my old app did, as this error is related to trying to get the data via an AJAX request from a remote resource that has the CORS No-Access thing is set by the website owners.

You can attempt to work around it with the above methods, but a better solution would be to use something like PHP or .NET (Or any other back-end language that supports CURL or some sort of HTTPGet) to download the json locally, then use AJAX to access the local .json files.  Added bonus of faster response times too.  I would have it cycle through the 600 or so player json files & download them to disk every hour on a timer.


问:
Reading dxf file special characters
When I'm reading a TXT file with "special" characters it works perfectly fine. But when I read a DXF file, it translates it to the wrong characters (see image below).

is the iso-8859-1 not the correct encoding for DXF files?

答:
According to this documentation, DXF files have been written using UTF-8 since DXF R2007. This makes them much more portable than depending on a specific code page.

That's also the default for File.ReadAllLines, so you can just use File.ReadAllLines(FileName).

Title: Reading dxf file special characters


问:
Telegram API code is no longer sending messages
Telegram API/BOT code is no longer sending messages and getting the following error

```<code>The request was aborted: Could not create SSL/TLS secure channel.
</code>```

I also tried the following option

```<code>ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
</code>```

API/BOT is working locally as expected but when I hosted the application in live server (Bigrock shared hosting) am getting this issue. Tried in both secure & non-secure environments

答:
I got the same problem. "Working in dev but not in live"

Found this: https://clickalgo.com/telegram-secure-channel

Worked for me, you probably just need to run it before you create the bot.

Example from site:

Body:
Telegram API/BOT code is no longer sending messages and getting the following error

The request was aborted: Could not create SSL/TLS secure channel.

I also tried the following option

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

API/BOT is working locally as expected but when I hosted the application in live server (Bigrock shared hosting) am getting this issue. Tried in both secure & non-secure environments


问:
How to exclude some data on a SQL query depending on it's different values?
I have the following 2 tables:

```<code>create table Director (

    id_director int,
    name varchar(255),
    primary key (id_director)
);

create table Movies (

    id_movie int,
    id_director int,
    title varchar(255),
    year int,
    primary key (id_movie),
    foreign key (id_director) references Director (id_director)
);
</code>```

Some data has been already inserted on this tables. Imagine the data is:

Table Director

```<code>id_director       name
-------------------------
   1               Charles
   2               Jack
   3               Katia
   4               David
</code>```

Table Movies

```<code>id_movie      id_director     title        year
------------------------------------------------
   1              2            title1      1999
   2              1            title2      2011
   3              1            title3      2019
   4              3            title4      2019
   5              4            title5      1968
   6              3            title6      2020
   7              2            title7      1977
   8              4            title8      2004
   9              1            title9      2020
</code>```

I want to execute a SELECT clause in order to filter the directors that it's first movie its from 2019. Note from the example that only the director with the id_director = 3 meets the requirement as has made 2 films, one on 2019 and the other one on 2020.

How can I do this?

The output I would like to get is:

```<code>id_director          name
------------------------------
    3                Katia
</code>```

I have tried this, but it's obviously wrong because some directors that made films before 2019, have also made films after 2019.

```<code>select director.id_director, director.name from director, movies
where director.id_director = movie.id_director and year = 2019
group by (name);
</code>```

I'm using MySQL and I'm supposing I can do this with an IN / NOT IN subquery (but how)?

答:
If I understand right you want to look at the min(year) for that director. So the SQL would be something like:</p>

```<code>select * from movies m
inner join directors d on m.id_director = d.id_director
where min(m.year) = 2019
group by d.id_director;
</code>```

Body:
I have the following 2 tables:

create table Director (

    id_director int,
    name varchar(255),
    primary key (id_director)
);

create table Movies (

    id_movie int,
    id_director int,
    title varchar(255),
    year int,
    primary key (id_movie),
    foreign key (id_director) references Director (id_director)
);

Some data has been already inserted on this tables. Imagine the data is:

Table Director

id_director       name
-------------------------
   1               Charles
   2               Jack
   3               Katia
   4               David

Table Movies

id_movie      id_director     title        year
------------------------------------------------
   1              2            title1      1999
   2              1            title2      2011
   3              1            title3      2019
   4              3            title4      2019
   5              4            title5      1968
   6              3            title6      2020
   7              2            title7      1977
   8              4            title8      2004
   9              1            title9      2020

I want to execute a SELECT clause in order to filter the directors that it's first movie its from 2019. Note from the example that only the director with the id_director = 3 meets the requirement as has made 2 films, one on 2019 and the other one on 2020.

How can I do this?

The output I would like to get is:

id_director          name
------------------------------
    3                Katia

I have tried this, but it's obviously wrong because some directors that made films before 2019, have also made films after 2019.

select director.id_director, director.name from director, movies
where director.id_director = movie.id_director and year = 2019
group by (name);

I'm using MySQL and I'm supposing I can do this with an IN / NOT IN subquery (but how)?

Body:
If I understand right you want to look at the min(year) for that director. So the SQL would be something like:

select * from movies m
inner join directors d on m.id_director = d.id_director
where min(m.year) = 2019
group by d.id_director;


问:
How do resolve macro from preview mode inside Kentico CMS
I need to show a setting key from a Text Editable widget, it works fine in preview mode. But inside CMS it just show macro code.

Is there any way to run macro in preview mode both in CMS and live site?

答: The macro code will only display in Edit mode otherwise you'd have no way to editing or knowing there is a macro there.  Once the system is running in preview or live site mode, it will render without issue (assuming you have a valid macro).</p>