问:
How to set specific language for all pages in Codeigniter 4
I've translated 2 language in 'app/Language' folder and set language switcher. Currently translation works fine for base url like example.com/en and example.com/sp.

My problem is when visitor visits other page like /post/cats/123 then How I set the language for all view page. What is the standard way for language setting in codeigniter 4.

Language folder -

language switcher code.

```<code><div class="dropdown-menu" aria-labelledby="navbarDropdown">
    <a class="dropdown-item" href="<?= base_url('en') ?>">English</a>
    <a class="dropdown-item" href="<?= base_url('sp') ?>">Spanish</a>
</div>
</code>```

Route-

```<code>$routes->get('/{locale}', 'Language::index');
</code>```

Language class -

```<code>class Language extends BaseController
{

    public function index()
    {
         $locale = $this->request->getLocale();
         $this->request->setLocale($locale);
         return redirect()->back();
    }
}
</code>```

答:
I got a solution for multi language in codeigniter-4  myself that I described now. My view code is here that is clickable for selection a language -

```<code><a class="dropdown-item" href="<?= base_url('lang/en'); ?>">English</a>
<a class="dropdown-item" href="<?= base_url('lang/es'); ?>">Español</a>
</code>```

then I used a route for language-

```<code>$routes->get('/lang/{locale}', 'Language::index');
</code>```

For this route I created a class Language with a method index-

```<code>class Language extends BaseController
{

    public function index()
    {   $session = session();
        $locale = $this->request->getLocale();
        $session->remove('lang');
        $session->set('lang',$locale);
        $url = base_url();
        return redirect()->to($url);
    }
}
</code>```

Here I enabled session to store selected language and removed old language from session. $locale = $this->request->getLocale(); With this request I received selected language and stored into into session $session->set('lang',$locale); and redirect it to base url.

In codeigniter-4 default BaseController in initController method, I set language $language->setLocale($session->lang); for all controllers that I extends for other.

```<code>class BaseController extends Controller{
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
      $session = \Config\Services::session();
      $language = \Config\Services::language();
      $language->setLocale($session->lang);
    }
}
</code>```

Here I enabled language Library as a service $language = \Config\Services::language(); and set language with this method $language->setLocale($session->lang); using session data.

Body:
I've translated 2 language in 'app/Language' folder and set language switcher. Currently translation works fine for base url like example.com/en and example.com/sp.

My problem is when visitor visits other page like /post/cats/123 then How I set the language for all view page. What is the standard way for language setting in codeigniter 4.

Language folder -

language switcher code.

    <a class="dropdown-item" href="<?= base_url('en') ?>">English
    <a class="dropdown-item" href="<?= base_url('sp') ?>">Spanish

Route-

$routes->get('/{locale}', 'Language::index');

Language class -

class Language extends BaseController
{

    public function index()
    {
         $locale = $this->request->getLocale();
         $this->request->setLocale($locale);
         return redirect()->back();
    }
}

Body:
I got a solution for multi language in codeigniter-4  myself that I described now. My view code is here that is clickable for selection a language -

<a class="dropdown-item" href="<?= base_url('lang/en'); ?>">English</a>
<a class="dropdown-item" href="<?= base_url('lang/es'); ?>">Español</a>

then I used a route for language-

$routes->get('/lang/{locale}', 'Language::index');

For this route I created a class Language with a method index-

class Language extends BaseController
{

    public function index()
    {   $session = session();
        $locale = $this->request->getLocale();
        $session->remove('lang');
        $session->set('lang',$locale);
        $url = base_url();
        return redirect()->to($url);
    }
}

Here I enabled session to store selected language and removed old language from session. $locale = $this->request->getLocale(); With this request I received selected language and stored into into session $session->set('lang',$locale); and redirect it to base url.

In codeigniter-4 default BaseController in initController method, I set language $language->setLocale($session->lang); for all controllers that I extends for other.

class BaseController extends Controller{
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
      $session = \Config\Services::session();
      $language = \Config\Services::language();
      $language->setLocale($session->lang);
    }
}

Here I enabled language Library as a service $language = \Config\Services::language(); and set language with this method $language->setLocale($session->lang); using session data.


来源: stackexchange

问:
Locking a table within a transaction
I would like to be able to lock an entire table to prevent any INSERTs or UPDATEs in it between the "beginTransaction" and the ending "commit" or "rollback".

I know that beginning a transaction results in an implicit UNLOCK TABLES and that a LOCK table results in a implicit COMMIT... so is there any way to do what I want?

答:
```<code>select count(*) from table
</code>```

<p>within a transaction, locks the talbe on msSQL 2000 </p>

ContentLicense: CC BY-SA 3.0

Title: Locking a table within a transaction

Body:
select count(*) from table

within a transaction, locks the talbe on msSQL 2000


问:
Permission to display pop-up windows while running in the background
I have a project that needs to display pop-up windows while running in the background permission. How to ask the user permission. I already tried the Setting.canDrawOverlay() but it doesn't work for the app that killed.

this is my app permission in setting

I only can get the green one permission but I need the red one.

Thanks.

答:
This permission has to be given manually, but after searching for some time I came up with an idea that can be used to open the correct permission screen, so the user can activate the permission.

```<code>    fun isMiUi(): Boolean {
        return getSystemProperty("ro.miui.ui.version.name")?.isNotBlank() == true
    }

    fun isMiuiWithApi28OrMore(): Boolean {
        return isMiUi() && Build.VERSION.SDK_INT >= 28
    }

    fun goToXiaomiPermissions(context: Context) {
        val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity")
        intent.putExtra("extra_pkgname", context.packageName)
        context.startActivity(intent)
    }

    private fun getSystemProperty(propName: String): String? {
        val line: String
        var input: BufferedReader? = null
        try {
            val p = Runtime.getRuntime().exec("getprop $propName")
            input = BufferedReader(InputStreamReader(p.inputStream), 1024)
            line = input.readLine()
            input.close()
        } catch (ex: IOException) {
            return null
        } finally {
            if (input != null) {
                try {
                    input.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return line
    }
</code>```

In my project I verify if isMiuiWithApi28OrMore() and if it is then I can prepare an additional step telling the user that the app needs the permission and sends him to the permission screen.

I hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
This permission has to be given manually, but after searching for some time I came up with an idea that can be used to open the correct permission screen, so the user can activate the permission.

    fun isMiUi(): Boolean {
        return getSystemProperty("ro.miui.ui.version.name")?.isNotBlank() == true
    }

    fun isMiuiWithApi28OrMore(): Boolean {
        return isMiUi() && Build.VERSION.SDK_INT >= 28
    }

    fun goToXiaomiPermissions(context: Context) {
        val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity")
        intent.putExtra("extra_pkgname", context.packageName)
        context.startActivity(intent)
    }

    private fun getSystemProperty(propName: String): String? {
        val line: String
        var input: BufferedReader? = null
        try {
            val p = Runtime.getRuntime().exec("getprop $propName")
            input = BufferedReader(InputStreamReader(p.inputStream), 1024)
            line = input.readLine()
            input.close()
        } catch (ex: IOException) {
            return null
        } finally {
            if (input != null) {
                try {
                    input.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return line
    }

In my project I verify if isMiuiWithApi28OrMore() and if it is then I can prepare an additional step telling the user that the app needs the permission and sends him to the permission screen.

I hope it helps.


问:
How can i push item on an array without change the initialised array
THis is my code

let a = ["a","b","c"]
let b = "dd"
let c = a
c.push(b)

console.log(a);
console.log(c);```

But i want that when i log "a" it returns ["a","b","c"]
And when i log "c" it returns ["a","b","c", "d"]

答:
Array/object values are copied by reference instead of by value. So, if you do let c = a the c points to the same array object as a

You can use Spread Operator (Shallow copy) to make a new copy of the array.

let a = ["a","b","c"]
let b = "dd"
let c = [...a]
c.push(b)

console.log(a);
console.log(c);```
</div>
</div>
</p>

<p>Be aware this does not safely copy multi-dimensional arrays. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let a = [["a"],["b"]]
let c = [...a]
let b = "dd"
c[0].push(b)

console.log(a);
console.log(c);
// [["a", "dd"], ["b"]]
// [["a", "dd"], ["b"]]
// They've both been changed because they share references</code>```

Body:
THis is my code

let a = ["a","b","c"]
let b = "dd"
let c = a
c.push(b)

console.log(a);
console.log(c);

But i want that when i log "a" it returns ["a","b","c"]
And when i log "c" it returns ["a","b","c", "d"]

Body:
Array/object values are copied by reference instead of by value. So, if you do let c = a the c points to the same array object as a

You can use Spread Operator (Shallow copy) to make a new copy of the array.

let a = ["a","b","c"]
let b = "dd"
let c = [...a]
c.push(b)

console.log(a);
console.log(c);

Be aware this does not safely copy multi-dimensional arrays.

let a = [["a"],["b"]]
let c = [...a]
let b = "dd"
c[0].push(b)

console.log(a);
console.log(c);
// [["a", "dd"], ["b"]]
// [["a", "dd"], ["b"]]
// They've both been changed because they share references


问:
token is not working after login when i am trying to get method with token
Que:After generating Authtoken when i am trying to use get method as a profile (which i mentioned in signin.js file) it not providing the user detail instead its showing user is not loged in.(middleware file)

Blockquote

one more question : do i have to store token in database or not? if yes,please explain in detail

controller: signin.js code

```<code>var express=require('express');
var signupuser=require('../model/singup')
var router=express.Router();
var bcrypt=require('bcryptjs');
var validator=require('validator');
var jwt=require('jsonwebtoken');
var auth=require('../middleware/auth')
router.post('/',async(req,res)=>
{
const {email,password}=req.body
const user=await signupuser.findByCredentials(email,password)
if(!user){
    return res.status(401).send({error:"Login failed ! email or pasword wrong"})
}
const authtoken=await user.generateauthToken()
res.send({user,authtoken})
});

router.get('/profile',auth,(req,res)=>{  // using this method to get profile but it is not providing token
    res.send(req.user)
})
module.exports=router;
</code>```

Blockquote

Middleware:auth.js code

```<code>var express=require('express');
var signupuser=require('../model/singup')
var jwt=require('jsonwebtoken');
var router=express.Router();
var auth= async function(req,res,next){
const token =req.header("Authorization").replace('Bearer ','')
const decode=jwt.verify(token,"mynameisbhupesh");
try{
    const user= await signupuser.findOne({id:decode._id,'authtoken.token':token})
    if(!user){
        res.json("user not loged in" )
    }
    req.user=user
    req.token=token
    next();
 }catch(err){
res.status(401).send({error:'no auth token'})
 }}

module.exports=auth
</code>```

Blockquote

model:signup.js

```<code>var mongoose=require('mongoose');
require('../db');
var bcrypt=require('bcryptjs');
var validator=require('validator');
var jwt=require('jsonwebtoken');
mongoose.Promise=require('bluebird');
var schema= new mongoose.Schema({
    name:{type:String,required:true},
    email:{type:String,required:true,unique:true,validate:value=>{
        if(!validator.isEmail(value)){
            throw new Error({error:'invalid email address'})
        }
    }},
    password:{type:String,required:true,minlength:5},
    //  authtoken:[{token:{type:String,required:true}}],
});

schema.pre('save',async function(next){
    const user=this
    if(user.isModified('password')){
        user.password=await bcrypt.hash(user.password,8)
    }
    next()
})

schema.methods.generateauthToken=async function(){
    const user=this
    const token=jwt.sign({_id:user._id},"mynameisbhupesh",{
        expiresIn:10000000000000000000000000
    })
    // user.authtoken=user.authtoken.concat({token})
   await user.save()
    return token
}
schema.statics.findByCredentials =async (email,password)=>{
    const user=await signupuser.findOne({email})
    if(!user){
        throw new Error ({error:'Invalid user'})
    }
    const ispassmatch=await bcrypt.compare(password,user.password)
    if(!ispassmatch){
        throw new Error ({error:'Invalid user'})
    }
    return user
     }

const signupuser=mongoose.model('signupuser',schema);
module.exports=signupuser;
</code>```

Blockquote

controller:signup.js

```<code>var express=require('express');
var signupuser=require('../model/singup')
var router=express.Router();
var bcrypt=require('bcryptjs');
var validator=require('validator');
var jwt=require('jsonwebtoken');
router.post('/',async (req,res)=>{
    try{
        const user=new signupuser(req.body)
        await user.save()
        const token=await user.generateauthToken()
        res.status(201).send({user,token})
    }
    catch(error){
        res.status(400).send(error)
    }
})
module.exports=router;
</code>```

Blockquote

database:db.js

```<code>var cookie=require('cookie-parser');
var Mongostor=require('connect-mongo');
var mongose=require('mongoose');
var express=require('express');
var session=require('express-session');
var app=express()
require('dotenv')
mongose.set('useNewUrlParser', 'true');
mongose.set('useCreateIndex', 'true');
mongose.set('useFindAndModify', 'true');
mongose.connect("mongodb://127.0.0.1:27017/website");

var db=mongose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',(req,res)=>{
    console.log("connected with db!!!");
})
app.use(cookie());
app.use(session({
    secret:'topsecret ',
    resave:false,
    cookies:{
        secrue:true
    },
}))
module.exports=mongose
</code>```

Blockquote

index.js file

```<code>require('./middleware/auth')
var app=require('./server')
var signup=require('./controller/signup');
var signin=require('./controller/signin')
var session=require('express-session')
var db=require('./db');
var bodyParser = require('body-parser');
var cookie=require('cookie-parser');
var Mongostor=require('connect-mongo');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.set('viewengin','ejs')
app.set('useNewUrlParser', 'true')
app.set('useUnifiedTopology', 'true')
app.use('/user/signup',signup);
app.use('/user/signin',signin);

app.all('*',(req,res)=>{
    return res.json({status: 205,message: 'not found'});
})

var server=app.get('/',(req,res)=>{
req.end()
});
</code>```

答:
You do not need to store token in the database. You just need to verify token and then you will get data if token is valid.

You need to update auth.js file(specially signupuser.findOne({ _id: decode._id})), id to _id and remove token from query

```<code>var express = require('express');
var signupuser = require('../model/singup');
var jwt = require('jsonwebtoken');
var router = express.Router();
var auth = async function (req, res, next) {
    const token = req.header("Authorization").replace('Bearer ', '');
    const decode = jwt.verify(token, "mynameisbhupesh");
    try {
        if(!decode) {
            return res.status(401).send({ error: 'no auth token' });
        }
        const user = await signupuser.findOne({ _id: decode._id});
        if (!user) {
            return res.json("user not loged in");
        }
        req.user = user;
        req.token = token;
        next();
    } catch (err) {
        res.status(401).send({ error: 'no auth token' });
    }
}

module.exports = auth
</code>```

Body:
Que:After generating Authtoken when i am trying to use get method as a profile (which i mentioned in signin.js file) it not providing the user detail instead its showing user is not loged in.(middleware file)

Blockquote

one more question : do i have to store token in database or not? if yes,please explain in detail

controller: signin.js code

var express=require('express');
var signupuser=require('../model/singup')
var router=express.Router();
var bcrypt=require('bcryptjs');
var validator=require('validator');
var jwt=require('jsonwebtoken');
var auth=require('../middleware/auth')
router.post('/',async(req,res)=>
{
const {email,password}=req.body
const user=await signupuser.findByCredentials(email,password)
if(!user){
    return res.status(401).send({error:"Login failed ! email or pasword wrong"})
}
const authtoken=await user.generateauthToken()
res.send({user,authtoken})
});

router.get('/profile',auth,(req,res)=>{  // using this method to get profile but it is not providing token
    res.send(req.user)
})
module.exports=router;

Blockquote

Middleware:auth.js code

var express=require('express');
var signupuser=require('../model/singup')
var jwt=require('jsonwebtoken');
var router=express.Router();
var auth= async function(req,res,next){
const token =req.header("Authorization").replace('Bearer ','')
const decode=jwt.verify(token,"mynameisbhupesh");
try{
    const user= await signupuser.findOne({id:decode._id,'authtoken.token':token})
    if(!user){
        res.json("user not loged in" )
    }
    req.user=user
    req.token=token
    next();
 }catch(err){
res.status(401).send({error:'no auth token'})
 }}

module.exports=auth

Blockquote

model:signup.js

var mongoose=require('mongoose');
require('../db');
var bcrypt=require('bcryptjs');
var validator=require('validator');
var jwt=require('jsonwebtoken');
mongoose.Promise=require('bluebird');
var schema= new mongoose.Schema({
    name:{type:String,required:true},
    email:{type:String,required:true,unique:true,validate:value=>{
        if(!validator.isEmail(value)){
            throw new Error({error:'invalid email address'})
        }
    }},
    password:{type:String,required:true,minlength:5},
    //  authtoken:[{token:{type:String,required:true}}],
});

schema.pre('save',async function(next){
    const user=this
    if(user.isModified('password')){
        user.password=await bcrypt.hash(user.password,8)
    }
    next()
})

schema.methods.generateauthToken=async function(){
    const user=this
    const token=jwt.sign({_id:user._id},"mynameisbhupesh",{
        expiresIn:10000000000000000000000000
    })
    // user.authtoken=user.authtoken.concat({token})
   await user.save()
    return token
}
schema.statics.findByCredentials =async (email,password)=>{
    const user=await signupuser.findOne({email})
    if(!user){
        throw new Error ({error:'Invalid user'})
    }
    const ispassmatch=await bcrypt.compare(password,user.password)
    if(!ispassmatch){
        throw new Error ({error:'Invalid user'})
    }
    return user
     }

const signupuser=mongoose.model('signupuser',schema);
module.exports=signupuser;

Blockquote

controller:signup.js

var express=require('express');
var signupuser=require('../model/singup')
var router=express.Router();
var bcrypt=require('bcryptjs');
var validator=require('validator');
var jwt=require('jsonwebtoken');
router.post('/',async (req,res)=>{
    try{
        const user=new signupuser(req.body)
        await user.save()
        const token=await user.generateauthToken()
        res.status(201).send({user,token})
    }
    catch(error){
        res.status(400).send(error)
    }
})
module.exports=router;

Blockquote

database:db.js

var cookie=require('cookie-parser');
var Mongostor=require('connect-mongo');
var mongose=require('mongoose');
var express=require('express');
var session=require('express-session');
var app=express()
require('dotenv')
mongose.set('useNewUrlParser', 'true');
mongose.set('useCreateIndex', 'true');
mongose.set('useFindAndModify', 'true');
mongose.connect("mongodb://127.0.0.1:27017/website");

var db=mongose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',(req,res)=>{
    console.log("connected with db!!!");
})
app.use(cookie());
app.use(session({
    secret:'topsecret ',
    resave:false,
    cookies:{
        secrue:true
    },
}))
module.exports=mongose

Blockquote

index.js file

require('./middleware/auth')
var app=require('./server')
var signup=require('./controller/signup');
var signin=require('./controller/signin')
var session=require('express-session')
var db=require('./db');
var bodyParser = require('body-parser');
var cookie=require('cookie-parser');
var Mongostor=require('connect-mongo');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.set('viewengin','ejs')
app.set('useNewUrlParser', 'true')
app.set('useUnifiedTopology', 'true')
app.use('/user/signup',signup);
app.use('/user/signin',signin);

app.all('*',(req,res)=>{
    return res.json({status: 205,message: 'not found'});
})

var server=app.get('/',(req,res)=>{
req.end()
});

Body:
You do not need to store token in the database. You just need to verify token and then you will get data if token is valid.

You need to update auth.js file(specially signupuser.findOne({ _id: decode._id})), id to _id and remove token from query

var express = require('express');
var signupuser = require('../model/singup');
var jwt = require('jsonwebtoken');
var router = express.Router();
var auth = async function (req, res, next) {
    const token = req.header("Authorization").replace('Bearer ', '');
    const decode = jwt.verify(token, "mynameisbhupesh");
    try {
        if(!decode) {
            return res.status(401).send({ error: 'no auth token' });
        }
        const user = await signupuser.findOne({ _id: decode._id});
        if (!user) {
            return res.json("user not loged in");
        }
        req.user = user;
        req.token = token;
        next();
    } catch (err) {
        res.status(401).send({ error: 'no auth token' });
    }
}

module.exports = auth


问:
How to avoid transition between column-organized data processing and row-organized data processing
I'm working on DB2 Blu on with column organized tables.

My dataset is the following :

```<code>Day month year value
------- -------
20200101 202001 2020 100
20200102 202001 2020 110
...
20200215 202002 2020 120
</code>```

I want to aggregate by week, month and year for this result :

```<code>Id value
2020 12000
202001 4000 'january
202002 4000 'february
2020001 700 'first week of 2020
</code>```

In order to do this, I also have the table d_tps

```<code>Type Id week month year
J 20200101 2020001 202001 2020
J 20200102 2020001 202001 2020
...

J 20200215 2020007 202002 2020
M 202001 null 202001 2020
M 202002 null 202002 2020
Y 2020 null null 2020

</code>```

My approach is the following

```<code>select d.id, sum(value) from tab1
Inner join d_tps d
On d.id = tab1.year
Or d.id = tab1.month
Or d.id = tab1.year
group by d.id
</code>```

It works and return the expected result. Unfortunately, in the query plan, the join with OR condition causes the CTQ operator to come early and most of the query (which is in reality more complex) is treated as rows instead of columns.

How can I optimize it ?

答:
You should use GROUP BY GROUPING SETS & GROUPING function to achieve what you want.

```<code>WITH T (day, month, year, value) AS
(
values
  (20200101, 202001, 2020, 100)
, (20200102, 202001, 2020, 110)
, (20200215, 202002, 2020, 120)
)
SELECT
CASE
  WHEN GROUPING(DAY)   = 0 THEN DAY
  WHEN GROUPING(MONTH) = 0 THEN MONTH
  WHEN GROUPING(YEAR ) = 0 THEN YEAR
END AS ID
, SUM(VALUE) AS VALUE
FROM T
GROUP BY GROUPING SETS (DAY, MONTH, YEAR);
</code>```

The result is:

```<code>|ID         |VALUE      |
|-----------|-----------|
|2020       |330        |
|202001     |210        |
|202002     |120        |
|20200101   |100        |
|20200102   |110        |
|20200215   |120        |
</code>```

Body:
I'm working on DB2 Blu on with column organized tables.

My dataset is the following :

Day month year value
------- -------
20200101 202001 2020 100
20200102 202001 2020 110
...
20200215 202002 2020 120

I want to aggregate by week, month and year for this result :

Id value
2020 12000
202001 4000 'january
202002 4000 'february
2020001 700 'first week of 2020

In order to do this, I also have the table d_tps

Type Id week month year
J 20200101 2020001 202001 2020
J 20200102 2020001 202001 2020
...

J 20200215 2020007 202002 2020
M 202001 null 202001 2020
M 202002 null 202002 2020
Y 2020 null null 2020

My approach is the following

select d.id, sum(value) from tab1
Inner join d_tps d
On d.id = tab1.year
Or d.id = tab1.month
Or d.id = tab1.year
group by d.id

It works and return the expected result. Unfortunately, in the query plan, the join with OR condition causes the CTQ operator to come early and most of the query (which is in reality more complex) is treated as rows instead of columns.

How can I optimize it ?

Body:
You should use GROUP BY GROUPING SETS & GROUPING function to achieve what you want.

WITH T (day, month, year, value) AS
(
values
  (20200101, 202001, 2020, 100)
, (20200102, 202001, 2020, 110)
, (20200215, 202002, 2020, 120)
)
SELECT
CASE
  WHEN GROUPING(DAY)   = 0 THEN DAY
  WHEN GROUPING(MONTH) = 0 THEN MONTH
  WHEN GROUPING(YEAR ) = 0 THEN YEAR
END AS ID
, SUM(VALUE) AS VALUE
FROM T
GROUP BY GROUPING SETS (DAY, MONTH, YEAR);

The result is:

|ID         |VALUE      |
|-----------|-----------|
|2020       |330        |
|202001     |210        |
|202002     |120        |
|20200101   |100        |
|20200102   |110        |
|20200215   |120        |


问:
Extracting text/number from tspan class tag HTML with R
I am trying to extract Current Production number from this website http://okg.se/sv/Produktionsinformation/ (in the blue area below).

Here is the HTML code part I need to use:

```<code><tspan dy="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">518</tspan>
</code>```

The example of the code I used:

```<code>url <- "http://okg.se/sv/Produktionsinformation//"
download.file(url, destfile = "scrapedpage.html", quiet=TRUE)
content <- read_html("scrapedpage.html")
content %>% html_nodes(".content__info__item__value")
</code>```

But the result I get shows that there is not nodes available:

```<code>{xml_nodeset (0)}
</code>```

Do you have any ides on how to solve this issue?

Thanks in advance!

答:
I am not pretty sure about the value that you need, but this work</p>

```<code>librar(rvest)

# page url
url <- "http://okg.se/sv/Produktionsinformation/"

# current value
read_html(url) %>%
  html_nodes(".footer__gauge") %>%
  html_attr("data-current")

# Max value
read_html(url) %>%
  html_nodes(".footer__gauge") %>%
  html_attr("data-max")

</code>```

Body:
I am trying to extract Current Production number from this website http://okg.se/sv/Produktionsinformation/ (in the blue area below).

Here is the HTML code part I need to use:

<tspan dy="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">518</tspan>

The example of the code I used:

url <- "http://okg.se/sv/Produktionsinformation//"
download.file(url, destfile = "scrapedpage.html", quiet=TRUE)
content <- read_html("scrapedpage.html")
content %>% html_nodes(".content__info__item__value")

But the result I get shows that there is not nodes available:

{xml_nodeset (0)}

Do you have any ides on how to solve this issue?

Thanks in advance!

Body:
I am not pretty sure about the value that you need, but this work

librar(rvest)

# page url
url <- "http://okg.se/sv/Produktionsinformation/"

# current value
read_html(url) %>%
  html_nodes(".footer__gauge") %>%
  html_attr("data-current")

# Max value
read_html(url) %>%
  html_nodes(".footer__gauge") %>%
  html_attr("data-max")


问:
Why should I use docker ONBUILD?

1. Scenario with ONBUILD

Base Dockerfile

```<code>FROM ubuntu:latest
RUN apt-get update && apt-get install python3

ONBUILD COPY test.py test.py
</code>```

Obliviously, when we build above Dockerfile(test-image:latest), the COPY wont affected.(The test.py not copied)

Now onbuild Dockerfile

```<code>FROM test-image:latest
</code>```

Now, when we build above Dockerfile, the COPY will affect, copies test.py

2. Scenario without ONBUILD

I achieve same thing without use ONBUILD

Base Dockerfile

```<code>FROM ubuntu:latest
RUN apt-get update && apt-get install python3
</code>```

Above Dockerfile build docker image which has python3 (test-image2:latest)

Now child docker image Dockerfile

```<code>FROM test-image2:latest
COPY test.py /test.py
</code>```

So, my question is, why should I use ONBUILD or when should use? is there any performance difference

答:
I think that the answer is simple:  you want to use ONBUILD when your parent image has to be used in various children images, so you

avoid repetitions

contstrain the user of the image to have test.py copied

Title: Why should I use docker ONBUILD?

Body:
1. Scenario with ONBUILD

Base Dockerfile

FROM ubuntu:latest
RUN apt-get update && apt-get install python3

ONBUILD COPY test.py test.py

Obliviously, when we build above Dockerfile(test-image:latest), the COPY wont affected.(The test.py not copied)

Now onbuild Dockerfile

FROM test-image:latest

Now, when we build above Dockerfile, the COPY will affect, copies test.py

2. Scenario without ONBUILD

I achieve same thing without use ONBUILD

Base Dockerfile

FROM ubuntu:latest
RUN apt-get update && apt-get install python3

Above Dockerfile build docker image which has python3 (test-image2:latest)

Now child docker image Dockerfile

FROM test-image2:latest
COPY test.py /test.py

So, my question is, why should I use ONBUILD or when should use? is there any performance difference


答:
Try this to make new ref

```<code>let a = ["a","b","c"]
let b = "dd"
let c = [...a]
c.push(b)

console.log(a);
console.log(c);
</code>```

Title: How can i push item on an array without change the initialised array

Body:
Try this to make new ref

let a = ["a","b","c"]
let b = "dd"
let c = [...a]
c.push(b)

console.log(a);
console.log(c);


问:
Problem with PUT , alter all tables ReactJs
I would like to explain my problem of the day.

In the following code, everything works properly.

unfortunately when I PUT it changes all the tables in my database.

I would like this to change only the table on which I make my put

```<code> import React, { Component } from 'react';
 import { CardText, Card, Row, Col, Button } from 'reactstrap';

 const entrypoint = process.env.REACT_APP_API_ENTRYPOINT + '/api';

 class AdminPage extends Component {

 constructor(props) {
 super(props);
 this.state= {
 data: [],
 }
 handleSubmit = (e) => {
 e.preventDefault();
 const config = {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({livree: new Date().toISOString().slice(11,16)}),
 };

  const url = entrypoint + "/alluserpls";
  fetch(url, config)
  .then(res => res.json())
  .then(res => {
    if (res.error) {
      alert(res.error);
    } else {
      alert(`ajouté avec l'ID ${res}!`);
    }
  }).catch(e => {
    console.error(e);

    }).finally(() => this.setState({ redirect: true }));
 }
 getRandom = async () => {

const res = await axios.get(
  entrypoint + "/alluserpls"
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
 }

 render() {

 let datas = this.state.data.map((datass, index) => {
   return (
    <div >
      <Col sm="12" key={index} className="wtfFuHereIsForOnlyBackGroundColorForCol12Nice">
                <form onSubmit={this.handleSubmit}>
      <button type="submit">Add</button>
      </form>
              </Button>
              <CardText className="cardTextForAdminPageForDataName"> Commande de
              {datass.name}</CardText>
              <Col sm="6">
                <CardText>{datass.alertStyle} </CardText>
              </Col>
      </ Col>
      </div>
     )
   })
  return (
       <div>
          {datas}
        </div>
   )
 }
}
export default AdminPage
</code>```

that is route on back

```<code> app.put('/api/alluserpls', (req, res, ) => {
 // récupération des données envoyées
 const formData = req.body;
 connection.query('UPDATE alluserpls SET ?', formData, err => {
 if (err) {
  // Si une erreur est survenue, alors on informe l'utilisateur de
l'erreur
  console.log(err);
  res.status(500).send("Erreur lors de la modification des users");
} else {
  // Si tout s'est bien passé, on envoie un statut "ok".
  res.sendStatus(200);
 }
});
});
</code>```

I tried to clean as much as possible
Do you have an idea of how to fix this? Neff

答:
unfortunately when I PUT it changes all the tables in my database.

I believe you mean it is changing all the rows of your table, not all tables.

Your UPDATE command does not have any WHERE clause or anything else limiting your update to a single row, which means that all rows are updated

Body:
I would like to explain my problem of the day.

In the following code, everything works properly.

unfortunately when I PUT it changes all the tables in my database.

I would like this to change only the table on which I make my put

 import React, { Component } from 'react';
 import { CardText, Card, Row, Col, Button } from 'reactstrap';

 const entrypoint = process.env.REACT_APP_API_ENTRYPOINT + '/api';

 class AdminPage extends Component {

 constructor(props) {
 super(props);
 this.state= {
 data: [],
 }
 handleSubmit = (e) => {
 e.preventDefault();
 const config = {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({livree: new Date().toISOString().slice(11,16)}),
 };

  const url = entrypoint + "/alluserpls";
  fetch(url, config)
  .then(res => res.json())
  .then(res => {
    if (res.error) {
      alert(res.error);
    } else {
      alert(`ajouté avec l'ID ${res}!`);
    }
  }).catch(e => {
    console.error(e);

    }).finally(() => this.setState({ redirect: true }));
 }
 getRandom = async () => {

const res = await axios.get(
  entrypoint + "/alluserpls"
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
 }

 render() {

 let datas = this.state.data.map((datass, index) => {
   return (

      <Col sm="12" key={index} className="wtfFuHereIsForOnlyBackGroundColorForCol12Nice">
                <form onSubmit={this.handleSubmit}>
      <button type="submit">Add</button>
      </form>
              </Button>
              <CardText className="cardTextForAdminPageForDataName"> Commande de
              {datass.name}</CardText>
              <Col sm="6">
                <CardText>{datass.alertStyle} </CardText>
              </Col>
      </ Col>

     )
   })
  return (

          {datas}

   )
 }
}
export default AdminPage

that is route on back

 app.put('/api/alluserpls', (req, res, ) => {
 // récupération des données envoyées
 const formData = req.body;
 connection.query('UPDATE alluserpls SET ?', formData, err => {
 if (err) {
  // Si une erreur est survenue, alors on informe l'utilisateur de
l'erreur
  console.log(err);
  res.status(500).send("Erreur lors de la modification des users");
} else {
  // Si tout s'est bien passé, on envoie un statut "ok".
  res.sendStatus(200);
 }
});
});

I tried to clean as much as possible
Do you have an idea of how to fix this? Neff


问:
ngClass directive to use with ngFor
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

```<code><ul>
      <li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
    </ul>
income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];
</code>```

答:
I have modified only the template part which you have given.

With the consideration of data from backend, and assuming that the text will be like you have given, the solution as follows..

Using [innerHTML] property you can give the string split up step by step and when you reach the $ part, just give class   like,

You can split the text part by part like, ''+ text.text.split(' ')[3][0] + '' .

By this way, you can make only the $ as bold and remaining text as it is..

```<code><ul>
  <li *ngFor="let text of income; let i = index">
    <div [innerHTML]="text.text.split(' ')[3][0] ? text.text.split(' ')[0] + ' ' + text.text.split(' ')[1]+ ' ' + text.text.split(' ')[2] + ' ' + '<strong>'+ text.text.split(' ')[3][0] + '</strong>' + ' ' + text.text.split(' ')[3].substring(1) : text.text"></div>
    </li>
</ul>
</code>```

Working Stackblitz

Title: ngClass directive to use with ngFor

Body:
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

{{text.text}}

income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];

Body:
I have modified only the template part which you have given.

With the consideration of data from backend, and assuming that the text will be like you have given, the solution as follows..

Using [innerHTML] property you can give the string split up step by step and when you reach the $ part, just give class <b> </b> like,

You can split the text part by part like, '<b>'+ text.text.split(' ')[3][0] + '</b>' .

By this way, you can make only the $ as bold and remaining text as it is..

<ul>
  <li *ngFor="let text of income; let i = index">
    <div [innerHTML]="text.text.split(' ')[3][0] ? text.text.split(' ')[0] + ' ' + text.text.split(' ')[1]+ ' ' + text.text.split(' ')[2] + ' ' + '<strong>'+ text.text.split(' ')[3][0] + '</strong>' + ' ' + text.text.split(' ')[3].substring(1) : text.text"></div>
    </li>
</ul>

Working Stackblitz


问:
Obtain libAdIdAccess.a via Carthage for GoogleIDFASupport
My task currently is to enable IDFA Collection for an app. For that I'm supposed to link two libraries according to this: https://support.google.com/firebase/answer/6318039?hl=en.

AdSupport.Framework I can find but I've no clue where to get libAdIdAccess.a from. It seems to be  part of https://cocoapods.org/pods/GoogleIDFASupport, but as the title already tells I can't use any pods for this project.

As we already imported firebase stuff like this https://github.com/firebase/firebase-ios-sdk/blob/master/Carthage.md I thought it may be part of that but it also isn't.

So I now hope to find the answer to where I can obtain this library from when not using cocoa pods but rather carthage?

答:
Google provides only two official ways to import that binary: via Cocoapods and by downloading zip file from their site with all that extra dependencies ~ 1gb.
Anyway, you can find in Cocoapods logs (via --verbose command) the url with the only file you needed. Here is the link to git repository with the dependency https://github.com/CocoaPods/Specs/tree/master/Specs/1/c/4/GoogleIDFASupport

You may manually import that binary to your project, or make a private git and provide it to your carthfile via git [git address] [sha commit]


问:
When do Redis PUB/SUB events fire-and-forget?
Redis events are fire-and-forget. If no one is listening, they will just remain undetected. There's no history. But nowhere on the internet did I find anything that answers the following question (I'm using redis-py and aioredis for python):

Does the code actually need to LISTEN to the events to receive it or will the redis connection cache events for me?

Let's suppose I have this loop:

```<code>redis_db = Redis(...)

while True:
    print("Hey, I'm listening now!")
    msg = redis_db.blocking_subscribe("some_topic") # pseudo-code, because I'm using various libraries
    if msg == "calc":
        do_a_heavy_5_seconds_calculation()
        print("YAY, I was busy and am back up now!")
</code>```

So will I miss all events that occur in the 5s calculation or will my redis_db cache them for me?

In other words... does fire-and-forget apply if I don't have a connection or if I have a connection, but am not listening ?

答:
As you mentioned, if you are using Redis Pub/Sub, it is a fire and forget so your application has to be up and running and listen to the event.

I have to say that I have not tested your use case.

For your logic, to have more control, I would suggest you look at Redis Streams.

First of all, this is not a fire-and-forget publish-subscribe, ut a more resilient messaging system.

Your application will control which messages to read, have to be read and send an ack when read.

Your pseudo-code will be very easy to implement with Streams, with better control.

Body:
Redis events are fire-and-forget. If no one is listening, they will just remain undetected. There's no history. But nowhere on the internet did I find anything that answers the following question (I'm using redis-py and aioredis for python):

Does the code actually need to LISTEN to the events to receive it or will the redis connection cache events for me?

Let's suppose I have this loop:

redis_db = Redis(...)

while True:
    print("Hey, I'm listening now!")
    msg = redis_db.blocking_subscribe("some_topic") # pseudo-code, because I'm using various libraries
    if msg == "calc":
        do_a_heavy_5_seconds_calculation()
        print("YAY, I was busy and am back up now!")

So will I miss all events that occur in the 5s calculation or will my redis_db cache them for me?

In other words... does fire-and-forget apply if I don't have a connection or if I have a connection, but am not listening ?


问:
Format credit card in edit text in android
How to make EditText accept input in format:

```<code>4digit 4digit 4digit 4digit
</code>```

I tried Custom format edit text input android to accept credit card number, but unfortunately I was unable to delete the spaces. Whenever there is a space, I could not to delete it. Please help me in finding out the issue.

答:
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;`

public class CreditCard implements TextWatcher
{
    EditText editText;

    public CreditCard(EditText editText)
    {
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        try
        {
            editText.removeTextChangedListener(this);

            String str = editText.getText().toString().replaceAll("-", "");

            editText.setText(setDash(str));

            editText.setSelection(editText.getText().toString().length());

            editText.addTextChangedListener(this);
            return;
        }

        catch (Exception ex)
        {
            ex.printStackTrace();
            editText.addTextChangedListener(this);
        }

    }

    public static String setDash(String value)
    {
        String str = "";
        int j = 0;

        for (int i = 0;i<value.length(); i++)
        {
            j++;

            if (j == 5)
            {
                str = str+"-";
                j = 1;
            }

            str = str + value.charAt(i);
        }

        return str;

    }

    public static String trimDashOfString(String string)
    {
        if (string.contains("-")) {
            return string.replace("-", "");
            } else {
            return string;
        }

    }
}
```

Body:
How to make EditText accept input in format:

4digit 4digit 4digit 4digit

I tried Custom format edit text input android to accept credit card number, but unfortunately I was unable to delete the spaces. Whenever there is a space, I could not to delete it. Please help me in finding out the issue.


问:
Using Items definition on public static void in c#
I have problem using Items on public static void.

When I try to recover with a for each the items element is not recognized.

How to do resolve this ?

Please, can you help me ?

My code below.

.aspx

```<code>  <asp:DropDownCheckBoxes ID="propo" runat="server"
        UseSelectAllNode="false"
        Enabled="true"
        CssClass="body"
        UseButtons="true">
        <Style SelectBoxWidth="400"
            DropDownBoxBoxWidth="400"
            DropDownBoxBoxHeight="500"
            SelectBoxCssClass="body"
            DropDownBoxCssClass="body" />
        <Texts SelectBoxCaption="[ ------- Select ------- ]" />
    </asp:DropDownCheckBoxes>
</code>```

.cs

```<code>public class pnpropo
{
    public string propo { get; set; }
}

[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnpro(pnpropo pro)
{
   string xpro = string.Empty;

   foreach (System.Web.UI.WebControls.ListItem item in pro.propo.Items) <<< line error
   {
      if (item.Selected)
      {
         xpro += item.Value + "; ";
      }
   }
}
</code>```

答:
You have to change the type of property propo. I suggest you use a

```<code>List<System.Web.UI.WebControls.ListItem>
</code>```

Try like:

```<code>public class pnpropo
{
    public List<System.Web.UI.WebControls.ListItem> propo { get; set; }
}

[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnpro(pnpropo pro)
{
   string xpro = string.Empty;

   foreach (System.Web.UI.WebControls.ListItem item in pro.propo)
   {
      if (item.Selected)
      {
         xpro += item.Value + "; ";
      }
   }
}
</code>```

Body:
I have problem using Items on public static void.

When I try to recover with a for each the items element is not recognized.

How to do resolve this ?

Please, can you help me ?

My code below.

.aspx

  <asp:DropDownCheckBoxes ID="propo" runat="server"
        UseSelectAllNode="false"
        Enabled="true"
        CssClass="body"
        UseButtons="true">

Body:
You have to change the type of property propo. I suggest you use a

List<System.Web.UI.WebControls.ListItem>

Try like:

public class pnpropo
{
    public List<System.Web.UI.WebControls.ListItem> propo { get; set; }
}

[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnpro(pnpropo pro)
{
   string xpro = string.Empty;

   foreach (System.Web.UI.WebControls.ListItem item in pro.propo)
   {
      if (item.Selected)
      {
         xpro += item.Value + "; ";
      }
   }
}


问:
Remove gap between widget
I want to close the gap between the lists but its just not working. the only option i have is to increase the gap : Sizedbox,spacer,divider

screenshot of my problem

code:

body: Container(
        child: Column(
          children: <Widget>[
            _mainList(Icon(Icons.cached), "Erste", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Zweite", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Dritte", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Vierte", "21:13 pm"),
          ]
        )
  )```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  Widget _mainList(Icon symbol, String name, String time){
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: ListTile(
        leading: symbol,
        title: Text(name, textScaleFactor: 1.2),
        trailing: Text(time, textScaleFactor: 1.3),
      ),
    );
  }</code>```

答:
contentPadding of ListTile is EdgeInsets.symmetric(horizontal: 16.0) by default. So it has padding from top and bottom. You can change it like following:

```<code>ListTile(
  // I made zero padding for this example but you can give anything you want
  contentPadding: EdgeInsets.zero,
  leading: symbol,
  title: Text(name, textScaleFactor: 1.2),
  trailing: Text(time, textScaleFactor: 1.3),
)
</code>```

Title: Remove gap between widget

Body:
I want to close the gap between the lists but its just not working. the only option i have is to increase the gap : Sizedbox,spacer,divider

screenshot of my problem

code:

body: Container(
        child: Column(
          children: <Widget>[
            _mainList(Icon(Icons.cached), "Erste", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Zweite", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Dritte", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Vierte", "21:13 pm"),
          ]
        )
  )

  Widget _mainList(Icon symbol, String name, String time){
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: ListTile(
        leading: symbol,
        title: Text(name, textScaleFactor: 1.2),
        trailing: Text(time, textScaleFactor: 1.3),
      ),
    );
  }

Body:
contentPadding of ListTile is EdgeInsets.symmetric(horizontal: 16.0) by default. So it has padding from top and bottom. You can change it like following:

ListTile(
  // I made zero padding for this example but you can give anything you want
  contentPadding: EdgeInsets.zero,
  leading: symbol,
  title: Text(name, textScaleFactor: 1.2),
  trailing: Text(time, textScaleFactor: 1.3),
)


问:
c++ SIGTERM not returning after caught
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

```<code>class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}
</code>```

EDIT: sorry did not finish the code off properly.

答:
As was mentioned above volatile is the correct answer. Also I'd like to add that according to you code sigwait() will be better solution instead the loop... BTW in case of sigwait you do not need signal handler

Opps, sorry miss a socket operations

Title: c++ SIGTERM not returning after caught

Body:
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}

EDIT: sorry did not finish the code off properly.


问:
Website not loading CSS, Webpage not loading Images
CSS is perfectly loading on the offline webpage (localhost) but on the live website, CSS is not loading.

I am using hosting and domain from the biz.nf website.
I used bootstrap 4 on this website.

My index.html head code:

```<code>   <!DOCTYPE html>
   <html>
   <head>

    <title> </title>
    <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
     <link rel="stylesheet" type="text/css" href="http://www.site.c1.biz/css/style.css" media="screen" />
     <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
   </head>
</code>```

答: Maybe you try using relative css path or check your webserver configuration, because loading the CSS file returned a 403 forbidden error code. </p>

Body:
CSS is perfectly loading on the offline webpage (localhost) but on the live website, CSS is not loading.

I am using hosting and domain from the biz.nf website.
I used bootstrap 4 on this website.

My index.html head code:

   <!DOCTYPE html>

    <title> </title>
    <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
     <link rel="stylesheet" type="text/css" href="http://www.site.c1.biz/css/style.css" media="screen" />
     <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">


问:
NameError: name '*' is not defined
Why this line add(root, sum, 0) gets NameError: name 'add' is not defined error?

```<code>class Solution:
    def rob(root: TreeNode) -> int:
        sum = [0, 0]
        add(root, sum, 0)
        if sum[0] < sum[1]:
            return sum[1]
        else:
            return sum[0]

    def add(node: TreeNode, sum: List[int], index: int):
        if not node:
            return
        sum[index] += node.val
        index += 1
        if index >= len(sum):
            index = 0;
        add(node.left, sum, index)
        add(node.right, sum, index)
</code>```

答:
Try this.</p>

```<code>class Solution:
    def rob(self, root: TreeNode) -> int:
        sum = [0, 0]
        self.add(root, sum, 0)
        if sum[0] < sum[1]:
             return sum[1]
        else:
             return sum[0]

    def add(self, node: TreeNode, sum: List[int], index: int):
        if not node:
            return
        sum[index] += node.val
        index += 1
        if index >= len(sum):
            index = 0;
        self.add(node.left, sum, index)
        self.add(node.right, sum, index)
</code>```

Title: NameError: name '*' is not defined

Body:
Why this line add(root, sum, 0) gets NameError: name 'add' is not defined error?

class Solution:
    def rob(root: TreeNode) -> int:
        sum = [0, 0]
        add(root, sum, 0)
        if sum[0] < sum[1]:
            return sum[1]
        else:
            return sum[0]

    def add(node: TreeNode, sum: List[int], index: int):
        if not node:
            return
        sum[index] += node.val
        index += 1
        if index >= len(sum):
            index = 0;
        add(node.left, sum, index)
        add(node.right, sum, index)

Body:
Try this.

class Solution:
    def rob(self, root: TreeNode) -> int:
        sum = [0, 0]
        self.add(root, sum, 0)
        if sum[0] < sum[1]:
             return sum[1]
        else:
             return sum[0]

    def add(self, node: TreeNode, sum: List[int], index: int):
        if not node:
            return
        sum[index] += node.val
        index += 1
        if index >= len(sum):
            index = 0;
        self.add(node.left, sum, index)
        self.add(node.right, sum, index)


问:
Stripe connect transfers and payouts without verification
I am trying to clarify things associated with Stripe Connect's paymentIntent and transfers endpoints. The thing is that I do think that I do not understand the flow perfectly and even do not know if I did choose the best solution for my application.

I am using the separate charges and transfers method and for the account type I did choose custom.

What I want to achieve is the following:

Get money from user A and send it to user B (user in this context is my platform user not the Stripe Account or Customer). I want to take my cut while I send the money to user B. It leads to a question, if I do need to create both the Stripe Customer and Account. And if the user B who gets the money after transfer is not acting as a company, why would I need to collect industry and other legal information from him/her just to make payout?

What I did:

First of all I do create Stipe Customer and Account for my platform users. Then I:

Create PaymentIntent to take money from (Stripe Customer A). Includes the Stripe fees

Create Transfer of the PaymentIntent and transfer it to (Stripe Account B).

Now I want to create payout of the transferred money. Do I have to trigger the payout endpoint for this case?

The 3 last steps in code:

Create paymentIntent

```<code>const paymentIntent = {description, amount, currency, customer_id, transfer_group, payment_method, confirmation_method: 'manual', confirm: true};
const response = await stripe.paymentIntents.create(paymentIntent);
</code>```

Create transfer

```<code>const transfer = { amount, currency, destination: destinationAccount, transfer_group };
const response = await stripe.transfers.create(transfer);
stripe.paymentIntents.confirm(response.client_secret, {payment_method: response.payment_method})
</code>```

Now money is taken from Customer A and transferred to Account B but I have no idea what legal information I need from my platform users to be able to create payouts? All my Stripe accounts/customers did accept the tos_acceptance also while adding a new source. None of my platform users are industry nor a company. They are individuals doing their things.

答:
To follow the flow which you mentioned you need to create stripe Connect account for each of your customer B. As you need to do payouts to there bank accounts they need to be completely verified by stripe this shows legal information required for verification as per country
Though your end users are individuals you need to completely prove them for authenticity as you are involving them in legal fund transfer and making there sub-merchant accounts.

And you don't have to trigger the payout end point as it is automatically handled by stripe and you can also change it either you want to do payout weekly/daily/monthly etc and also set for custom payouts from dashboard settings.

Body:
I am trying to clarify things associated with Stripe Connect's paymentIntent and transfers endpoints. The thing is that I do think that I do not understand the flow perfectly and even do not know if I did choose the best solution for my application.

I am using the separate charges and transfers method and for the account type I did choose custom.

What I want to achieve is the following:

Get money from user A and send it to user B (user in this context is my platform user not the Stripe Account or Customer). I want to take my cut while I send the money to user B. It leads to a question, if I do need to create both the Stripe Customer and Account. And if the user B who gets the money after transfer is not acting as a company, why would I need to collect industry and other legal information from him/her just to make payout?

What I did:

First of all I do create Stipe Customer and Account for my platform users. Then I:

Create PaymentIntent to take money from (Stripe Customer A). Includes the Stripe fees

Create Transfer of the PaymentIntent and transfer it to (Stripe Account B).

Now I want to create payout of the transferred money. Do I have to trigger the payout endpoint for this case?

The 3 last steps in code:

Create paymentIntent

const paymentIntent = {description, amount, currency, customer_id, transfer_group, payment_method, confirmation_method: 'manual', confirm: true};
const response = await stripe.paymentIntents.create(paymentIntent);

Create transfer

const transfer = { amount, currency, destination: destinationAccount, transfer_group };
const response = await stripe.transfers.create(transfer);
stripe.paymentIntents.confirm(response.client_secret, {payment_method: response.payment_method})

Now money is taken from Customer A and transferred to Account B but I have no idea what legal information I need from my platform users to be able to create payouts? All my Stripe accounts/customers did accept the tos_acceptance also while adding a new source. None of my platform users are industry nor a company. They are individuals doing their things.


问:
Unable to find column names in a FK constraint
I have created two tables in Snowflake.

```<code>create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);

create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);
</code>```

Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.

EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.

答:
Updated answer:

I was checking on something unrelated and noticed a very efficient way to list all primary and foreign keys:

```<code>show exported keys in account; -- Foreign keys
show primary keys in account;
</code>```

When you limit the call to a table, it appears you have to request the foreign keys that point to the parent table:

```<code>show exported keys in table "DB_NAME"."SCHEMA_NAME"."PARENT_TABLE";
</code>```

You can check the documentation for how to limit the show command to a specific database or schema, but this returns rich information in a table very quickly.

Body:
I have created two tables in Snowflake.

create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);

create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);

Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.

EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.

Body:
Updated answer:

I was checking on something unrelated and noticed a very efficient way to list all primary and foreign keys:

show exported keys in account; -- Foreign keys
show primary keys in account;

When you limit the call to a table, it appears you have to request the foreign keys that point to the parent table:

show exported keys in table "DB_NAME"."SCHEMA_NAME"."PARENT_TABLE";

You can check the documentation for how to limit the show command to a specific database or schema, but this returns rich information in a table very quickly.


问:
all? method behavior with ampersand (&) and a block
I have a method to check if a coordinate is valid.

```<code>def valid_coordinate?(coordinate)
  valid_latitude?(coordinate['lat']) && valid_longitude?(coordinate['lng'])
end
</code>```

When I try to use it with all? for an array of hashes (An example hash is {"lat" => 63, "lng" => -24}), it works with a block but it does not work with an ampersand.

Working version:

coordinates.all? { |c| valid_coordinate?(c) }

Non-working version:

coordinates.all?(&:valid_coordinate?)

I get the following error:

NoMethodError: undefined method `valid_coordinate?' for {"lat"=>63, "lng"=>-24}:Hash

I also checked the documentation page for my Ruby version but could not find an explanation. As far as I know, an ampersand can be used with this method ([1,3,5].all?(&:odd?)).

答:
This 'ampersand' notation is a short form of:

```<code>coordinates.all? { |c| c.valid_coordinate? }
</code>```

It's obviously different from what you wanted since valid_coordinate? is being called on the object held by c variable instead of self:

```<code>coordinated.all? { |c| valid_coordinate?(c) }
</code>```

And that's why it doesn't work.

Body:
I have a method to check if a coordinate is valid.

def valid_coordinate?(coordinate)
  valid_latitude?(coordinate['lat']) && valid_longitude?(coordinate['lng'])
end

When I try to use it with all? for an array of hashes (An example hash is {"lat" => 63, "lng" => -24}), it works with a block but it does not work with an ampersand.

Working version:

coordinates.all? { |c| valid_coordinate?(c) }

Non-working version:

coordinates.all?(&:valid_coordinate?)

I get the following error:

NoMethodError: undefined method `valid_coordinate?' for {"lat"=>63, "lng"=>-24}:Hash

I also checked the documentation page for my Ruby version but could not find an explanation. As far as I know, an ampersand can be used with this method ([1,3,5].all?(&:odd?)).

Body:
This 'ampersand' notation is a short form of:

coordinates.all? { |c| c.valid_coordinate? }

It's obviously different from what you wanted since valid_coordinate? is being called on the object held by c variable instead of self:

coordinated.all? { |c| valid_coordinate?(c) }

And that's why it doesn't work.


问:
PHP - Getting an "[filename] is not commonly downloaded and may be dangerous" alert on an ics file in Google Chrome
I've built a plugin in WordPress that allows the creation of autogenerated .ics files. The header are these two lines:-

```<code>header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=' . get_the_title() . '.ics');
</code>```

I've uploaded it to a new site, and whenever I download the .ical file I get an error saying "[filename] is not commonly downloaded and may be dangerous" within Google Chrome and to download the file I need to select "Keep". This only occurs in Google Chrome (Safari / Firefox download the file as intended).

The domain is registered approximately at the time of writing 24 hours old. Here is what I've done so far.

Installed a different plugin on the same domain, same server that does .ical file export (The Events Calendar), test created an event with ical export. Done the export unsuccessfully (I still get the error).

Installed both The Events Calendar & my plugin on a different domain, different sever. Test created an event in both The Events Calendar & my plugin. Done an export in both plugins successfully (I get no errors).

Installed both The Events Calendar & my plugin on a different domain, same server. Test created an event in both The Events Calendar & my plugin. Done an export in both plugins successfully (I get no errors).

This leads me to believe that the domain is possibly an issue. It is brand new and may need whitelisting(?) in Chrome. Is there a way to do this?

Thanks!

答:
Okay. If anybody else gets this issue, it's because it's a brand new site. After a while (about a week for me), it corrected itself.

Gabor's answer below is half way there, if you sign up to Google Search Console and go to Security & Manual Actions > Security, you will see if your site has any security issues.

If you don't, then eventually the warning will disappear. Again, it was about a week, but you may be different.

I guess possible advice is to register a domain before needing it.

Body:
I've built a plugin in WordPress that allows the creation of autogenerated .ics files. The header are these two lines:-

header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=' . get_the_title() . '.ics');

I've uploaded it to a new site, and whenever I download the .ical file I get an error saying "[filename] is not commonly downloaded and may be dangerous" within Google Chrome and to download the file I need to select "Keep". This only occurs in Google Chrome (Safari / Firefox download the file as intended).

The domain is registered approximately at the time of writing 24 hours old. Here is what I've done so far.

Installed a different plugin on the same domain, same server that does .ical file export (The Events Calendar), test created an event with ical export. Done the export unsuccessfully (I still get the error).

Installed both The Events Calendar & my plugin on a different domain, different sever. Test created an event in both The Events Calendar & my plugin. Done an export in both plugins successfully (I get no errors).

Installed both The Events Calendar & my plugin on a different domain, same server. Test created an event in both The Events Calendar & my plugin. Done an export in both plugins successfully (I get no errors).

This leads me to believe that the domain is possibly an issue. It is brand new and may need whitelisting(?) in Chrome. Is there a way to do this?

Thanks!


问:
403 redirect doesn't work
How to force apache to redirect to a 403 error?

I've tried:

```<code>RewriteRule ^forbid/(.*)$ / [R=403,L]
</code>```

this caused 500 server error on the whole site

```<code>RewriteRule ^forbid/(.*)$ - [R=403,L]
</code>```

and

```<code>RewriteRule ^forbid/(.*)$ [R=403,L]
</code>```

these simply don't work

I have the following .htaccess file:

```<code>RewriteEngine on
RewriteRule ^(config|backup)(.*)$ - [F] [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^admin/(.*)$ /admin/index.php?%{QUERY_STRING} [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !util
RewriteRule ^(.*)$ index.php?%{QUERY_STRING} [L,QSA]
</code>```

Please, help me!

答:
Unless you have a RewriteBase defined that we don't see in your rules, I think you don't want the ^ before 'forbid' your expression, since it would technically start with '/'

```<code>RewriteRule ^forbid/(.*)$ - [R=403,L]
# Instead try
RewriteRule ^/forbid/(.*)$ - [R=403,L]
# Or
RewriteRule forbid/(.*)$ - [R=403,L]
</code>```

Title: 403 redirect doesn't work

Body:
How to force apache to redirect to a 403 error?

I've tried:

RewriteRule ^forbid/(.*)$ / [R=403,L]

this caused 500 server error on the whole site

RewriteRule ^forbid/(.*)$ - [R=403,L]

and

RewriteRule ^forbid/(.*)$ [R=403,L]

these simply don't work

I have the following .htaccess file:

RewriteEngine on
RewriteRule ^(config|backup)(.*)$ - [F] [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^admin/(.*)$ /admin/index.php?%{QUERY_STRING} [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !util
RewriteRule ^(.*)$ index.php?%{QUERY_STRING} [L,QSA]

Please, help me!

Body:
Unless you have a RewriteBase defined that we don't see in your rules, I think you don't want the ^ before 'forbid' your expression, since it would technically start with '/'

RewriteRule ^forbid/(.*)$ - [R=403,L]
# Instead try
RewriteRule ^/forbid/(.*)$ - [R=403,L]
# Or
RewriteRule forbid/(.*)$ - [R=403,L]


问:
Chart JS Fill Between two lines
I am looking for a way to fill between two lines with Chart.js so that it would look like this. I have looked and everything seems to talk about filling between two lines across zero. I also need other lines to fill all the way down like normal. Is this something chart.js can do?

答: On chart.js v2.0 you have this feature now inside. See https://www.chartjs.org/samples/latest/charts/area/line-datasets.html</p>

Title: Chart JS Fill Between two lines


问:
How to use ImplicitEuler solver in Julia?
when trying to call Implicit Euler for solving an ODE, I receive the following error:

```<code>MethodError: no method matching OrdinaryDiffEq.NLNewtonConstantCache(::Float32, ::Array{Float64,2}, ::LinearAlgebra.LU{Float64,Array{Float64,2}}, ::Bool, ::Bool, ::Bool, ::Float32, ::DiffEqBase.UDerivativeWrapper{ODEFunction{false,DiffEqFlux.var"#dudt_#50"{NeuralODE{Chain{Tuple{Dense{typeof(tanh),Array{Float32,2},Array{Float32,1}},Dense{typeof(identity),Array{Float32,2},Array{Float32,1}}}},Array{Float32,1},Flux.var"#12#14"{Chain{Tuple{Dense{typeof(tanh),Array{Float32,2},Array{Float32,1}},Dense{typeof(identity),Array{Float32,2},Array{Float32,1}}}}},Tuple{Float32,Float32},ImplicitEuler{0,false,DefaultLinSolve,NLNewton{Rational{Int64},Rational{Int64},Rational{Int64}},DataType},Tuple{},Base.Iterators.Pairs{Symbol,Any,NTuple{4,Symbol},NamedTuple{(:dt, :saveat, :reltol, :abstol),Tuple{Float64,StepRangeLen{Float32,Float64,Float64},Float64,Float64}}}}},LinearAlgebra.UniformScaling{Bool},Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing},Float32,Array{Float32,1}}, ::Float64, ::Float32, ::Float32)

Closest candidates are:
  OrdinaryDiffEq.NLNewtonConstantCache(::tType, ::J, ::W, ::Bool, ::Bool, ::Bool, ::tType, ::ufType, !Matched::tType, ::tType, ::tType) where {tType, J, W, ufType} at /Users/sdoneva/.julia/packages/OrdinaryDiffEq/nV9bA/src/nlsolve/type.jl:62
</code>```

And this is how I called the solver:

```<code>using Flux, DiffEqFlux, DifferentialEquations, Plots
u0 = [1.0,1.0]
solver = ImplicitEuler(autodiff = false)
tspan_train = (0.0f0,4.00f0)
train_size = 32
t_train = range(tspan_train[1],tspan_train[2],length = train_size)
function create_neural_ode(solver, tspan, t_saveat)
    dudt = Chain(
            Dense(2,50,tanh),
            Dense(50,2))
    ps = Flux.params(dudt)
    n_ode = NeuralODE(dudt, tspan, solver, dt=1/2^4, saveat = t_saveat, reltol=1e-7, abstol=1e-9)
    n_ode
end
n_ode = create_neural_ode(solver, tspan_train, t_train)

plot(n_ode(u0))
</code>```

What is the right way to call ImplicitEuler?

答:
Your state was Float64 while time was Float32, and it just wasn't able to initialize the implicit tooling with that combination. I'd labelled it as a bug and hope to fix it soon, but in the meantime I recommend just using both Float32 or both Float64. Example:

```<code>using Flux, DiffEqFlux, DifferentialEquations, Plots
u0 = Float32[1.0,1.0]
solver = ImplicitEuler(autodiff = false)
tspan_train = (0.0f0,4.00f0)
train_size = 32
t_train = range(tspan_train[1],tspan_train[2],length = train_size)
function create_neural_ode(solver, tspan, t_saveat)
    dudt = Chain(
            Dense(2,50,tanh),
            Dense(50,2))
    ps = Flux.params(dudt)
    n_ode = NeuralODE(dudt, tspan, solver, dt=1/2^4, saveat = t_saveat, reltol=1e-7, abstol=1e-9)
    n_ode
end
n_ode = create_neural_ode(solver, tspan_train, t_train)

plot(n_ode(u0))
</code>```

works just fine.

Body:
when trying to call Implicit Euler for solving an ODE, I receive the following error:

MethodError: no method matching OrdinaryDiffEq.NLNewtonConstantCache(::Float32, ::Array{Float64,2}, ::LinearAlgebra.LU{Float64,Array{Float64,2}}, ::Bool, ::Bool, ::Bool, ::Float32, ::DiffEqBase.UDerivativeWrapper{ODEFunction{false,DiffEqFlux.var"#dudt_#50"{NeuralODE{Chain{Tuple{Dense{typeof(tanh),Array{Float32,2},Array{Float32,1}},Dense{typeof(identity),Array{Float32,2},Array{Float32,1}}}},Array{Float32,1},Flux.var"#12#14"{Chain{Tuple{Dense{typeof(tanh),Array{Float32,2},Array{Float32,1}},Dense{typeof(identity),Array{Float32,2},Array{Float32,1}}}}},Tuple{Float32,Float32},ImplicitEuler{0,false,DefaultLinSolve,NLNewton{Rational{Int64},Rational{Int64},Rational{Int64}},DataType},Tuple{},Base.Iterators.Pairs{Symbol,Any,NTuple{4,Symbol},NamedTuple{(:dt, :saveat, :reltol, :abstol),Tuple{Float64,StepRangeLen{Float32,Float64,Float64},Float64,Float64}}}}},LinearAlgebra.UniformScaling{Bool},Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing},Float32,Array{Float32,1}}, ::Float64, ::Float32, ::Float32)

Closest candidates are:
  OrdinaryDiffEq.NLNewtonConstantCache(::tType, ::J, ::W, ::Bool, ::Bool, ::Bool, ::tType, ::ufType, !Matched::tType, ::tType, ::tType) where {tType, J, W, ufType} at /Users/sdoneva/.julia/packages/OrdinaryDiffEq/nV9bA/src/nlsolve/type.jl:62

And this is how I called the solver:

using Flux, DiffEqFlux, DifferentialEquations, Plots
u0 = [1.0,1.0]
solver = ImplicitEuler(autodiff = false)
tspan_train = (0.0f0,4.00f0)
train_size = 32
t_train = range(tspan_train[1],tspan_train[2],length = train_size)
function create_neural_ode(solver, tspan, t_saveat)
    dudt = Chain(
            Dense(2,50,tanh),
            Dense(50,2))
    ps = Flux.params(dudt)
    n_ode = NeuralODE(dudt, tspan, solver, dt=1/2^4, saveat = t_saveat, reltol=1e-7, abstol=1e-9)
    n_ode
end
n_ode = create_neural_ode(solver, tspan_train, t_train)

plot(n_ode(u0))

What is the right way to call ImplicitEuler?

Body:
Your state was Float64 while time was Float32, and it just wasn't able to initialize the implicit tooling with that combination. I'd labelled it as a bug and hope to fix it soon, but in the meantime I recommend just using both Float32 or both Float64. Example:

using Flux, DiffEqFlux, DifferentialEquations, Plots
u0 = Float32[1.0,1.0]
solver = ImplicitEuler(autodiff = false)
tspan_train = (0.0f0,4.00f0)
train_size = 32
t_train = range(tspan_train[1],tspan_train[2],length = train_size)
function create_neural_ode(solver, tspan, t_saveat)
    dudt = Chain(
            Dense(2,50,tanh),
            Dense(50,2))
    ps = Flux.params(dudt)
    n_ode = NeuralODE(dudt, tspan, solver, dt=1/2^4, saveat = t_saveat, reltol=1e-7, abstol=1e-9)
    n_ode
end
n_ode = create_neural_ode(solver, tspan_train, t_train)

plot(n_ode(u0))

works just fine.


问:
How to render HTML tags in Html.EditorFor in mvc 4 razor
I have one property named Description in my class.
I am having value in it some thing like this

```<code>Object.Description = "<b>Hello</b>";
</code>```

Now I am showing this in view page using Html.EditorFor

```<code>@Html.EditorFor(x => x.Object.Description);
</code>```

This is showing text as "Hello" instead of showing "Hello" in bold.
i.e. it is not rendering HTML tags.

I know that I can render HTML tags like this

```<code>@Html.Raw(HttpUtility.HtmlDecode(Object.Description));
</code>```

But how to use it with EditorFor HTML helper so that I can show all rendered content in textarea ?

Note: I am using http://jqueryte.com/ for showing editor for textarea.

答:
In my case html.editorfor and showing content on other page:</p>

```<code>@Html.Raw(HttpUtility.HtmlDecode(abouts[0].Description))
</code>```

Body:
I have one property named Description in my class.
I am having value in it some thing like this

Object.Description = "Hello";

Now I am showing this in view page using Html.EditorFor

@Html.EditorFor(x => x.Object.Description);

This is showing text as "Hello" instead of showing "Hello" in bold.
i.e. it is not rendering HTML tags.

I know that I can render HTML tags like this

@Html.Raw(HttpUtility.HtmlDecode(Object.Description));

But how to use it with EditorFor HTML helper so that I can show all rendered content in textarea ?

Note: I am using http://jqueryte.com/ for showing editor for textarea.

Body:
In my case html.editorfor and showing content on other page:

@Html.Raw(HttpUtility.HtmlDecode(abouts[0].Description))


问:
Django Management Command best practice for additional file location
I am writing a Django management command. The command itself is located under myapp/management/commands/mycommand.py. I need to write an additional class which I would like to place in an extra file.

Should this file live in

myapp/extrafile.py or

myapp/management/commands/extrafile.py

What would be a recommended location. The class is only need for the management command, not elsewhere in the app.

答:
Generally in these cases you are writing a helper file for that file so You can create a helper folder like this:

```<code>myapp
-helpers
--commands
--other_helpers
</code>```

you can read more about helpers here, they can be separated from the original class/function.

Body:
Generally in these cases you are writing a helper file for that file so You can create a helper folder like this:

myapp
-helpers
--commands
--other_helpers

you can read more about helpers here, they can be separated from the original class/function.


问:
Bigger value without greater than or less than operators
this is just for fun.

Can you give me a way to determine the greater value of two numbers? You can use other operators except greater than or less than operator.

Use any tool you like (programming language, pencil paper, etc.).
And another thing you cannot do the following:

int main()
{
    int num1, num2;
    cin >> num1 >> num2;

    if( (num1-num2) + abs(num1-num2) )
        cout << num1 << " is bigger" << endl;
    else
        cout << num2 << " is bigger" << endl;
    return 0;
}
```

答:
Well, if you assume two's complement arithmetic:

```<code>int highBit = ~INT_MAX;
int rslt = num1 - num2;

if (rslt & highBit)
    // num2 > num1
else if (rslt)
    // num1 > num2
else
    // num1 == num2
</code>```

This will only work when both numbers are positive. For example, if num1 is positive and num2 is negative, then num1-num2 could overflow, causing the result to be negative, which would erroneously report that num2 > num1. If both numbers are negative, this will report the opposite (i.e. -12 will be reported greater than -1).

Body:
Well, if you assume two's complement arithmetic:

int highBit = ~INT_MAX;
int rslt = num1 - num2;

if (rslt & highBit)
    // num2 > num1
else if (rslt)
    // num1 > num2
else
    // num1 == num2

This will only work when both numbers are positive. For example, if num1 is positive and num2 is negative, then num1-num2 could overflow, causing the result to be negative, which would erroneously report that num2 > num1. If both numbers are negative, this will report the opposite (i.e. -12 will be reported greater than -1).


问:
Connect Postgres DB and Models (Django & Flask) in Docker containers
I have Docker Containers application with Flask and Django containers. It is possible share Database between Django container and Flask Container?

```<code> django: &django
  ...
  depends_on:
  - postgres

 flask:
  ...
  ports:
    - "5090:5090"
  ...
  - postgres
  links:
  - postgres

 postgres:
   build:
   ...
   env_file:
  - ./.envs/.local/.postgres
</code>```

Models are in Django application. So, I need to do a Login in Flask Application using Postgres Database. The problem is, I only want to use the connection to Database, I do not need to do models in Flask.

I used Sqlalchemy method:

```<code>  if form.validate_on_submit():
    query = session.query(User)
    login = User.query.filter(username=form.username.data).first()
    if login is not None:
        print(login)
        return redirect(url_for('index'))
   return render_template('login.html', form=form)
</code>```

And I tried with Panda method:

```<code>     if form.validate_on_submit():
    sql = "SELECT * from users WHERE username = '{0}'".format(form.username.data)
    login = pd.read_sql_query(sql,SQLALCHEMY_DATABASE_URI)
    if login is not None:
        print(login)
        return redirect(url_for('index'))
</code>```

But the error is the same in both cases, I need to do a relation, so, it is a Migration, in Flask.

```<code>   **sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users"**
</code>```

It is my database.py:

```<code>     ...
     SQLALCHEMY_DATABASE_URI = 'postgres://%s:%s@%s:%s/%s' % (user, pwd, host, port, db)
     SQLALCHEMY_TRACK_MODIFICATIONS = os.environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')

     db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=engine))
     def init_db():
     ...
</code>```

答:
It's certainly possible to share the database between multiple containers. I wouldn't, but it's possible, nonetheless.

The error I see above seems to be that the user table doesn't have the name you'd expect. You can verify using some database gui or the psql cli tool. Unless you explicitly named it users it will be named using the <app_name>_<model_name> convention. If you're using the default django User model then the actual db table will be named auth_user.

Side note: you could definitely continue this way, but, if you have some time to invest on the problem: I'd highly suggest you look into OAUTH+OIDC, JWTs, and how to accomplish SSO using them.

Body:
I have Docker Containers application with Flask and Django containers. It is possible share Database between Django container and Flask Container?

 django: &django
  ...
  depends_on:
  - postgres

 flask:
  ...
  ports:
    - "5090:5090"
  ...
  - postgres
  links:
  - postgres

 postgres:
   build:
   ...
   env_file:
  - ./.envs/.local/.postgres

Models are in Django application. So, I need to do a Login in Flask Application using Postgres Database. The problem is, I only want to use the connection to Database, I do not need to do models in Flask.

I used Sqlalchemy method:

  if form.validate_on_submit():
    query = session.query(User)
    login = User.query.filter(username=form.username.data).first()
    if login is not None:
        print(login)
        return redirect(url_for('index'))
   return render_template('login.html', form=form)

And I tried with Panda method:

     if form.validate_on_submit():
    sql = "SELECT * from users WHERE username = '{0}'".format(form.username.data)
    login = pd.read_sql_query(sql,SQLALCHEMY_DATABASE_URI)
    if login is not None:
        print(login)
        return redirect(url_for('index'))

But the error is the same in both cases, I need to do a relation, so, it is a Migration, in Flask.

   **sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users"**

It is my database.py:

     ...
     SQLALCHEMY_DATABASE_URI = 'postgres://%s:%s@%s:%s/%s' % (user, pwd, host, port, db)
     SQLALCHEMY_TRACK_MODIFICATIONS = os.environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')

     db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=engine))
     def init_db():
     ...


问:
How can I print_r an array from controller while an ajax process?
I am trying to debug my AJAX call to database.

But there is no way to see the data i am using. I have tried to do it inserting some Javascript:

I also tried to use print_r, but nothing happens.

Is there any way to see my variables? A developer tool for example, or any command i could use.

Thanks for your help.

```<code>function console_log( $data ){
    echo '<script>';
    echo 'console.log('. json_encode( $data ) .')';
    echo '</script>';
}
</code>```

This is my controller code:

```<code>public function searchEvents(){
        $request = Request::createFromGlobals();
        if($request->getMethod()=='POST') {
            $value = $request->request->get('searchBox');
            $em=$this->getDoctrine()->getManager();
            $searchFor = $request->request->get('value');
            $qb = $em->createQueryBuilder();
            //$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
            $query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
            $query->setParameter('value', '%'.$searchFor.'%');
            $eventos = $query->getResult();
            /*$qb->select('u')
                ->from('App:Evento','u')
                ->where(('u.title = '.$searchFor));
            $query = $qb->getQuery();
            $eventos = $query->getResult();*/
            $response = [];
            foreach($eventos as $evento){
                array_unshift($response,[
                    $evento->getTitle(),
                    $evento->getFecha()
                ]);
                print_r($response);
            }
            $respuesta = new JsonResponse();
            $respuesta->setData(
                array('response'=>'success',
                    'eventos'=>$response)
            );
        }
        return $respuesta;
}
</code>```

And my js code:

```<code>function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: value=2,
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}
</code>```

答:
The way you send your AJAX request is invalid. Change it to:

```<code>function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: {value: 2},
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}
</code>```

This will still not pass searchbox, but hopefully this is enough to figure that out as well. If not, then please add more details.

As about debugging the data, you can always use the good old echo var_dump and see what it puts into your request response in the network tab of dev tools or you can do it the Symfony way, logging it into a file.

Body:
I am trying to debug my AJAX call to database.

But there is no way to see the data i am using. I have tried to do it inserting some Javascript:

I also tried to use print_r, but nothing happens.

Is there any way to see my variables? A developer tool for example, or any command i could use.

Thanks for your help.

function console_log( $data ){
    echo '';
}

This is my controller code:

public function searchEvents(){
        $request = Request::createFromGlobals();
        if($request->getMethod()=='POST') {
            $value = $request->request->get('searchBox');
            $em=$this->getDoctrine()->getManager();
            $searchFor = $request->request->get('value');
            $qb = $em->createQueryBuilder();
            //$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
            $query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
            $query->setParameter('value', '%'.$searchFor.'%');
            $eventos = $query->getResult();
            /*$qb->select('u')
                ->from('App:Evento','u')
                ->where(('u.title = '.$searchFor));
            $query = $qb->getQuery();
            $eventos = $query->getResult();*/
            $response = [];
            foreach($eventos as $evento){
                array_unshift($response,[
                    $evento->getTitle(),
                    $evento->getFecha()
                ]);
                print_r($response);
            }
            $respuesta = new JsonResponse();
            $respuesta->setData(
                array('response'=>'success',
                    'eventos'=>$response)
            );
        }
        return $respuesta;
}

And my js code:

function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: value=2,
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}

Body:
The way you send your AJAX request is invalid. Change it to:

function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: {value: 2},
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}

This will still not pass searchbox, but hopefully this is enough to figure that out as well. If not, then please add more details.

As about debugging the data, you can always use the good old echo var_dump and see what it puts into your request response in the network tab of dev tools or you can do it the Symfony way, logging it into a file.


问:
Extract either two or three words and exclude duplicates and accronyms
I have a group of names worded in a bizarre fashion. Here is a sample:

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

```<code>df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)
</code>```

This is what I'm getting returned

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

To be clear, goal would be to have this:

```<code>Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster
</code>```

data

```<code>df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)
</code>```

答:
Another way :

```<code>sub("(.*?\\s.*?[a-z](?=[A-Z])).*", "\\1", df$name,  perl = TRUE)
#> [1] "Sammy Watkins"        "Buffalo Bills"        "New England Patriots"
#> [4] "Tre'Quan Smith"       "JuJu Smith-Schuster"

sub(".*?\\s.*?[a-z](?=[A-Z])", "", df$name, perl = TRUE)
#> [1] "S. Watkins"        "BUF"               "NE"
#> [4] "T. Smith"          "J. Smith-Schuster"
</code>```

We're splitting between a lower case character and an upper case character, but not before we see a space.

You could also use unglue :

```<code>library(unglue)
unglue_unnest(df, name, "{name1=.*?\\s.*?[a-z]}{name2=[A-Z].*?}")
#>                  name1             name2
#> 1        Sammy Watkins        S. Watkins
#> 2        Buffalo Bills               BUF
#> 3 New England Patriots                NE
#> 4       Tre'Quan Smith          T. Smith
#> 5  JuJu Smith-Schuster J. Smith-Schuster
</code>```

Body:
I have a group of names worded in a bizarre fashion. Here is a sample:

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)

This is what I'm getting returned

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

To be clear, goal would be to have this:

Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster

data

df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)

Body:
Another way :

sub("(.*?\\s.*?[a-z](?=[A-Z])).*", "\\1", df$name,  perl = TRUE)
#> [1] "Sammy Watkins"        "Buffalo Bills"        "New England Patriots"
#> [4] "Tre'Quan Smith"       "JuJu Smith-Schuster"

sub(".*?\\s.*?[a-z](?=[A-Z])", "", df$name, perl = TRUE)
#> [1] "S. Watkins"        "BUF"               "NE"
#> [4] "T. Smith"          "J. Smith-Schuster"

We're splitting between a lower case character and an upper case character, but not before we see a space.

You could also use unglue :

library(unglue)
unglue_unnest(df, name, "{name1=.*?\\s.*?[a-z]}{name2=[A-Z].*?}")
#>                  name1             name2
#> 1        Sammy Watkins        S. Watkins
#> 2        Buffalo Bills               BUF
#> 3 New England Patriots                NE
#> 4       Tre'Quan Smith          T. Smith
#> 5  JuJu Smith-Schuster J. Smith-Schuster