问:
Heroku socket.io server runs locally, but not anywhere else
Basically my socket.io server is only working for.. one computer only, I suppose. It works if I use Chrome, Chrome incognito, Edge. I tried using the app with my phone, while on the same Wifi, and that's where I encountered problems. It looked like socket.io just wouldn't work then. I feel like it's only working for one client (maybe ip, port issues?)

I use socket.io in pair with React js, and oh boy it was pain in the arse to make them work both locally and on Heroku.

Here's my server file /src/server/index.js

```<code>const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001; // Only this port works for some reason
const index = require("./routes/index");
const app = express();
const path = require('path');
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!

io = socketIo.listen(app);

io.configure(function () {
  io.set("transports", ["xhr-polling"]);
  io.set("polling duration", 10);  // Recommended from online guys
});

app.use(express.static(path.join(__dirname, '../../index')));
app.get('/', (req, res, next) =>
  res.sendFile(index))

io.on("connection", socket => {
  console.log("New client connected");
})

server.listen(port, () => console.log(`Listening on port ${port}`));
</code>```

I use config file to dynamically change the server and I import it every time I need to connect to my socket via socket.io-client

```<code>let server = 'ws://XXXXXXXXXXXXX.herokuapp.com/socket.io/?EIO=4&transport=websocket';

const env = process.env.NODE_ENV;

if (env === 'development') {
    server = 'http://127.0.0.1:4001';
}

module.exports = server;
</code>```

What could be the problem? Why is only working on my root computer? Could be a dyno problem or something else?
I'm a complete beginner with both heroku and socket.io, so any information would be helpful.

**EDIT:

I am not sure, but I feel like a server running in my VS Code made it work in my heroku app. I have turned it off and the server just keeps sending net::ERR_CONNECTION_REFUSED error.

答:
Solution:

Using mars/heroku-cra-node buildpack is a must. It seperates react-ui and server code. Port config: const port = process.env.PORT || 4001,
Client listens for: let server = window.location.hostname
Also good to have a seperate config file for clientside that has the following:

```<code>const env = process.env.NODE_ENV;
if (env === 'development') {
    server = 'http://localhost:4001';
}
module.exports = server;
</code>```

Then you won't have to change ports and servers in development (VSCode) or production (Heroku).

Body:
Basically my socket.io server is only working for.. one computer only, I suppose. It works if I use Chrome, Chrome incognito, Edge. I tried using the app with my phone, while on the same Wifi, and that's where I encountered problems. It looked like socket.io just wouldn't work then. I feel like it's only working for one client (maybe ip, port issues?)

I use socket.io in pair with React js, and oh boy it was pain in the arse to make them work both locally and on Heroku.

Here's my server file /src/server/index.js

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001; // Only this port works for some reason
const index = require("./routes/index");
const app = express();
const path = require('path');
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!

io = socketIo.listen(app);

io.configure(function () {
  io.set("transports", ["xhr-polling"]);
  io.set("polling duration", 10);  // Recommended from online guys
});

app.use(express.static(path.join(__dirname, '../../index')));
app.get('/', (req, res, next) =>
  res.sendFile(index))

io.on("connection", socket => {
  console.log("New client connected");
})

server.listen(port, () => console.log(`Listening on port ${port}`));

I use config file to dynamically change the server and I import it every time I need to connect to my socket via socket.io-client

let server = 'ws://XXXXXXXXXXXXX.herokuapp.com/socket.io/?EIO=4&transport=websocket';

const env = process.env.NODE_ENV;

if (env === 'development') {
    server = 'http://127.0.0.1:4001';
}

module.exports = server;

What could be the problem? Why is only working on my root computer? Could be a dyno problem or something else?
I'm a complete beginner with both heroku and socket.io, so any information would be helpful.

**EDIT:

I am not sure, but I feel like a server running in my VS Code made it work in my heroku app. I have turned it off and the server just keeps sending net::ERR_CONNECTION_REFUSED error.

Body:
Solution:

Using mars/heroku-cra-node buildpack is a must. It seperates react-ui and server code. Port config: const port = process.env.PORT || 4001,
Client listens for: let server = window.location.hostname
Also good to have a seperate config file for clientside that has the following:

const env = process.env.NODE_ENV;
if (env === 'development') {
    server = 'http://localhost:4001';
}
module.exports = server;

Then you won't have to change ports and servers in development (VSCode) or production (Heroku).


来源: stackexchange

问:
How can I make Python3.6, Red Hat Software Collection, persist after a reboot/logout/login?
I am trying to enable rh-python36 software collection after reboot So I can avoid calling "scl enable" all the time.

After unzipping and installing the package:

yum install -y tmp/rpms/*

I created a new file "python36.sh" under /etc/profile.d with the following script:

```<code>#!/bin/bash
source /opt/rh/rh-python36/enable
export X_SCLS="`scl enable rh-python36 'echo $X_SCLS'`"
</code>```

After restarting or rebooting the instance, I am getting : No such file or directoryenable

I am using CentOS release 6.10 (Final)

答:
If you have the root privilege, then add the line of code below to the .bash_profile  file found in your root directory:</p>

```<code>source /opt/rh/rh-python36/enable
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to enable rh-python36 software collection after reboot So I can avoid calling "scl enable" all the time.

After unzipping and installing the package:

yum install -y tmp/rpms/*

I created a new file "python36.sh" under /etc/profile.d with the following script:

#!/bin/bash
source /opt/rh/rh-python36/enable
export X_SCLS="`scl enable rh-python36 'echo $X_SCLS'`"

After restarting or rebooting the instance, I am getting : No such file or directoryenable

I am using CentOS release 6.10 (Final)

Body:
If you have the root privilege, then add the line of code below to the .bash_profile  file found in your root directory:

source /opt/rh/rh-python36/enable


问:
Error creating MongoTransactionManager bean in spring-data-mongoDB
I am trying to add transactional support in MongoDB with spring-data-MongoDB. But I am unable to create a bean of MongoTransactionManager which is necessary to add transactional support.

My code -

```<code>@Configuration
public class MongoTransactionsConfig extends AbstractMongoConfiguration{
    @Bean
    MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }

    @Override
    @Bean
    public MongoClient mongoClient() {
        return new MongoClient("localhost", 27017);
    }

    @Override
    protected String getDatabaseName() {
        return "backend";
    }

}
</code>```

I am following https://spring.io/blog/2018/06/28/hands-on-mongodb-4-0-transactions-with-spring-data

This is the error I receive-

```<code>java.lang.IllegalStateException: Failed to introspect Class [com.observeai.platform.integration.backend.da.config.MongoTransactionsConfig] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:659) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:556) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:541) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:599) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:726) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:667) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:635) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1489) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:420) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:390) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:511) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1198) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.SpringApplication.getExitCodeFromMappedException(SpringApplication.java:889) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.getExitCodeFromException(SpringApplication.java:875) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.handleExitCode(SpringApplication.java:861) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:810) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.observeai.platform.integration.backend.web.App.main(App.java:18) [classes/:na]
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/mongodb/MongoTransactionManager
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_141]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_141]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_141]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:641) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 20 common frames omitted

Caused by: java.lang.ClassNotFoundException: org.springframework.data.mongodb.MongoTransactionManager
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_141]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_141]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_141]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_141]
... 24 common frames omitted
</code>```

Versions I am using -

MongoDB - 4.0.0

Spring Data MongoDB - 2.1.0.RC1

MongoDB Driver - 3.8.0

答:
Successfull supported versions. Use Spring boot version 2.1.5.RELEASE
Please download latest MongoDB Java driver from MongoDB Java Driver or use below maven dependency

```<code><dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.10.2</version>
</dependency>
</code>```

Spring data MongoDB

```<code><dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-mongodb-parent</artifactId>
   <version>2.1.8.RELEASE</version>
   <type>pom</type>
</dependency>
</code>```

MongoDB: 4.0.9

Body:
I am trying to add transactional support in MongoDB with spring-data-MongoDB. But I am unable to create a bean of MongoTransactionManager which is necessary to add transactional support.

My code -

@Configuration
public class MongoTransactionsConfig extends AbstractMongoConfiguration{
    @Bean
    MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }

    @Override
    @Bean
    public MongoClient mongoClient() {
        return new MongoClient("localhost", 27017);
    }

    @Override
    protected String getDatabaseName() {
        return "backend";
    }

}

I am following https://spring.io/blog/2018/06/28/hands-on-mongodb-4-0-transactions-with-spring-data

This is the error I receive-

java.lang.IllegalStateException: Failed to introspect Class [com.observeai.platform.integration.backend.da.config.MongoTransactionsConfig] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:659) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:556) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:541) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:599) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:726) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:667) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:635) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1489) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:420) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:390) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:511) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1198) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.SpringApplication.getExitCodeFromMappedException(SpringApplication.java:889) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.getExitCodeFromException(SpringApplication.java:875) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.handleExitCode(SpringApplication.java:861) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:810) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.observeai.platform.integration.backend.web.App.main(App.java:18) [classes/:na]
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/mongodb/MongoTransactionManager
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_141]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_141]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_141]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:641) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 20 common frames omitted

Caused by: java.lang.ClassNotFoundException: org.springframework.data.mongodb.MongoTransactionManager
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_141]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_141]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_141]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_141]
... 24 common frames omitted

Versions I am using -

MongoDB - 4.0.0

Spring Data MongoDB - 2.1.0.RC1

MongoDB Driver - 3.8.0

Body:
Successfull supported versions. Use Spring boot version 2.1.5.RELEASE
Please download latest MongoDB Java driver from MongoDB Java Driver or use below maven dependency

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.10.2</version>
</dependency>

Spring data MongoDB

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-mongodb-parent</artifactId>
   <version>2.1.8.RELEASE</version>
   <type>pom</type>
</dependency>

MongoDB: 4.0.9


问:
Can't resolve symbol android.support.v4.util.Pools in react-native-gesture-handler
I am working on react-native project.

After I update my modules by running 'npm install',

I cannot find class 'Pools' which located in 'android.support.v4.util' in 'react-native-gesture-handler'.

Why Is this error occur?

How can I fix this?

1.error (In case run "react-native run-android")
-cmd

```<code>Task :react-native-gesture-handler:compileDebugJavaWithJavac FAILED
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
                              ^
  symbol:   class Pools
  location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:19: error: package Pools does not exist
  private static final Pools.SynchronizedPool<RNGestureHandlerEvent> EVENTS_POOL =
                            ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
                              ^
  symbol:   class Pools
  location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:18: error: package Pools does not exist
  private static final Pools.SynchronizedPool<RNGestureHandlerStateChangeEvent> EVENTS_POOL =
                            ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:20: error: package Pools does not exist
          new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
                   ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:19: error: package Pools does not exist
          new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
                   ^
Note:D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerButtonViewManager.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors
</code>```

2.React Native Environment Info:

```<code>System:
      OS: Windows 10
      CPU: (4) x64 Intel(R) Core(TM) i5-7500 CPU @ 3.40GHz
      Memory: 7.59 GB / 15.96 GB
    Binaries:
      Yarn: 1.15.2 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
      npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD
    IDEs:
      Android Studio: Version  3.4.0.0 AI-183.5429.30.34.5452501
</code>```

3.package.json

```<code>{
 "name": "project_y",
 "version": "0.0.1",
 "private": true,
 "scripts": {
 "start": "react-native run-android",
 "gradle-clean": "cd android & gradlew clean",
 "start-root": "react-native run-android --root",
 "test": "jest",
 "bundle": "react-native bundle --platform android --dev false --entry-file
 index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/",
 "build": "cd android & gradlew assembleDebug"
 },
 "dependencies": {
  "axios": "^0.18.0",
  "moment": "^2.24.0",
  "prop-types": "^15.7.2",
  "react": "16.6.3",
  "react-native": "0.58.5",
  "react-native-android-open-settings": "^1.3.0",
  "react-native-custom-checkbox": "^1.5.2",
  "react-native-gesture-handler": "^1.0.16",
  "react-native-grid-list": "^1.0.9",
  "react-native-image-resizer": "^1.0.1",
  "react-native-kakao-logins": "^1.3.6",
  "react-native-linear-gradient": "^2.5.3",
  "react-native-picker-select": "^6.0.0",
  "react-native-shadow": "^1.2.2",
  "react-native-super-grid": "^3.0.3",
  "react-native-svg": "^9.2.4",
  "react-native-vector-icons": "^6.3.0",
  "react-native-webview": "^5.5.0",
  "react-navigation": "^3.3.2",
  "react-redux": "^6.0.1",
  "redux": "^4.0.1"
 },
 "devDependencies": {
  "babel-core": "7.0.0-bridge.0",
  "babel-jest": "24.1.0",
  "jest": "24.1.0",
  "metro-react-native-babel-preset": "0.52.0",
  "react-test-renderer": "16.6.3",
  "redux-devtools": "^3.5.0"
 },
 "jest": {
   "preset": "react-native"
 },
 "rnpm": {
  "assets": [
    "./assets/fonts/",
    "resources/fonts"
  ]
 }
}
</code>```

4.build.gradle(app/)

```<code>apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false

android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion

defaultConfig {
    applicationId "com.projecty.projecty"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 10
    versionName "1.9"
}
splits {
    abi {
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a"
    }
}
buildTypes {
    release {
        minifyEnabled enableProguardInReleaseBuilds
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
}
applicationVariants.all { variant ->
    variant.outputs.each { output ->

        def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3]
        def abi = output.getFilter(OutputFile.ABI)
        if (abi != null) {  // null for the universal-debug, universal-release variants
            output.versionCodeOverride =
                    versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
        }
    }
}
}

dependencies {
 implementation 'com.google.android.gms:play-services-base:12.0.0'
 implementation 'com.android.installreferrer:installreferrer:1.0'
 implementation 'com.igaworks.adbrix:abx-common-rm:+'

 implementation project(':react-native-webview')
 implementation project(':react-native-android-open-settings')
 implementation project(':react-native-kakao-logins')
 implementation project(':react-native-svg')
 implementation project(':react-native-linear-gradient')
 implementation project(':react-native-vector-icons')
 implementation project(':react-native-gesture-handler')

 implementation fileTree(dir: "libs", include: ["*.jar"])
 implementation "com.android.support:appcompat-
 v7:${rootProject.ext.supportLibVersion}"
 compile(name: 'IgawSSP_v2.0.6a', ext: 'aar')
 repositories {
    flatDir {
        dirs 'libs'
    }
 }
implementation "com.facebook.react:react-native:+"  // From node_modules
}

task copyDownloadableDepsToLibs(type: Copy) {
 from configurations.compile
 into 'libs'
}

subprojects {
 repositories {
    mavenCentral()
    maven { url
 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' }
 }
}
</code>```

5.build.gradle(android/)

```<code>buildscript {
    ext {
        buildToolsVersion = "28.0.2"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        flatDir {
            dirs 'libs'
        }
        maven {
            url 'https://dl.bintray.com/igaworks/AdbrixRmSDK'
        }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        mavenCentral()
        maven {
            url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/'
        }

    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '4.7'
    distributionUrl = distributionUrl.replace("bin", "all")
}
</code>```

I expect the complete of build project.

答:
Open project use AndroidStudio3.3+

Click module android[react-native-gesture-handler]

Click top Refactor -> Migrate to AndroidX

Done

Body:
I am working on react-native project.

After I update my modules by running 'npm install',

I cannot find class 'Pools' which located in 'android.support.v4.util' in 'react-native-gesture-handler'.

Why Is this error occur?

How can I fix this?

1.error (In case run "react-native run-android")
-cmd

Task :react-native-gesture-handler:compileDebugJavaWithJavac FAILED
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
                              ^
  symbol:   class Pools
  location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:19: error: package Pools does not exist
  private static final Pools.SynchronizedPool<RNGestureHandlerEvent> EVENTS_POOL =
                            ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
                              ^
  symbol:   class Pools
  location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:18: error: package Pools does not exist
  private static final Pools.SynchronizedPool<RNGestureHandlerStateChangeEvent> EVENTS_POOL =
                            ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:20: error: package Pools does not exist
          new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
                   ^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:19: error: package Pools does not exist
          new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
                   ^
Note:D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerButtonViewManager.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors

2.React Native Environment Info:

System:
      OS: Windows 10
      CPU: (4) x64 Intel(R) Core(TM) i5-7500 CPU @ 3.40GHz
      Memory: 7.59 GB / 15.96 GB
    Binaries:
      Yarn: 1.15.2 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
      npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD
    IDEs:
      Android Studio: Version  3.4.0.0 AI-183.5429.30.34.5452501

3.package.json

{
 "name": "project_y",
 "version": "0.0.1",
 "private": true,
 "scripts": {
 "start": "react-native run-android",
 "gradle-clean": "cd android & gradlew clean",
 "start-root": "react-native run-android --root",
 "test": "jest",
 "bundle": "react-native bundle --platform android --dev false --entry-file
 index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/",
 "build": "cd android & gradlew assembleDebug"
 },
 "dependencies": {
  "axios": "^0.18.0",
  "moment": "^2.24.0",
  "prop-types": "^15.7.2",
  "react": "16.6.3",
  "react-native": "0.58.5",
  "react-native-android-open-settings": "^1.3.0",
  "react-native-custom-checkbox": "^1.5.2",
  "react-native-gesture-handler": "^1.0.16",
  "react-native-grid-list": "^1.0.9",
  "react-native-image-resizer": "^1.0.1",
  "react-native-kakao-logins": "^1.3.6",
  "react-native-linear-gradient": "^2.5.3",
  "react-native-picker-select": "^6.0.0",
  "react-native-shadow": "^1.2.2",
  "react-native-super-grid": "^3.0.3",
  "react-native-svg": "^9.2.4",
  "react-native-vector-icons": "^6.3.0",
  "react-native-webview": "^5.5.0",
  "react-navigation": "^3.3.2",
  "react-redux": "^6.0.1",
  "redux": "^4.0.1"
 },
 "devDependencies": {
  "babel-core": "7.0.0-bridge.0",
  "babel-jest": "24.1.0",
  "jest": "24.1.0",
  "metro-react-native-babel-preset": "0.52.0",
  "react-test-renderer": "16.6.3",
  "redux-devtools": "^3.5.0"
 },
 "jest": {
   "preset": "react-native"
 },
 "rnpm": {
  "assets": [
    "./assets/fonts/",
    "resources/fonts"
  ]
 }
}

4.build.gradle(app/)

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false

android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion

defaultConfig {
    applicationId "com.projecty.projecty"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 10
    versionName "1.9"
}
splits {
    abi {
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a"
    }
}
buildTypes {
    release {
        minifyEnabled enableProguardInReleaseBuilds
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
}
applicationVariants.all { variant ->
    variant.outputs.each { output ->

        def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3]
        def abi = output.getFilter(OutputFile.ABI)
        if (abi != null) {  // null for the universal-debug, universal-release variants
            output.versionCodeOverride =
                    versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
        }
    }
}
}

dependencies {
 implementation 'com.google.android.gms:play-services-base:12.0.0'
 implementation 'com.android.installreferrer:installreferrer:1.0'
 implementation 'com.igaworks.adbrix:abx-common-rm:+'

 implementation project(':react-native-webview')
 implementation project(':react-native-android-open-settings')
 implementation project(':react-native-kakao-logins')
 implementation project(':react-native-svg')
 implementation project(':react-native-linear-gradient')
 implementation project(':react-native-vector-icons')
 implementation project(':react-native-gesture-handler')

 implementation fileTree(dir: "libs", include: ["*.jar"])
 implementation "com.android.support:appcompat-
 v7:${rootProject.ext.supportLibVersion}"
 compile(name: 'IgawSSP_v2.0.6a', ext: 'aar')
 repositories {
    flatDir {
        dirs 'libs'
    }
 }
implementation "com.facebook.react:react-native:+"  // From node_modules
}

task copyDownloadableDepsToLibs(type: Copy) {
 from configurations.compile
 into 'libs'
}

subprojects {
 repositories {
    mavenCentral()
    maven { url
 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' }
 }
}

5.build.gradle(android/)

buildscript {
    ext {
        buildToolsVersion = "28.0.2"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        flatDir {
            dirs 'libs'
        }
        maven {
            url 'https://dl.bintray.com/igaworks/AdbrixRmSDK'
        }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        mavenCentral()
        maven {
            url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/'
        }

    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '4.7'
    distributionUrl = distributionUrl.replace("bin", "all")
}

I expect the complete of build project.


问:
pixel-precise positioning of line mesh on top of image data with matplotlib
I am trying to precisely overlay a mesh of 1-pixel wide lines on top of an image grid as displayed by the python library matplotlib.

Unfortunately, I seem to be unable to have enough fine control over the result to achieve proper alignment of the line mesh with the data grid, as the code below shows. The results seems to always be close but not quite exactly right.

I have tried using both the imshow and pcolormesh functions, and encountered problems with both approaches.

imshow approach:

import matplotlib.pyplot as plt
import numpy as np

size = 60
border = 5

#create test data for image and ticks location
im = np.zeros(shape=(size,size),dtype=np.float32)
ticks = np.arange(size)+0.5

#create test checkerboard pattern outside of border area
for index in range(size-2*border):
    im[border+index,border:-border] += index % 2
for index in range(size-2*border):
    im[border:-border,index+border] -= index % 2
im = np.abs(im)

#display image with imshow
plt.imshow(im, interpolation='nearest', cmap='binary', vmin=0, vmax=1)
ax = plt.gca()
ax.set_xticks(ticks)
ax.set_xticklabels([])
ax.set_yticks(ticks)
ax.set_yticklabels([])
ax.grid(color='r', linestyle='-', linewidth=1)
#sometimes line is off by 1 pixel
plt.show()
```

<p>I would expect the line mesh of red lines to overlay precisely the checkerboard pattern of the data grid, but they are off by one pixel.</p>

<p>This zoomed image show the results and the offset is easily visible:</p>

<p><img src="https://i.stack.imgur.com/vKy5p.png" alt="red_mesh_offset_by_one_pixel"></p>

<p>I also tried using pcolormesh and edgecolor (using same data as above):</p>

<pre class="lang-py prettyprint-override"><code>plt.pcolormesh(im, cmap='binary', vmin=0, vmax=1, edgecolors='r', linewidth=0.005)
plt.show()
</code>```

Here the red line mesh aligns better, but the line width is not consistent, sometimes is 1-pixel wide, sometimes 2-pixel wide, as shown in this image:

Here, ideally, I would like to always get a 1-pixel wide line.
It is possible to play around with the linewidth parameter, but if I make it too small, then the lines start to have 0-pixel width and they disappear altogether, and also I am not quite understanding what is the unit of linewidth.

In conclusion, I would appreciate any suggestions on how to achieve consistency in both positioning (red line mesh without offset from black and white checkerboard) and line width (always exactly 1-pixel wide on screen).

答:
Oh well, I guess I'll answer my own question. This is based on trial and error, so I am not sure if it is universally valid, but I hope the information may be useful for someone.

I was able to consistently plot the pcolormesh grid with width of exactly 1 pixels using the code below, where my_dpi needs to be set exactly to the dpi resolution of the display screen
and imsize_pixel_x and imsize_pixel_y are the desired size of the plot window.

my_dpi = 96.0
imsize_pixel_x = 800
imsize_pixel_y = 600

plt.figure(figsize=(imsize_pixel_x/my_dpi, imsize_pixel_y/my_dpi), dpi=my_dpi)
plt.pcolormesh(im, cmap='binary', vmin=0, vmax=1, edgecolors='r', linewidth=my_dpi/(1024*32))

plt.show()
```

Body:
I am trying to precisely overlay a mesh of 1-pixel wide lines on top of an image grid as displayed by the python library matplotlib.

Unfortunately, I seem to be unable to have enough fine control over the result to achieve proper alignment of the line mesh with the data grid, as the code below shows. The results seems to always be close but not quite exactly right.

I have tried using both the imshow and pcolormesh functions, and encountered problems with both approaches.

imshow approach:

import matplotlib.pyplot as plt
import numpy as np

size = 60
border = 5

#create test data for image and ticks location
im = np.zeros(shape=(size,size),dtype=np.float32)
ticks = np.arange(size)+0.5

#create test checkerboard pattern outside of border area
for index in range(size-2*border):
    im[border+index,border:-border] += index % 2
for index in range(size-2*border):
    im[border:-border,index+border] -= index % 2
im = np.abs(im)

#display image with imshow
plt.imshow(im, interpolation='nearest', cmap='binary', vmin=0, vmax=1)
ax = plt.gca()
ax.set_xticks(ticks)
ax.set_xticklabels([])
ax.set_yticks(ticks)
ax.set_yticklabels([])
ax.grid(color='r', linestyle='-', linewidth=1)
#sometimes line is off by 1 pixel
plt.show()

I would expect the line mesh of red lines to overlay precisely the checkerboard pattern of the data grid, but they are off by one pixel.

This zoomed image show the results and the offset is easily visible:

I also tried using pcolormesh and edgecolor (using same data as above):

plt.pcolormesh(im, cmap='binary', vmin=0, vmax=1, edgecolors='r', linewidth=0.005)
plt.show()

Here the red line mesh aligns better, but the line width is not consistent, sometimes is 1-pixel wide, sometimes 2-pixel wide, as shown in this image:

Here, ideally, I would like to always get a 1-pixel wide line.
It is possible to play around with the linewidth parameter, but if I make it too small, then the lines start to have 0-pixel width and they disappear altogether, and also I am not quite understanding what is the unit of linewidth.

In conclusion, I would appreciate any suggestions on how to achieve consistency in both positioning (red line mesh without offset from black and white checkerboard) and line width (always exactly 1-pixel wide on screen).


问:
OncePerRequestFilter unable to set error code different than 404
I have a Spring application (not using Spring boot) deployed to tomcat

I'm trying to return error 401 (HttpServletResponse.SC_UNAUTHORIZED) on specific URLs in given condition using OncePerRequestFilter ,

But I keep getting Not found error:

```<code>Response code: 404
</code>```

My Filter(removed conditions):

```<code>@Component
public class MyFilter extends OncePerRequestFilter {

    private static final Logger logger = Logger.getLogger(MyFilter.class);
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not autorized");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                PrintWriter out = response.getWriter();
                out.write(""); // Empty
                out.flush();
            } catch (IOException e) {
                logger.error("error filtering", e);
            }
            return; // stop chain
    }
}
</code>```

I tried using similar code to previous similar answer

I believe you can response.sendError inside do Filter method.

EDIT

If I just throw an exception instead I get a generic error code 500

```<code>Response code: 500
</code>```

EDIT 2

I'm adding filter inside onStartup method overriden WebApplicationInitializer's

```<code>FilterRegistration myFilter = servletContext.addFilter("myFilter ", MyFilter.class);
myFilter.addMappingForUrlPatterns(null, false, "/myservlet/myendpoint/*");
</code>```

EDIT 3

Also my filter in @Componenet and its package include in component scan

```<code>@ComponentScan(basePackages = { "my.parent.pacakge"})
</code>```

答:
I tried your code and it works. Different error codes were getting successfully returned. Although, I wanna point out a couple of things-

The method sendError() sends the response to the client and also clears the response buffer. So, anything you write after it into the response after that is of no use.

Calling setStatus() is of no use either. The HTTP response and HTTP response code has already been sent to the client in the above line when you called sendError().

Now, this is my hypothesis why your code is not working for you, but it is for me-

The reason that you might be getting HTTP 404 is that your API is not present. This can be due to a spelling error or maybe due to a simple ignorance like calling your API named /foo/bar like /foo/bar/ i.e. with extra trailing forward slash. I believe that your filter is getting executed successfully and you must be doing something useful there, not the sample code of sendError() that you have explained in the question.

Also, when you throw an Exception in your filter, the control does not reach to the API and API lookup does not happen. Hence, the default HTTP 500 response is sent to the client due to the unhandled exception instead of HTTP 404.

Body:
I have a Spring application (not using Spring boot) deployed to tomcat

I'm trying to return error 401 (HttpServletResponse.SC_UNAUTHORIZED) on specific URLs in given condition using OncePerRequestFilter ,

But I keep getting Not found error:

Response code: 404

My Filter(removed conditions):

@Component
public class MyFilter extends OncePerRequestFilter {

    private static final Logger logger = Logger.getLogger(MyFilter.class);
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not autorized");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                PrintWriter out = response.getWriter();
                out.write(""); // Empty
                out.flush();
            } catch (IOException e) {
                logger.error("error filtering", e);
            }
            return; // stop chain
    }
}

I tried using similar code to previous similar answer

I believe you can response.sendError inside do Filter method.

EDIT

If I just throw an exception instead I get a generic error code 500

Response code: 500

EDIT 2

I'm adding filter inside onStartup method overriden WebApplicationInitializer's

FilterRegistration myFilter = servletContext.addFilter("myFilter ", MyFilter.class);
myFilter.addMappingForUrlPatterns(null, false, "/myservlet/myendpoint/*");

EDIT 3

Also my filter in @Componenet and its package include in component scan

@ComponentScan(basePackages = { "my.parent.pacakge"})


问:
How to use external database in django?
I am new to django, I have pretty good idea of basics. I am able to  build model(Django database) and use it in templates. But now I want to connect external database to the django templates. How do I do that? I referred to the following link - Pulling data to the template from an external database with django
But I am still running into errors.

My views.py file looks like this :

    def view(request):
        conn = sqlite3.connect("data_new.db")
        try:
            cur = conn.cursor()
            cur.execute("delete from data_new where date = ''; ")
            cur.execute("select * from data_new;")
            results = cur.fetchall()
        finally:
            conn.close()
        return render("main.html",{"results": results})

```

<p>Following error is displayed when I run it on server : -  </p>

```TypeError at /

join() argument must be str or bytes, not 'dict'
```

答:
you forgot to pass request to render()

```<code>return render(request, "main.html",{"results": results})
</code>```

Title: How to use external database in django?

Body:
I am new to django, I have pretty good idea of basics. I am able to  build model(Django database) and use it in templates. But now I want to connect external database to the django templates. How do I do that? I referred to the following link - Pulling data to the template from an external database with django
But I am still running into errors.

My views.py file looks like this :

    def view(request):
        conn = sqlite3.connect("data_new.db")
        try:
            cur = conn.cursor()
            cur.execute("delete from data_new where date = ''; ")
            cur.execute("select * from data_new;")
            results = cur.fetchall()
        finally:
            conn.close()
        return render("main.html",{"results": results})

Following error is displayed when I run it on server : -

TypeError at /

join() argument must be str or bytes, not 'dict'

Body:
you forgot to pass request to render()

return render(request, "main.html",{"results": results})


问:
Cannot prevent a file from direct URL Access in wordpress
I'm trying to block my direct pdf url but unfortunately my pdfs are accessible directly from the url. I have already edit my htaccess file in which is stored in /opt/bitnami/apps/wordpress/htdocs

And my pfds are stored in /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs

I have gone through these urls:

Wordpress protect file if not logged in

https://wordpress.stackexchange.com/questions/37144/how-to-protect-uploads-if-user-is-not-logged-in

```<code>RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteRule ^(.*)$ /wp-content/download.php?file=$1 [L]

require_once('/path/to/wp-config.php');
require_once('/path/to/wp-includes/wp-db.php');
require_once('/path/to/wp-includes/pluggable.php');

if (!is_user_logged_in()) {
    // redirect to login page or show the message + login form
    die; // or exit, wp_redirect etc
}

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp); ```

All pdfs urls are public accessible
https://abc/wp-content/uploads/securepdfs/2019/05/Testing-pdf-1.pdf
```

答:
Bitnami Engineer here. One of our main goals is to configure Bitnami applications in the most secure way. For this reason, we moved the configuration in the .htaccess files to the main application configuration files and set the AllowOverride option to None by default.

The content of the .htaccess files have been moved to the /opt/bitnami/apps/wordpress/conf/htaccess.conf file. If you want to add new information, please follow these steps

Add a new entry in the /opt/bitnami/apps/wordpress/conf/htaccess.conf file specifying the path where the htaccess file is (/opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs) and pasting below the content of that file.

NOTE: CONTENT OF THE .htaccess FILE HERE is a placeholder, replace it with the content of the /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs/.htaccess file created by the plugin.

```<code>...
<Directory "/opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs">
CONTENT OF THE .htaccess FILE HERE
</Directory>
</code>```

Restart Apache to make the changes take effect:

```<code>sudo /opt/bitnami/ctlscript.sh restart
</code>```

You can find more information in our documentation: https://docs.bitnami.com/aws/apps/wordpress/administration/use-htaccess/

Body:
I'm trying to block my direct pdf url but unfortunately my pdfs are accessible directly from the url. I have already edit my htaccess file in which is stored in /opt/bitnami/apps/wordpress/htdocs

And my pfds are stored in /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs

I have gone through these urls:

Wordpress protect file if not logged in

https://wordpress.stackexchange.com/questions/37144/how-to-protect-uploads-if-user-is-not-logged-in

RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteRule ^(.*)$ /wp-content/download.php?file=$1 [L]

require_once('/path/to/wp-config.php');
require_once('/path/to/wp-includes/wp-db.php');
require_once('/path/to/wp-includes/pluggable.php');

if (!is_user_logged_in()) {
    // redirect to login page or show the message + login form
    die; // or exit, wp_redirect etc
}

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp); ```

All pdfs urls are public accessible
https://abc/wp-content/uploads/securepdfs/2019/05/Testing-pdf-1.pdf

Body:
Bitnami Engineer here. One of our main goals is to configure Bitnami applications in the most secure way. For this reason, we moved the configuration in the .htaccess files to the main application configuration files and set the AllowOverride option to None by default.

The content of the .htaccess files have been moved to the /opt/bitnami/apps/wordpress/conf/htaccess.conf file. If you want to add new information, please follow these steps

Add a new entry in the /opt/bitnami/apps/wordpress/conf/htaccess.conf file specifying the path where the htaccess file is (/opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs) and pasting below the content of that file.

NOTE: CONTENT OF THE .htaccess FILE HERE is a placeholder, replace it with the content of the /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs/.htaccess file created by the plugin.

...
<Directory "/opt/bitnami/apps/wordpress/htdocs/wp-content/uploads/securepdfs">
CONTENT OF THE .htaccess FILE HERE
</Directory>

Restart Apache to make the changes take effect:

sudo /opt/bitnami/ctlscript.sh restart

You can find more information in our documentation: https://docs.bitnami.com/aws/apps/wordpress/administration/use-htaccess/


问:
Cannot bind ngModel to p-dropdown value (Angular)
I using PrimeNg dropdown

Here is html of template

  {{ l('Portfolio') }}

```

<p>I get values for dropdown via this method</p>

<pre class="lang-js prettyprint-override"><code>getLandlordPortfoliosById(landlordId: number): void {
  this.landlordPortfolios = [];

  this._landlordPortfolios.getPortfolioDropdownValuesById(landlordId).subscribe(result => {
    result.items.forEach(value => {
      this.landlordPortfolios.push({
        label: value.name,
        value: value.id,
      });
    });
  });
}
</code>```

And call it like this

if (this.property.landlordId) {
  this.getLandlordPortfoliosById(this.property.landlordId);

  this.initLandlordSuggestionsById(this.property.landlordId);
}
```

For example I have landlordId = 1 and selected option for dropdown must be also with id = 1.
Here is result

But I get selected item in dropdown, just blank field, and I see all options when click dropdown. Where can be my problem?

答:
So problem was in data request/get

if I set *ngIf to dropdown, like this *ngIf = "landlordPortfolios.length" and delete [disabled], all going well.

Body:
I using PrimeNg dropdown

Here is html of template

  {{ l('Portfolio') }}

I get values for dropdown via this method

getLandlordPortfoliosById(landlordId: number): void {
  this.landlordPortfolios = [];

  this._landlordPortfolios.getPortfolioDropdownValuesById(landlordId).subscribe(result => {
    result.items.forEach(value => {
      this.landlordPortfolios.push({
        label: value.name,
        value: value.id,
      });
    });
  });
}

And call it like this

if (this.property.landlordId) {
  this.getLandlordPortfoliosById(this.property.landlordId);

  this.initLandlordSuggestionsById(this.property.landlordId);
}

For example I have landlordId = 1 and selected option for dropdown must be also with id = 1.
Here is result

But I get selected item in dropdown, just blank field, and I see all options when click dropdown. Where can be my problem?


问:
Shifting from iterator to for each
I have a panel1 function that returns an iterator that works with the following program:

```<code>public static void main(String[] args) {

     Iterator<Integer> it = panel1(1,5);
     for(;it.hasNext();)
        System.out.println(it.next()); // return 1 2 3 4 5
}
</code>```

For simplicity, I want to facilitate this by using the Java foreach syntax as shown in the following example.

```<code>for(int i:panel2(1,5))
    System.out.println(i); // would return 1 2 3 4 5
</code>```

Here is the Panel class I did so far with an anonym class:

```<code>import java.util.Iterator;
import java.util.NoSuchElementException;

public class Panel{

    public static Iterator<Integer> panel1(final int begin,final int end){
        Iterator<Integer> it = new Iterator<Integer>(){

            private int nextValue = begin;
            private final int max = end;

            public boolean hasNext() {
                return nextValue <= max;
            }

            public Integer next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return Integer.valueOf(nextValue++);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }

    public static void main(String[] args) {

         Iterator<Integer> it = panel1(1,5);
         for(;it.hasNext();)
            System.out.println(it.next()); // affiche 1 2 3 4 5
    }
}
</code>```

答:
Iterators are not Iterable in Java as they are in some other languages, so you have to have panel1 return an Iterable<Integer>, not an Iterator<Integer>, and then use it directly in the enhanced for loop:

```<code>public class Panel{

    public static Iterable<Integer> panel1(final int begin,final int end){
        return new Iterable<Integer>() {
            public Iterator<Integer> iterator() {
                Iterator<Integer> it = new Iterator<Integer>(){

                    private int nextValue = begin;
                    private final int max = end;

                    public boolean hasNext() {
                        return nextValue <= max;
                    }

                    public Integer next() {
                        if (!hasNext()) {
                            throw new NoSuchElementException();
                        }
                        return Integer.valueOf(nextValue++);
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
                return it;
            }
        };
    }

    public static void main(String[] args) {

         for (int i : panel1(1,5)) {
            System.out.println(i);
         }
    }
}
</code>```

Title: Shifting from iterator to for each

Body:
I have a panel1 function that returns an iterator that works with the following program:

public static void main(String[] args) {

     Iterator<Integer> it = panel1(1,5);
     for(;it.hasNext();)
        System.out.println(it.next()); // return 1 2 3 4 5
}

For simplicity, I want to facilitate this by using the Java foreach syntax as shown in the following example.

for(int i:panel2(1,5))
    System.out.println(i); // would return 1 2 3 4 5

Here is the Panel class I did so far with an anonym class:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Panel{

    public static Iterator<Integer> panel1(final int begin,final int end){
        Iterator<Integer> it = new Iterator<Integer>(){

            private int nextValue = begin;
            private final int max = end;

            public boolean hasNext() {
                return nextValue <= max;
            }

            public Integer next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return Integer.valueOf(nextValue++);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }

    public static void main(String[] args) {

         Iterator<Integer> it = panel1(1,5);
         for(;it.hasNext();)
            System.out.println(it.next()); // affiche 1 2 3 4 5
    }
}

Body:
Iterators are not Iterable in Java as they are in some other languages, so you have to have panel1 return an Iterable<Integer>, not an Iterator<Integer>, and then use it directly in the enhanced for loop:

public class Panel{

    public static Iterable<Integer> panel1(final int begin,final int end){
        return new Iterable<Integer>() {
            public Iterator<Integer> iterator() {
                Iterator<Integer> it = new Iterator<Integer>(){

                    private int nextValue = begin;
                    private final int max = end;

                    public boolean hasNext() {
                        return nextValue <= max;
                    }

                    public Integer next() {
                        if (!hasNext()) {
                            throw new NoSuchElementException();
                        }
                        return Integer.valueOf(nextValue++);
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
                return it;
            }
        };
    }

    public static void main(String[] args) {

         for (int i : panel1(1,5)) {
            System.out.println(i);
         }
    }
}


问:
rxjs - Tap vs subscribe
In many articles I find that tap operator is a good way to perform side effects. My question is about a difference between performing side effects using subscribe and tap. Here are examples which are doing actually the same:

```<code>        this.store$
           .pipe(tap(x => {
               this.store = x;
           }));

        this.store$
           .subscribe(x => {
              this.store = x;
           });
</code>```

Is there any difference in the performance or is there any reason to use one of these approaches?

答:
In Angular context.
You may have a component say MyComponent. There is a service as well for this component MyService. This service is responsible for some complex operation in MyComponent. Now you will make the subscription in the MyComponent as

```<code>$myObs.subscribe((val) => //do something );
</code>```

But same data may be required in your service as well, so you define it in service as

```<code>$myObs.pipe(tap((val) => // do something with data in service));
</code>```

Subscription will be done in component but using tap you can assign data member variable in your service as well.

Title: rxjs - Tap vs subscribe

Body:
In many articles I find that tap operator is a good way to perform side effects. My question is about a difference between performing side effects using subscribe and tap. Here are examples which are doing actually the same:

        this.store$
           .pipe(tap(x => {
               this.store = x;
           }));

        this.store$
           .subscribe(x => {
              this.store = x;
           });

Is there any difference in the performance or is there any reason to use one of these approaches?

Body:
In Angular context.
You may have a component say MyComponent. There is a service as well for this component MyService. This service is responsible for some complex operation in MyComponent. Now you will make the subscription in the MyComponent as

$myObs.subscribe((val) => //do something );

But same data may be required in your service as well, so you define it in service as

$myObs.pipe(tap((val) => // do something with data in service));

Subscription will be done in component but using tap you can assign data member variable in your service as well.


问:
Why does multimap allow duplicate key-value pairs?
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

```<code>#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}
</code>```

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?

答:
As you know, multimap allows to have multiple keys. Since it does not place any constraints on values comparability, it is unable to check, if values haven't been doubled.

If you want to have some dictionary data structure which allows for duplicate keys, but not key-value pairs, you would have to ensure that values are comparable.

Let's say we have a game of some sort, where there is 2D world of sqaure fields, and you can put items on fields. You can have multimap<Field, Item>, which will allow you to keep two identical items on the field. Items don't have to be comparable here.

ContentLicense: CC BY-SA 3.0

Body:
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?


问:
Caused by: java.lang.NullPointerException:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'void com.andremion.counterfab.CounterFab.setCount(int)' on a
  null object reference

Code

```<code>@Override
protected void onResume() {
    super.onResume();

   fab.setCount(new Database(getBaseContext()). getCountCart());

    if (adapter!=null )
    {
        adapter.startListening();
    }
}
</code>```

答: It seems that you did not initialize the fab variable. Thus you receive a NullPointerException. As this variable seems to be global, you should at any place initialize the fab variable in your code before you call functions on it. Since you use it already in the onResume() function, you'd best initialize it in your onCreate()

Body:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'void com.andremion.counterfab.CounterFab.setCount(int)' on a
  null object reference

Code

@Override
protected void onResume() {
    super.onResume();

   fab.setCount(new Database(getBaseContext()). getCountCart());

    if (adapter!=null )
    {
        adapter.startListening();
    }
}


问:
Implement modal close on click outside
I've been trying to implement an onclick modal close in my system. I already implemented a modal onclick event using a close button but haven't done it successfully when clicking outside the modal

I already tried adding onclick listener on the div but the content is closing even clicking inside the modal window.

```<code><div
                className={"Overlay " + (this.state.hidden? "hidden": "show")}
                id={this.props.id + "-container"} onClick={() => {
                this.setState({ hidden: true })
            }}>
</code>```

here's my modal box rendering code so far

```<code> render() {
        const contentClassName = this.getContentClassName();

        if (this.props.show) {
            document.body.style.overflow = 'hidden';
        }

        const contentStyle = {
            width: this.props.width,
            height: this.props.height,
            position: "relative"
        };

        return (
            <div
                className={"Overlay " + (this.state.hidden? "hidden": "show")}
                id={this.props.id + "-container"} onClick={() => {
                this.setState({ hidden: true })
            }}>
                <div className={contentClassName}>
                    <div className={"Overlay-container"} style={contentStyle}>
                        <a id={this.props.id + '-closeButton'}
                           className="Overlay-closeBtn icon-close-zoom" onClick={() => {
                               this.setState({ hidden: true })
                        }}/>
                        {this.props.children}
                    </div>
                </div>
            </div>
        );
    }
</code>```

as expected i want the modal to be close when clicking outside the modal window. currently it's closing even after clicking the modal window.

答:
Manage to solved this by doing this one

```<code>onClickOutside(e){
        if (e.target.classList.contains('Overlay-content') || e.target.classList.contains('Overlay-container')) {
            this.setState({
                hidden: true
            })
        }
    }
</code>```

```<code><div
                className={"Overlay " + (this.state.hidden? "hidden": "show")}
                id={this.props.id + "-container"}>
                <div className={contentClassName} onClick={(e)=>{
                    this.onClickOutside(e);

                }}>
                    <div className={"Overlay-container"} style={contentStyle}>
                        <a id={this.props.id + '-closeButton'}
                           className="Overlay-closeBtn icon-close-zoom" onClick={(e) => {
                               this.onClickHide(e)
                        }}/>
                        {this.props.children}
                    </div>
                </div>
            </div>
</code>```

Thanks!

Title: Implement modal close on click outside

Body:
I've been trying to implement an onclick modal close in my system. I already implemented a modal onclick event using a close button but haven't done it successfully when clicking outside the modal

I already tried adding onclick listener on the div but the content is closing even clicking inside the modal window.

 {
                this.setState({ hidden: true })
            }}>

here's my modal box rendering code so far

 render() {
        const contentClassName = this.getContentClassName();

        if (this.props.show) {
            document.body.style.overflow = 'hidden';
        }

        const contentStyle = {
            width: this.props.width,
            height: this.props.height,
            position: "relative"
        };

        return (

 {
                this.setState({ hidden: true })
            }}>

                         {
                               this.setState({ hidden: true })
                        }}/>
                        {this.props.children}

        );
    }

as expected i want the modal to be close when clicking outside the modal window. currently it's closing even after clicking the modal window.

Body:
Manage to solved this by doing this one

onClickOutside(e){
        if (e.target.classList.contains('Overlay-content') || e.target.classList.contains('Overlay-container')) {
            this.setState({
                hidden: true
            })
        }
    }

<div
                className={"Overlay " + (this.state.hidden? "hidden": "show")}
                id={this.props.id + "-container"}>
                <div className={contentClassName} onClick={(e)=>{
                    this.onClickOutside(e);

                }}>
                    <div className={"Overlay-container"} style={contentStyle}>
                        <a id={this.props.id + '-closeButton'}
                           className="Overlay-closeBtn icon-close-zoom" onClick={(e) => {
                               this.onClickHide(e)
                        }}/>
                        {this.props.children}
                    </div>
                </div>
            </div>

Thanks!


问:
Create reversible YAML from JSON in python
While trying to create YAML from a JSON in python, using the PyYAML  library, I am able to convert the JSON into YAML. However, in the YAML I receive as a result, all the brackets of JSON are unfolded whereas I want to retain few square brackets (lists) from JSON to converted YAML. How can I request this library call to not unfold lists from JSON into YAML, but rather retain it as a list?

A snapshot of my issue follows:

```<code>import yaml
import json

original_json = {'a': {'next': ['b'], 'prev': []},
 'b': {'next': ['c'], 'prev': ['a']},
 'c': {'next': ['d', 'e'], 'prev': ['b']},
 'd': {'next': [], 'prev': ['c']},
 'e': {'next': ['f'], 'prev': ['c']},
 'f': {'next': [], 'prev': ['e']}}

obtained_yaml = yaml.dump(yaml.load(json.dumps(original_json)), default_flow_style=False)

# obtained_yaml looks like
#
# a:
#   next:
#   - b
#   prev: []
# b:
#   next:
#   - c
#   prev:
#   - a
# c:
#   next:
#   - d
#   - e
#   prev:
#   - b
# d:
#   next: []
#   prev:
#   - c
# e:
#   next:
#   - f
#   prev:
#   - c
# f:
#   next: []
#   prev:
#   - e

# expected yaml should look like
#
# a:
#   next:
#   - ["b"]
#   prev: []
# b:
#   next:
#   - ["c"]
#   prev:
#   - ["a"]
# c:
#   next:
#   - ["d"]
#   - ["e"]
#   prev:
#   - ["b"]
# d:
#   next: []
#   prev:
#   - ["c"]
# e:
#   next:
#   - ["f"]
#   prev:
#   - ["c"]
# f:
#   next: []
#   prev:
#   - ["e"]
</code>```

I tried few ways to solve this out but all that did not work in the way expected json should come out. Need suggestions on how to get it done.

答:
Yaml syntax defines a different list structure where members of a list are lines beginning at the same indentation level starting with a - (a dash and a space). If you want to keep the brackets, you will need to cast your list into a str - But then you will lose the ability to reverse the YAML into JSON.

Here's an example where you can see that even if you can get ["a"] into [["a"]] - YAML tranforms it into a double indented list:

In [4]: import yaml
   ...: import json
   ...: import collections
   ...: original_json = {'a': {'next': ['b'], 'prev': []},
   ...:  'b': {'next': ['c'], 'prev': ['a']},
   ...:  'c': {'next': ['d', 'e'], 'prev': ['b']},
   ...:  'd': {'next': [], 'prev': ['c']},
   ...:  'e': {'next': ['f'], 'prev': ['c']},
   ...:  'f': {'next': [], 'prev': ['e']}}
   ...:
   ...: mod_json = collections.defaultdict(dict)
   ...: for k, v in original_json.items():
   ...:     mod_json[k]["next"] = [v["next"]]
   ...:     mod_json[k]["prev"] = [v["prev"]]
   ...: obtained_yaml = yaml.dump(yaml.load(json.dumps(mod_json)), default_flow_style=False)
   ...:
   ...:

In [5]: obtained_yaml
Out[5]: 'a:\n  next:\n  - - b\n  prev:\n  - []\nb:\n  next:\n  - - c\n  prev:\n  - - a\nc:\n  next:\n  - - d\n    - e\n  prev:\n  - - b\nd:\n  next:\n  - []\n  prev:\n  - - c\ne:\n  next:\n  - - f\n  prev:\n  - - c\nf:\n  next:\n  - []\n  prev:\n  - - e\n'
```

Body:
While trying to create YAML from a JSON in python, using the PyYAML  library, I am able to convert the JSON into YAML. However, in the YAML I receive as a result, all the brackets of JSON are unfolded whereas I want to retain few square brackets (lists) from JSON to converted YAML. How can I request this library call to not unfold lists from JSON into YAML, but rather retain it as a list?

A snapshot of my issue follows:

import yaml
import json

original_json = {'a': {'next': ['b'], 'prev': []},
 'b': {'next': ['c'], 'prev': ['a']},
 'c': {'next': ['d', 'e'], 'prev': ['b']},
 'd': {'next': [], 'prev': ['c']},
 'e': {'next': ['f'], 'prev': ['c']},
 'f': {'next': [], 'prev': ['e']}}

obtained_yaml = yaml.dump(yaml.load(json.dumps(original_json)), default_flow_style=False)

# obtained_yaml looks like
#
# a:
#   next:
#   - b
#   prev: []
# b:
#   next:
#   - c
#   prev:
#   - a
# c:
#   next:
#   - d
#   - e
#   prev:
#   - b
# d:
#   next: []
#   prev:
#   - c
# e:
#   next:
#   - f
#   prev:
#   - c
# f:
#   next: []
#   prev:
#   - e

# expected yaml should look like
#
# a:
#   next:
#   - ["b"]
#   prev: []
# b:
#   next:
#   - ["c"]
#   prev:
#   - ["a"]
# c:
#   next:
#   - ["d"]
#   - ["e"]
#   prev:
#   - ["b"]
# d:
#   next: []
#   prev:
#   - ["c"]
# e:
#   next:
#   - ["f"]
#   prev:
#   - ["c"]
# f:
#   next: []
#   prev:
#   - ["e"]

I tried few ways to solve this out but all that did not work in the way expected json should come out. Need suggestions on how to get it done.


问:
Can't link INET library to omnet project correctly Ubuntu 18
I am on ubuntu 18, and I am trying to compile my project where I linked the INET library. It worked fine when I was on ubuntu 16. But now I got these errors on ubuntu 18:

I already added inet library to reference projects.

```<code>myApp.cc
HelloMsg_m.cc
XedMsg_m.cc
Creating executable: out/gcc-release//SaaS
../inet/src/libINET.so : undefined reference to « osg::StateSet::setRenderingHint(int) »
../inet/src/libINET.so : undefined reference to  « osgEarth::MapNode::getMapSRS() const »
../inet/src/libINET.so : undefined reference to  « osg::Group::removeChildren(unsigned int, unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::Object::getUserData() »
../inet/src/libINET.so : undefined reference to « osg::AutoTransform::setNormal(osg::Vec3f const&) »
../inet/src/libINET.so : undefined reference to  « osg::Texture::setFilter(osg::Texture::FilterParameter, osg::Texture::FilterMode) »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::Node&) »
../inet/src/libINET.so : undefined reference to  « vtable for osg::Array »
../inet/src/libINET.so : undefined reference to  « osgEarth::GeoTransform::GeoTransform() »
../inet/src/libINET.so : undefined reference to  « typeinfo for osg::Group »
../inet/src/libINET.so : undefined reference to « osg::Shader::Shader(osg::Shader::Type) »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::ProxyNode&) »
../inet/src/libINET.so : undefined reference to « osg::Node::getOrCreateStateSet() »
../inet/src/libINET.so : undefined reference to « osg::Texture2D::Texture2D() »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::OcclusionQueryNode&) »
../inet/src/libINET.so : undefined reference to « osg::StateSet::setMode(unsigned int, unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::BufferData::~BufferData() »
../inet/src/libINET.so : undefined reference to « osg::StateSet::getAttribute(osg::StateAttribute::Type, unsigned int) »
../inet/src/libINET.so : undefined reference to  « typeinfo for osg::NodeVisitor »
../inet/src/libINET.so : undefined reference to « osgText::TextBase::setDrawMode(unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::Transform::Transform(osg::Transform const&, osg::CopyOp const&) »
../inet/src/libINET.so : undefined reference to « osg::Object::Object(osg::Object const&, osg::CopyOp const&) »
../inet/src/libINET.so : undefined reference to  « vtable for osg::DrawArrays »
../inet/src/libINET.so : undefined reference to « osg::Referenced::Referenced(bool) »
../inet/src/libINET.so : undefined reference to « vtable for osg::Box »
../inet/src/libINET.so : undefined reference to « osg::StateSet::setAttribute(osg::StateAttribute*, unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::StateSet::setAttributeAndModes(osg::StateAttribute*, unsigned int) »
../inet/src/libINET.so : undefined reference to « typeinfo for osg::Geode »
../inet/src/libINET.so : undefined reference to « osg::Group::releaseGLObjects(osg::State*) const »
../inet/src/libINET.so : undefined reference to  « osg::Geode::Geode() »
../inet/src/libINET.so : undefined reference to « osg::Geometry::addPrimitiveSet(osg::PrimitiveSet*) »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::PagedLOD&) »
../inet/src/libINET.so : undefined reference to « osg::LineStipple::LineStipple() »
.
.
.

collect2: error: ld returned 1 exit status
Makefile:104: recipe for target 'out/gcc-release//SaaS' failed
make: *** [out/gcc-release//SaaS] Error 1
</code>```

Can someone help me on this, I've been trying to solve the problem for three days without success.

答:
You should use the latest version of OMNeT++ (5.4.1, soon 5.5 will be released, too) and INET 3.6.5 or INET 4.1.1.

osgEarth changed its API and older versions of INET do not compile anymore.

The other solution is to disable osg and osgEarth support in OMNeT++ (see the configure.user file) if you do not need and 3D visualization in your project.

Body:
I am on ubuntu 18, and I am trying to compile my project where I linked the INET library. It worked fine when I was on ubuntu 16. But now I got these errors on ubuntu 18:

I already added inet library to reference projects.

myApp.cc
HelloMsg_m.cc
XedMsg_m.cc
Creating executable: out/gcc-release//SaaS
../inet/src/libINET.so : undefined reference to « osg::StateSet::setRenderingHint(int) »
../inet/src/libINET.so : undefined reference to  « osgEarth::MapNode::getMapSRS() const »
../inet/src/libINET.so : undefined reference to  « osg::Group::removeChildren(unsigned int, unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::Object::getUserData() »
../inet/src/libINET.so : undefined reference to « osg::AutoTransform::setNormal(osg::Vec3f const&) »
../inet/src/libINET.so : undefined reference to  « osg::Texture::setFilter(osg::Texture::FilterParameter, osg::Texture::FilterMode) »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::Node&) »
../inet/src/libINET.so : undefined reference to  « vtable for osg::Array »
../inet/src/libINET.so : undefined reference to  « osgEarth::GeoTransform::GeoTransform() »
../inet/src/libINET.so : undefined reference to  « typeinfo for osg::Group »
../inet/src/libINET.so : undefined reference to « osg::Shader::Shader(osg::Shader::Type) »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::ProxyNode&) »
../inet/src/libINET.so : undefined reference to « osg::Node::getOrCreateStateSet() »
../inet/src/libINET.so : undefined reference to « osg::Texture2D::Texture2D() »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::OcclusionQueryNode&) »
../inet/src/libINET.so : undefined reference to « osg::StateSet::setMode(unsigned int, unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::BufferData::~BufferData() »
../inet/src/libINET.so : undefined reference to « osg::StateSet::getAttribute(osg::StateAttribute::Type, unsigned int) »
../inet/src/libINET.so : undefined reference to  « typeinfo for osg::NodeVisitor »
../inet/src/libINET.so : undefined reference to « osgText::TextBase::setDrawMode(unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::Transform::Transform(osg::Transform const&, osg::CopyOp const&) »
../inet/src/libINET.so : undefined reference to « osg::Object::Object(osg::Object const&, osg::CopyOp const&) »
../inet/src/libINET.so : undefined reference to  « vtable for osg::DrawArrays »
../inet/src/libINET.so : undefined reference to « osg::Referenced::Referenced(bool) »
../inet/src/libINET.so : undefined reference to « vtable for osg::Box »
../inet/src/libINET.so : undefined reference to « osg::StateSet::setAttribute(osg::StateAttribute*, unsigned int) »
../inet/src/libINET.so : undefined reference to « osg::StateSet::setAttributeAndModes(osg::StateAttribute*, unsigned int) »
../inet/src/libINET.so : undefined reference to « typeinfo for osg::Geode »
../inet/src/libINET.so : undefined reference to « osg::Group::releaseGLObjects(osg::State*) const »
../inet/src/libINET.so : undefined reference to  « osg::Geode::Geode() »
../inet/src/libINET.so : undefined reference to « osg::Geometry::addPrimitiveSet(osg::PrimitiveSet*) »
../inet/src/libINET.so : undefined reference to « osg::NodeVisitor::apply(osg::PagedLOD&) »
../inet/src/libINET.so : undefined reference to « osg::LineStipple::LineStipple() »
.
.
.

collect2: error: ld returned 1 exit status
Makefile:104: recipe for target 'out/gcc-release//SaaS' failed
make: *** [out/gcc-release//SaaS] Error 1

Can someone help me on this, I've been trying to solve the problem for three days without success.


问:
Connection time out access the external IP google compute engine
I'm new in GCP environment and tried to create go running on VM. External IP is 35.247.137.122.

below is the go code, giving response code:200, message: "OK"

```<code>package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    fmt.Println("ready to dig in...")
    http.HandleFunc("/", handle)

    fmt.Println(http.ListenAndServe(":8989", nil))
}

func handle(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    m, _ := json.Marshal(struct {
        Code    int
        Message string
    }{
        Code:    200,
        Message: "OK",
    })

    w.WriteHeader(http.StatusOK)
    w.Write([]byte(m))
}
</code>```

When I run the go files, I can get the response from the internal sources .

For the external test, set the firewall rules  but I still got the connection time out when access the external
Anybody willing to tell me how to resolve the issues
Thanks.

nb: I already installed nginx, so access the external IP will result in nginx home, but I tried to access my go code without Proxy Pass from nginx.

答:
What you did is exactly what's needed in order to achieve what you asked for.
I've tried reproducing exactly what you've got and I've received a 200 OK from the server on the given port on the external IP.

Probably it was a temporary problem, or maybe there is another firewall rule blocking the one you need. Try lowering the "Priority" number, in order to raise the rule's priority.

Body:
I'm new in GCP environment and tried to create go running on VM. External IP is 35.247.137.122.

below is the go code, giving response code:200, message: "OK"

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    fmt.Println("ready to dig in...")
    http.HandleFunc("/", handle)

    fmt.Println(http.ListenAndServe(":8989", nil))
}

func handle(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    m, _ := json.Marshal(struct {
        Code    int
        Message string
    }{
        Code:    200,
        Message: "OK",
    })

    w.WriteHeader(http.StatusOK)
    w.Write([]byte(m))
}

When I run the go files, I can get the response from the internal sources .

For the external test, set the firewall rules  but I still got the connection time out when access the external
Anybody willing to tell me how to resolve the issues
Thanks.

nb: I already installed nginx, so access the external IP will result in nginx home, but I tried to access my go code without Proxy Pass from nginx.


问:
import Swift vs import Foundation
Question

What is the difference between import Swift and import Foundation?

Until I read this comment by Martin R, I didn't even know that there was an import Swift.

Reading

I couldn't find the documentation and doing a Google search didn't turn up much.

What I tried

Testing it out shows that import Swift does not give any compile errors, but that doesn't really answer my question.

If I were to guess, I would say that you import Swift for Swift projects and that you import Foundation for Objective-C projects or maybe for Swift projects that use Objective-C classes (like NSString).

Testing this in the Playground:

```<code>import Foundation
import Swift

var str = "Hello, playground"
let str2: NSString = "hello"
let str3: String = "hello"
</code>```

Commenting out import Swift gives no errors and str is of String type. However, commenting out import Foundation gives an "undeclared type" error for NSString.

My question revisited

I would be happy enough to abandon Foundation and just use Swift. So am I right to just import Swift all the time unless I specifically need to use one of the old Objective-C classes?

答:
If you want to work with Strings, Dates, etc you need to import Foundation.

The Foundation framework provides a base layer of functionality for apps and frameworks, including data storage and persistence, text processing, date and time calculations, sorting and filtering, and networking.

If you want to work with UITableViewController, UIAlertController you need to import UIKit.

If you import UIKit you do not need to import Foundation because it already imports it in the backstage.

The Swift standard library defines a base layer of functionality for writing Swift programs, including:

Fundamental data types, Common data structures, Global functions such as print(:separator:terminator:) and abs(:), Protocols, such as Collection and Equatable... etc

If you import Foundation, then no need to import Swift again as Foundation contains references to Swift Standard Library by default.

When you are writing something not for iOS Apps, like say a server programming based on Vapor , you may need to consider import Swift.

Refer:-
https://developer.apple.com/documentation/swift/swift_standard_library/

Pleases refer:-
https://hasancan.tech.blog/2018/01/17/import-foundation-vs-uikit/

Title: import Swift vs import Foundation

Body:
Question

What is the difference between import Swift and import Foundation?

Until I read this comment by Martin R, I didn't even know that there was an import Swift.

Reading

I couldn't find the documentation and doing a Google search didn't turn up much.

What I tried

Testing it out shows that import Swift does not give any compile errors, but that doesn't really answer my question.

If I were to guess, I would say that you import Swift for Swift projects and that you import Foundation for Objective-C projects or maybe for Swift projects that use Objective-C classes (like NSString).

Testing this in the Playground:

import Foundation
import Swift

var str = "Hello, playground"
let str2: NSString = "hello"
let str3: String = "hello"

Commenting out import Swift gives no errors and str is of String type. However, commenting out import Foundation gives an "undeclared type" error for NSString.

My question revisited

I would be happy enough to abandon Foundation and just use Swift. So am I right to just import Swift all the time unless I specifically need to use one of the old Objective-C classes?


问:
How to get rid of extra characters in linux process ID using shell script
I m trying to kill a process by its pid, and this is the script that I found from web.

```<code>PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..
</code>```

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

```<code>**arguments must be process or job IDs**
</code>```

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!

答: From what I see, you dont want to kill a process by PID, by its name. And you do it by getting the process PID and then try to kill it via PID. If you want to kill by name, use killall processname.

Body:
I m trying to kill a process by its pid, and this is the script that I found from web.

PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

**arguments must be process or job IDs**

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!


答:
You need to pass Iterable<Integer> to the enhanced for loop, not an Iterator<Integer>.

For example:

```<code>public static void main(String[] args) {
    Iterable<Integer> iterable = () -> panel1(1,5);
    for (int i : iterable)
        System.out.println(i);
}
</code>```

Title: Shifting from iterator to for each

Body:
You need to pass Iterable<Integer> to the enhanced for loop, not an Iterator<Integer>.

For example:

public static void main(String[] args) {
    Iterable<Integer> iterable = () -> panel1(1,5);
    for (int i : iterable)
        System.out.println(i);
}


问:
How to obtain the total numbers of rows from a CSV file in Python?
I'm using python (Django Framework) to read a CSV file. I pull just 2 lines out of this CSV as you can see. What I have been trying to do is store in a variable the total number of rows the CSV also.

How can I get the total number of rows?

```<code>file = object.myfilePath
fileObject = csv.reader(file)
for i in range(2):
    data.append(fileObject.next())
</code>```

I have tried:

```<code>len(fileObject)
fileObject.length
</code>```

答:
After iterating the whole file with csv.reader() method, you have the total number of lines read, via instance variable  line_num:

```<code>import csv
with open('csv_path_file') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        pass
    print(csv_reader.line_num)
</code>```

Quoting the official documentation:

csvreader.line_num

The number of lines read from the source iterator.

Small caveat:

total number of lines, includes the header, if the CSV has.

Body:
I'm using python (Django Framework) to read a CSV file. I pull just 2 lines out of this CSV as you can see. What I have been trying to do is store in a variable the total number of rows the CSV also.

How can I get the total number of rows?

file = object.myfilePath
fileObject = csv.reader(file)
for i in range(2):
    data.append(fileObject.next())

I have tried:

len(fileObject)
fileObject.length

Body:
After iterating the whole file with csv.reader() method, you have the total number of lines read, via instance variable  line_num:

import csv
with open('csv_path_file') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        pass
    print(csv_reader.line_num)

Quoting the official documentation:

csvreader.line_num

The number of lines read from the source iterator.

Small caveat:

total number of lines, includes the header, if the CSV has.


问:
What causes "The permissions on <folder> are incorrectly ordered"?
While debugging a particularly troublesome error involving SQLite and IIS, we encountered a permissions problem when accessing the App_Data properties

The permissions on App_Data are incorrectly ordered, which may cause some entries to be ineffective.

Here's a screenshot as well:

My question isn't what incorrect ordering is, I think How do you programmatically fix a non-canonical ACL? already gives a good intro into the problem.

What I want to know is what types of ordering are incorrect? For example, if we put Full Control for Everyone, should that precede or follow some other permission? Are there any examples of incorrect ordering that trigger the error? We clicked Reorder so we no longer can reproduce the error on our machine.

答:
For us, it was the Cygwin that created files which were showing these problems
This thread explains it and possible remedies.
cygwin sets file permission to 000

Also, something I wasn't seeing in other threads, our ACL had "NULL SID" in it:
see the picture


问:
Ionic Cordova: Is there a way to set fixed cordova-ios version
Currently I am building an Ionic App.

When i clone a fresh copy of my repo and add platform ios, cordova-ios@5.0.1 is used because of following line in config.xml

```<code><engine name="ios" spec="5.0.1" />
</code>```

But when i remove platform iOS, this line also gets removed.

Therefore, on the next read cordova-ios@4.x.x gets installed. But I need at least version 5.0.1 otherwise the Google Maps plugin wont work.

Can i somehow force the use of cordova-ios@5.0.1?

Tried to find resolutions to the problems and tried various different settings in package.json and config.xml, nothing helps.

答:
My solution right now:

I added 2 items to the scripts part in package.json

```<code>"add:ios": "ionic cordova platform add ios@5",
"rm:ios": "ionic cordova platform rm ios"
</code>```

So the workaround now is to use

```<code>npm run add:ios
</code>```

instead of

```<code>ionic cordova platform add ios@5
</code>```

Body:
Currently I am building an Ionic App.

When i clone a fresh copy of my repo and add platform ios, cordova-ios@5.0.1 is used because of following line in config.xml

<engine name="ios" spec="5.0.1" />

But when i remove platform iOS, this line also gets removed.

Therefore, on the next read cordova-ios@4.x.x gets installed. But I need at least version 5.0.1 otherwise the Google Maps plugin wont work.

Can i somehow force the use of cordova-ios@5.0.1?

Tried to find resolutions to the problems and tried various different settings in package.json and config.xml, nothing helps.

Body:
My solution right now:

I added 2 items to the scripts part in package.json

"add:ios": "ionic cordova platform add ios@5",
"rm:ios": "ionic cordova platform rm ios"

So the workaround now is to use

npm run add:ios

instead of

ionic cordova platform add ios@5


问:
"hasPrefix" not working in Swift
I have an array of dictionary & I try to filter with prefix from using one of the key as follow:

```<code>let b = [["id":1,"name":"India"],["id":2,"name":"america"],["id":3,"name":"africa"],["id":4,"name":"indonesia"],["id":5,"name":"jakarta"],["id":6,"rec_name":"Zimba"]]

let g = b.filter({String(describing: $0["name"]).hasPrefix("I")})

print(g) //retun Empty array
</code>```

If I try with contains then it working fine

or

If I try with only pure String array then also  it working fine

Thank you,

答:
Try this code you'll get the proper solution.</p>

```<code>let b = [["id":1,"name":"India"],["id":2,"name":"america"],
["id":3,"name":"africa"],["id":4,"name":"indonesia"],["id":5,"name":"jakarta"],
["id":6,"rec_name":"Zimba"]]
let g = b.filter({($0["name"] as? String ?? "").hasPrefix("I")})
print(g)
</code>```

Title: "hasPrefix" not working in Swift

Body:
I have an array of dictionary & I try to filter with prefix from using one of the key as follow:

let b = [["id":1,"name":"India"],["id":2,"name":"america"],["id":3,"name":"africa"],["id":4,"name":"indonesia"],["id":5,"name":"jakarta"],["id":6,"rec_name":"Zimba"]]

let g = b.filter({String(describing: $0["name"]).hasPrefix("I")})

print(g) //retun Empty array

If I try with contains then it working fine

or

If I try with only pure String array then also  it working fine

Thank you,

Body:
Try this code you'll get the proper solution.

let b = [["id":1,"name":"India"],["id":2,"name":"america"],
["id":3,"name":"africa"],["id":4,"name":"indonesia"],["id":5,"name":"jakarta"],
["id":6,"rec_name":"Zimba"]]
let g = b.filter({($0["name"] as? String ?? "").hasPrefix("I")})
print(g)