How do I know which arithmetic operations to do?

For example,
$$x = 5(sin y) + 2$$
If I wanted to make $y$ a function of $x$,
$$x = 5(sin y) + 2$$
$$x – 2 = 5(sin y)$$
$$((x – 2)/5) = sin y$$
$$y = sin^{-1}((x – 2)/5)$$
I believe this is the correct answer, but I was wondering why it isn’t this way.

$$x = 5(sin y) + 2$$
$$x/5 = (sin y) + 2$$
$$x/5 – 2 = sin y$$
$$y = sin^{-1}(x/5 – 2)$$

Why is the second equation wrong?

linux – Ubuntu 14.04 poor performance in some operations

Few days ago something just happened, even not sure what. But some operations very slow. Server is virtual.

Disk, Memory, CPU all normal with minimum load. fsck shows no errors.
top, htop, iotop, stress --cpu 8 --io 4 --vm 4 --vm-bytes 2048M --timeout 10s all ok.

I even have no idea what to check else.

For example service slapd start couple days ago taken 2 sec. Now it takes 31 sec.

smbd even can’t be started, timeout I suppose.

SSH login takes 30secs in each step. Password, sudo etc.

What can be checked else?

Logs are clear, like nothing happens

8 – How can I get the Operations Link Field back?

I have a custom entity created in code which displays list in collection route. I decided to use a view to show this collection.

  1. I created a new view of type ‘Product’ (Views shows my custom entity)
  2. I added the fields I need to display
  3. then searched for Operations Links (to add the edit, delete menu)

but it wasn’t showing. I can confirm I’ve used this before in a view of custom entities.

Wat magic do I need to do here?

Pandas and for-loops: vectorizing operations and speeding up a python code

I am trying to understand how to make code works faster by converting for-loops to vectorized operations. As an example I use the following dataframe:

Based on this dataframe I want to create a new dataframe where each value is True or False based on some specific rules:

Data is presented in json format data.json:

(
 {
   "Date": "9/20/2020 8:50",
   "UE": 1,
   "DL": 154
 },
 {
   "Date": "9/20/2020 8:50",
   "UE": 2,
   "DL": 123
 },
 {
   "Date": "9/20/2020 8:50",
   "UE": 3,
   "DL": 132
 },
 {
   "Date": "9/20/2020 8:57",
   "UE": 1,
   "DL": 141
 },
 {
   "Date": "9/20/2020 8:57",
   "UE": 8,
   "DL": 151
 },
 {
   "Date": "9/20/2020 8:57",
   "UE": 2,
   "DL": 155
 },
 {
   "Date": "9/20/2020 9:12",
   "UE": 1,
   "DL": 151
 },
 {
   "Date": "9/20/2020 9:12",
   "UE": 5,
   "DL": 154
 },
 {
   "Date": "9/20/2020 9:12",
   "UE": 3,
   "DL": 144
 },
 {
   "Date": "9/20/2020 9:20",
   "UE": 1,
   "DL": 134
 },
 {
   "Date": "9/20/2020 9:20",
   "UE": 4,
   "DL": 155
 },
 {
   "Date": "9/20/2020 9:20",
   "UE": 3,
   "DL": 153
 }
)

I upload data as the following:

def upload_data(file):
    df = pd.read_json(file)
    df('Date') = pd.to_datetime(df('Date'), format="%Y-%d-%m %H:%M:%S") 
    df('CQI') = np.nan
    return df
df = upload_data('data.json')

Next, I create an additional row. I managed to do it in a vectorized way:

df('CQI') = (df('Date') != df('Date').shift()).cumsum()

Finally I create dataframe with the results:

def create_df_with_reslts(df):
    df_results = pd.DataFrame().reindex_like(df)
    df_results('Results') = np.nan
    return df_results
df_results = create_df_with_reslts(df)

And now I am looking at how to speed up and vectorize a main part of the code

def check_df(df, df_results):

    # check date format
    date_format = '%Y-%m-%d %H:%M:%S'
    for index, row in df.iterrows():
        date_string = row('Date')
        try:
            df_results('Date')(index) = True
        except ValueError:
            df_results('Date')(index) = False    

    # checking that number of UEs is between 1 and 500
    df_results('UE') = np.where((df('UE') >=1) & (df('UE') <=500), True, False)
    
    # finding bordes for CQI's spans
    previous_row = df('Date').astype(str)(0)
    CQI_index = 0
    CQI_list = ()
    for index, row in df.iterrows():
        # for same CQI
        if row('Date') == previous_row:
            CQI_index += 1
            previous_row = row('Date')
        # for next CQI in table
        else:
            CQI_list.append(CQI_index)
            CQI_index = 1
            previous_row = row('Date')
    CQI_list.append(CQI_index)
    
    # checking whether or not borders are correct
    k=0
    for i in range(len(CQI_list)):
        if CQI_list(i) == 6 or CQI_list(i) == 8:
            for j in range(CQI_list(i)):
                df_results('CQI')(j+k) = True     
        else:
            for j in range(CQI_list(i)):
                df_results('CQI')(j+k) = False   
        j=CQI_list(i)
        k=k+j
    
    # Values of DL corresponds to uniform distribution with epsilon 10%
    list_of_columns = ('DL')   
    for n in range(len(list_of_columns)):
        # find the highest number for each CQI (CQI_MAX)
        k=0
        max_list = ()  
        for i in range(len(CQI_list)):
            X = df(list_of_columns(n))(k:k+CQI_list(i)+1)
            max_list.append(X(X == X.max()).iloc(0))
            k=k+CQI_list(i)
        # check that each value in (max_list*10/100, max_list)
        k=0
        for i in range(len(CQI_list)):
            for j in range(CQI_list(i)):
                if float(df(list_of_columns(n))(j+k)) >= float(max_list(i))*90/100 and float(df(list_of_columns(n))(j+k)) <= float(max_list(i)):
                    df_results(list_of_columns(n))(j+k) = True
                else:
                    df_results(list_of_columns(n))(j+k) = False
            j=CQI_list(i)
            k=k+j
            
    # final results for each column
    df_results('Results') = df_results.prod(axis=1).astype(bool)
        
    # return max_list    
    return df_results
%timeit check_df(df, df_results)
# 19.5 ms ± 2.84 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

I changed iteration over dataframe into iteration over iterrows: range(len(df)) into df.iterrows(). It gave only ~20% speedup. Also one for-loop was changed with vectorized operation (np.where). I don’t know how to do the same for other for-loops.
So my question: is it possible to speedup and vectorize other parts of the code?

algorithms – Bitwise And and Bitwise or operations

You are given an integer $V$ with initial value set to $0$. You are also given an array of distinct positive integers $A$ with each $A_i$ less than $ 2 ^{20} $.
You can do the following operation to $V$ any number of times-
$bullet$ Choose any element from $A$ and set $V$ to either $V|{A_i} $ or $ V&{A_i} $.

Our task is to tell how many distinct values $V$ can take after applying some amount of operations to $V$ (possibly zero).

I tried this using recursion but failed to come up with any optimised approach. Kindly suggest some optimised approach.

algorithm – how to solve operations in txt file c++?

I got a file that named “Input.inp” and it will be opened with filestream and it will be read. Then operations will be done. But i dont know how to do it. E.g.

[Input.inp] File includes;

A = 5
B = 7
C = A*B
OUT C

I know all the other operations about filestream or anything else, just wondering how to make it done in txt file. How to make it solve?

How to configure view to carryout two operations from GET request Django

I’m trying to build a wish list for my website. So I created a view that will

  1. render out the wish list and to
  2. add items to the wish list – using ajax

Those two tasks are carried out by the same view. Here’s how I did it,

views.py

@login_required(login_url='/login')
def wishlist(request):

    wishes = Wishlist.objects.filter(customer=request.user.customer).prefetch_related(
        Prefetch('product',
                 queryset=Product.objects.prefetch_related(
                     Prefetch(
                         'productimage_set',
                         ProductImage.objects.filter(place='Main Product Image'),
                         to_attr='main_image'
                        ),
                 ),
                 to_attr='wished_dish'
        ),
    )

    # delete wished dish
    if request.method == 'POST':
        dish_to_delete = request.POST.getlist('delete_items')
        print(dish_to_delete)

        Wishlist.objects.filter(pk__in=dish_to_delete).delete()

# question is related to below statements 

    if request.method == 'GET':
        try:
            dish_id = request.GET('dish_id')

            dish = Product.objects.get(id=dish_id)

            wish, created = Wishlist.objects.get_or_create(
                customer=request.user.customer,
                product=dish
            )

            if created:
                return HttpResponse('Dish <b>{}</b> Added to wish list!'.format(dish.name))
            else:
                return HttpResponse('Dish <b>{}</b> is already in your wish list!'.format(dish.name))
        except:
            pass


    context = {
        'wishes': wishes,
    }

    return render(request, 'store/wishlist.html', context)

As you can see I’ve used a try:... except: pass block for GET requests to separate the adding functionality and viewing functionality.

It works fine but is this the optimal way to achieve the intended goal?

Freeze when io operations after SSD replacement

I upgraded my NVMe SSD from a PC300 SK Hynix 512G to a Kingston SA2000 1T in my Dell XPS 15.
I used Clonezilla to clone the disk and then GParted to resize/move partitions. Everything went smoothly without error.

But now, on Ubuntu 20.04, I have freezes when doing heavier IO operations (Android app compilation, writing multiple files via scripts, sometimes opening Chrome,…).

I don’t see anything in /var/log/syslog or in /var/log/kern.log corresponding to the freezes but the system is completely stuck: I cannot ctrl-C in the terminal or start anything. Also, icons disappear progressively from menus (as it tries to load them ?).

On Windows 10, I have no issue while gaming, so I presume it’s related to Ubuntu but cannot really prove it.

I tried a check disk, it didn’t report anything, the only thing reported was “inode extent tree (at level 1) could be shorter” which I corrected.
smartctl doesn’t show any error:

smartctl 7.1 2019-12-30 r5022 (x86_64-linux-5.4.0-58-generic) (local build)
Copyright (C) 2002-19, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Model Number:                       KINGSTON SA2000M81000G
Serial Number:                      50026B76842D46F8
Firmware Version:                   S5Z42105
PCI Vendor/Subsystem ID:            0x2646
IEEE OUI Identifier:                0x0026b7
Controller ID:                      1
Number of Namespaces:               1
Namespace 1 Size/Capacity:          1,000,204,886,016 (1.00 TB)
Namespace 1 Utilization:            782,120,886,272 (782 GB)
Namespace 1 Formatted LBA Size:     512
Namespace 1 IEEE EUI-64:            0026b7 6842d46f85
Local Time is:                      Tue Dec 29 11:57:29 2020 CET
Firmware Updates (0x14):            2 Slots, no Reset required
Optional Admin Commands (0x0017):   Security Format Frmw_DL Self_Test
Optional NVM Commands (0x005f):     Comp Wr_Unc DS_Mngmt Wr_Zero Sav/Sel_Feat Timestmp
Maximum Data Transfer Size:         32 Pages
Warning  Comp. Temp. Threshold:     75 Celsius
Critical Comp. Temp. Threshold:     80 Celsius

Supported Power States
St Op     Max   Active     Idle   RL RT WL WT  Ent_Lat  Ex_Lat
 0 +     9.00W       -        -    0  0  0  0        0       0
 1 +     4.60W       -        -    1  1  1  1        0       0
 2 +     3.80W       -        -    2  2  2  2        0       0
 3 -   0.0450W       -        -    3  3  3  3     2000    2000
 4 -   0.0040W       -        -    4  4  4  4    15000   15000

Supported LBA Sizes (NSID 0x1)
Id Fmt  Data  Metadt  Rel_Perf
 0 +     512       0         0

=== START OF SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

SMART/Health Information (NVMe Log 0x02)
Critical Warning:                   0x00
Temperature:                        25 Celsius
Available Spare:                    100%
Available Spare Threshold:          10%
Percentage Used:                    0%
Data Units Read:                    911,056 (466 GB)
Data Units Written:                 1,455,569 (745 GB)
Host Read Commands:                 13,570,300
Host Write Commands:                12,412,188
Controller Busy Time:               104
Power Cycles:                       35
Power On Hours:                     23
Unsafe Shutdowns:                   16
Media and Data Integrity Errors:    0
Error Information Log Entries:      0
Warning  Comp. Temperature Time:    0
Critical Comp. Temperature Time:    0
Thermal Temp. 1 Transition Count:   41
Thermal Temp. 1 Total Time:         837

Error Information (NVMe Log 0x01, max 256 entries)
No Errors Logged

My system is up to date on Linux gp2mv3-laptop 5.4.0-58-generic #64-Ubuntu SMP Wed Dec 9 08:16:25 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux.

What can I do to correct this issue? Is there an incompatibility issue with Ubuntu?

Thanks a lot!

node.js – Tiny REST API for making CRUD operations on list of posts

This is not a question related to a bug.I’ve just created a very tiny node.js/express API for education purposes.
I’ve created a very little API and what i would like is to have your point of view about the design and projet architecture and what you would recommand be as advice in term of what i can improve in this code.

As it’s open sources you’re also welcome for pull requests.

Notice : I’ve not considered aspects like logging,ORM's or specific packages for validation or these kind of things.

Here is the github repo where i explain cleary how to run the project in the local computer.

https://github.com/jochri3/tiny-express-api

My code organization is in a MVC pattern:

|controllers
    -posts.js
|middlewares
    -bodyValidation.js
    -postExists.js
|models
    -post.js
|startups
    -db.js
    -routes.js
app.js
router.js

Here is the codes content:

controllers/posts.js

const Post=require('../models/post');

const index=async(req,res)=>{
    const posts=await Post.getAll();
    res.send({data:posts})
}

// const show=(req,res)=>{
    
// }

const create=async({body},res)=>{
    await Post.create(body);
    res.status(201).send({message:'post created successfully'});
}

const update=async({body,params:{id}},res)=>{
    await Post.update(id,body)
    res.status(201).send({message:'posts updated successfully'});
}

const destroy=async({params:{id}},res)=>{
    await Post.delete(id);
     res.status(202).send({message:'post deleted successfully'})
}

module.exports={
    index,
    // show,
    create,
    update,
    destroy
}

middlewares/bodyValidate

module.exports=async({body},res,next)=>{
    const bodyValues=Object.values(body);
    if(bodyValues.some(value=>!value)){
        return res.status(422).send({message:'Veuillez remplir tous les champs correctement'})
    }
    next();
}

middlewares/postExists.js

const connection=require("../startups/db")

module.exports=async(req,res,next)=>{
    const {params:{id}}=req;
    if(!id){
        return res.status(404).send({message:'not found'})
    }
    const post=await connection.select().from('posts').where('id',id);
    if(!post.length){
        return res.status(404).send({message:'not found'})
    }
    req.post=post;
    next();
}

models/post.js

const connection=require("../startups/db");

class Post{
    
    static getAll(){
        return connection.select().from("posts");
    }

    static update(id,data){
        return connection('posts').where('id',id).update(data);
    }

    // static getOne(id){

    // }

    static delete(id){
        return connection('posts').where('id', id).del();
    }

    static create(data){
        return connection('posts').insert(data);
    }
}

module.exports=Post;

startups/db.js

const knex=require("knex");


module.exports=knex({
    client: 'sqlite3',
  connection: {
    filename: "./db.sqlite"
  }
})

startups/routes.js

const express=require('express');
const {postsRouter}=require('../router')

module.exports=(app)=>{
    app.use(express.json())
    app.use('/api/posts',postsRouter)
}

app.js

const express=require("express");
const connection=require("./startups/db");

const app=express();

require('./startups/routes')(app,connection)

require('express-async-errors');

const port=8000

app.listen(port,()=>{
    console.info(`Server in listening on port ${port}`)
})

router.js

const express=require('express');

//custom middlewares
const idExists=require("./middlewares/postsExists");
const bodyValidates=require("./middlewares/bodyValidate");

const PostsController=require("./controllers/posts")


const postsRouter=express.Router();


postsRouter.get('/',PostsController.index);

postsRouter.get('/:id',(idExists),async(req,res)=>{
        res.send({data:req.post(0)});
    });

postsRouter.post('/',(bodyValidates),PostsController.create)

postsRouter.put('/:id',(idExists,bodyValidates),PostsController.update)

postsRouter.delete('/:id',(idExists),PostsController.destroy)

module.exports={
    postsRouter
}

You can view the project in codesandbox : https://codesandbox.io/s/angry-montalcini-vsbfb

Does SQL Server optimize two “>” operations on same column

Can SQL Server optimize the following:

DECLARE @id INT;
DECLARE @d1 DATE;
SELECT a, b
FROM t
WHERE id_column = @id
AND date_column >= CAST(CURRENT_TIMESTAMP AS DATE)
AND date_column >= @d1

Notice that there are two > operators on the same column. Assuming that today is 2020-12-23 and d1 could be either 2020-12-20 or 2020-12-27, I was hoping that SQL Server would automatically use greater of the two dates… 2020-12-23 in the first case and 2020-12-27 in the latter. But I am not sure.