问:
How to use react-router-bootstrap LinkContainer?
I am using react-router-dom , react-router-bootstrap and react-bootstrap. In Navbar of react-bootstrap LinkContainer is not working. I have use below code.

```<code>import React from 'react';
import { LinkContainer } from 'react-router-bootstrap';
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';

const Header = () => {
  return (
<header>
    <Navbar bg="dark" variant='dark' expand="lg" collapseOnSelect>
          <Container>
              <LinkContainer to="/">
                    <Navbar.Brand>ProShop</Navbar.Brand>
              </LinkContainer>
            <Navbar.Toggle aria-controls="basic-navbar-nav" />
            <Navbar.Collapse id="basic-navbar-nav">
                <Nav className="justify-content-end"  style={{ width: "100%" }}>
                    <LinkContainer to="/cart">
                        <Nav.Link><i className='fas fa-shopping-cart'></i> Cart</Nav.Link>
                    </LinkContainer>
                    <LinkContainer to="/cart">
                        <Nav.Link href="/login"><i className='fas fa-sign-in'></i> Login</Nav.Link>
                    </LinkContainer>
                </Nav>
            </Navbar.Collapse>
        </Container>
    </Navbar>
</header>
)
}

export default Header
</code>```

When I check it in browser I got empty screen and below error.

```<code>Uncaught Error: useNavigate() may be used only in the context of a <Router> component.
at invariant (history.ts:460:1)
at useNavigate (hooks.tsx:158:1)
at LinkContainer (LinkContainer.js:48:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)

The above error occurred in the <LinkContainer> component:
at LinkContainer (http://localhost:3000/static/js/bundle.js:43940:23)
at div
at http://localhost:3000/static/js/bundle.js:15844:5
at nav
at http://localhost:3000/static/js/bundle.js:16187:70
at header
at Header
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
</code>```

If I remove LinkContainer and use default href then it work fine but when we click on link it refresh page.

Body:
I am using react-router-dom , react-router-bootstrap and react-bootstrap. In Navbar of react-bootstrap LinkContainer is not working. I have use below code.

import React from 'react';
import { LinkContainer } from 'react-router-bootstrap';
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';

const Header = () => {
  return (

    <Navbar bg="dark" variant='dark' expand="lg" collapseOnSelect>
          <Container>
              <LinkContainer to="/">
                    <Navbar.Brand>ProShop</Navbar.Brand>
              </LinkContainer>
            <Navbar.Toggle aria-controls="basic-navbar-nav" />
            <Navbar.Collapse id="basic-navbar-nav">

                    <LinkContainer to="/cart">
                         Cart
                    </LinkContainer>
                    <LinkContainer to="/cart">
                         Login
                    </LinkContainer>

            </Navbar.Collapse>
        </Container>
    </Navbar>

)
}

export default Header

When I check it in browser I got empty screen and below error.

Uncaught Error: useNavigate() may be used only in the context of a <Router> component.
at invariant (history.ts:460:1)
at useNavigate (hooks.tsx:158:1)
at LinkContainer (LinkContainer.js:48:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)

The above error occurred in the <LinkContainer> component:
at LinkContainer (http://localhost:3000/static/js/bundle.js:43940:23)
at div
at http://localhost:3000/static/js/bundle.js:15844:5
at nav
at http://localhost:3000/static/js/bundle.js:16187:70
at header
at Header
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

If I remove LinkContainer and use default href then it work fine but when we click on link it refresh page.


来源: stackexchange

问:
Two day's pivot values getting wrong
I am trying to create a simple indicator that predicts the day's trend by using the previous 2 day's pivot points.

I just want to label the day's first candle bullish if the pivot point value is greater than yesterday's pivot value and vice versa.

It looks very simple. But I am getting the wrong pivot values when I display the pivot values which are compared to the traditional pivot points indicator.

Here is the code.

```<code>
pivotYesterday = math.round(((high[2] + low[2] + close[2])/3),2)
pivotToday = math.round((high[1] + low[1] + close[1])/3,2)

if (hour(time)==09 and minute(time)==15 and pivotToday > pivotYesterday)
    label.new(bar_index, high, "Bullish")

else if(hour(time)==09 and minute(time)==15 and pivotToday < pivotYesterday)
    label.new(bar_index, high, "Bearish")

</code>```

Thank you.

ContentLicense: CC BY-SA 4.0

Title: Two day's pivot values getting wrong

Body:
I am trying to create a simple indicator that predicts the day's trend by using the previous 2 day's pivot points.

I just want to label the day's first candle bullish if the pivot point value is greater than yesterday's pivot value and vice versa.

It looks very simple. But I am getting the wrong pivot values when I display the pivot values which are compared to the traditional pivot points indicator.

Here is the code.

pivotYesterday = math.round(((high[2] + low[2] + close[2])/3),2)
pivotToday = math.round((high[1] + low[1] + close[1])/3,2)

if (hour(time)==09 and minute(time)==15 and pivotToday > pivotYesterday)
    label.new(bar_index, high, "Bullish")

else if(hour(time)==09 and minute(time)==15 and pivotToday < pivotYesterday)
    label.new(bar_index, high, "Bearish")

Thank you.


问:
Axios with basic auth
I have this function:

```<code>const axios = require('axios');
const https = require('https');

exports.apiRequest = async ({url, method = "GET", body}) => {

    const URL = process.env.APP_API_URL + url;
    const USER = process.env.APP_API_USER;
    const PASS = process.env.APP_API_PASSWORD;

    const httpsAgent = new https.Agent({
        rejectUnauthorized: false,
      });

    try {
        const config = {
            method: method,
            url: URL,
            auth: {
                username: USER,
                password: PASS
            },
            body: body,
            httpsAgent: httpsAgent
        }

        let res = await axios(config);
        //console.log(res);
        return res.data;

    } catch (error) {
        console.log("Error: ", error);
    }
}
</code>```

so I call it:

```<code>const { apiRequest } = require('./api/petition.controller');
const { urlEvents,
        getEventsFilterDate } = require('../utils/events/api/apiRoutes');

// GET Events
exports.getEvents = async (req, res) => {
    const data = await petition({
        url: urlEvents.getEvents,
        method: 'GET',
        body: {}
    });
    console.log("DATA:  ", data);
    return data;
}
</code>```

currently I'm getting nothing, I test witn postman the URL with basic auth and work, but with node js and axios didn't work, what's wrong??

the function apiRequest  is the component, I just want to structure for method get, post, put and delete.

Title: Axios with basic auth

Body:
I have this function:

const axios = require('axios');
const https = require('https');

exports.apiRequest = async ({url, method = "GET", body}) => {

    const URL = process.env.APP_API_URL + url;
    const USER = process.env.APP_API_USER;
    const PASS = process.env.APP_API_PASSWORD;

    const httpsAgent = new https.Agent({
        rejectUnauthorized: false,
      });

    try {
        const config = {
            method: method,
            url: URL,
            auth: {
                username: USER,
                password: PASS
            },
            body: body,
            httpsAgent: httpsAgent
        }

        let res = await axios(config);
        //console.log(res);
        return res.data;

    } catch (error) {
        console.log("Error: ", error);
    }
}

so I call it:

const { apiRequest } = require('./api/petition.controller');
const { urlEvents,
        getEventsFilterDate } = require('../utils/events/api/apiRoutes');

// GET Events
exports.getEvents = async (req, res) => {
    const data = await petition({
        url: urlEvents.getEvents,
        method: 'GET',
        body: {}
    });
    console.log("DATA:  ", data);
    return data;
}

currently I'm getting nothing, I test witn postman the URL with basic auth and work, but with node js and axios didn't work, what's wrong??

the function apiRequest  is the component, I just want to structure for method get, post, put and delete.


问:
React Saga - Creating own API without using axios -
My task is to create an array in saga and pass that as drop-down options in drop-down menu which is in other component.
In drop-down component I've to access those data from saga. In my application drop-down is in another component and saga is in another component.

So, I've to create an array in saga and create an API and pass it as dropdown options in otjer component


问:
How does these assignments work with object step by step?
Very interesting question from the interview. What is the output of the code below?

var obj1 = { n: 1 };
var obj2 = obj1;

obj1.x = obj1 = { n: 2 };

console.log(obj1.x);
console.log(obj2.x);
```
<p>Output is:</p>
<pre class="lang-js prettyprint-override"><code>undefined
{ n: 2 }
</code>```

But I was expecting this:

{ n: 2 }
undefined
```

since after obj1 = { n: 2 }, a pointer to this brand new object was saved, and next obj1.x = obj1 interacts with a new pointer, not old.

I would be very thankful if you can explain how does it actually works step by step.

Body:
Very interesting question from the interview. What is the output of the code below?

var obj1 = { n: 1 };
var obj2 = obj1;

obj1.x = obj1 = { n: 2 };

console.log(obj1.x);
console.log(obj2.x);

Output is:

undefined
{ n: 2 }

But I was expecting this:

{ n: 2 }
undefined

since after obj1 = { n: 2 }, a pointer to this brand new object was saved, and next obj1.x = obj1 interacts with a new pointer, not old.

I would be very thankful if you can explain how does it actually works step by step.


问:
Chrome alarms does not fire in my chrome extension
I am trying to print some value in console, just to check whether the alarm is working or not, but the alarm  does not fire and it doesn't print anything in console, is there anything which is missing?, Here is background.js file

`

```<code>// Running a code after every 1 minutes starts

chrome.alarms.create('Health Api Alarm', {
  periodInMinutes: 1,
});

console.log('In background.js');

chrome.alarms.getAll(function (alarms) {
  console.log('All alarms', alarms);
});

chrome.alarms.onAlarm.addListener(function (alarm) {
  console.log('Inside alarm function');
  if (alarm.name === 'Health Api Alarm') {
    let time = new Date().toLocaleTimeString();
    console.log('The current time is ' + time);
  }
});

// Running a code after every 1 minutes ends
</code>```

`

I tried to print the current time after every one minute, but the alarm did not fired.

Body:
I am trying to print some value in console, just to check whether the alarm is working or not, but the alarm  does not fire and it doesn't print anything in console, is there anything which is missing?, Here is background.js file

`

// Running a code after every 1 minutes starts

chrome.alarms.create('Health Api Alarm', {
  periodInMinutes: 1,
});

console.log('In background.js');

chrome.alarms.getAll(function (alarms) {
  console.log('All alarms', alarms);
});

chrome.alarms.onAlarm.addListener(function (alarm) {
  console.log('Inside alarm function');
  if (alarm.name === 'Health Api Alarm') {
    let time = new Date().toLocaleTimeString();
    console.log('The current time is ' + time);
  }
});

// Running a code after every 1 minutes ends

`

I tried to print the current time after every one minute, but the alarm did not fired.


问:
React18 throws invalid hooks error and BrowserRouter error while using react-router-dom
I am using React v18 and installed few packages react-router-dom react-social-login

App.js

import React from 'react';
import Home from './container/Home';
import Login from './components/Login';

import { Route, Routes} from "react-router-dom";

const App = () => {
        return(
                <Routes>
                    <Route path='/' element={<Home />} />
                    <Route path='/login' element={<Login />} />
                </Routes>
        );
}

export default App;
```
<p>Login.js</p>
<pre class="lang-js prettyprint-override"><code>import React from 'react'

const Login = () => {
  return (
    <div>
      <h1>Login</h1>
    </div>
  );
}

export default Login;
</code>```

Home.js

import React from 'react'

const Home = () => {
  return (

Home

  )
}

export default Home;
```
<p>console error I got this error while running the following program. The output Home and Login is not returned.
console error</p>
<p>Index.js</p>
<pre class="lang-js prettyprint-override"><code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import  App from './App';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
        <App />
    </BrowserRouter>
  </React.StrictMode>
);
</code>```

Body:
I am using React v18 and installed few packages react-router-dom react-social-login

App.js

import React from 'react';
import Home from './container/Home';
import Login from './components/Login';

import { Route, Routes} from "react-router-dom";

const App = () => {
        return(
                <Routes>
                    <Route path='/' element={<Home />} />
                    <Route path='/login' element={<Login />} />
                </Routes>
        );
}

export default App;

Login.js

import React from 'react'

const Login = () => {
  return (

Login

  );
}

export default Login;

Home.js

import React from 'react'

const Home = () => {
  return (

Home

  )
}

export default Home;

console error I got this error while running the following program. The output Home and Login is not returned.
console error

Index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import  App from './App';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
        <App />
    </BrowserRouter>
  </React.StrictMode>
);


问:
Detach a specified detail in csv using Pandas or something else
I'm new to python, I use pandas to read log files in cvs format and the information I want to use is all in the raw column. Is there any way for me use pandas or something else to detach information such as "timestamp", "src_ip", "proto",... into separate columns or a new sheet ?

Raw column:

```<code>{"timestamp":"2022-12-05T21:12:45.189212+0700","flow_id":12004372636444,"in_iface":"em0","event_type":"dns","src_ip":"192.168.x.xx","src_port":56490,"dest_ip":"8.8.8.8","dest_port":53,"proto":"UDP","dns":{"type":"query","id":48818,"rrname":"e123456.api.splkmobile.com","rrtype":"AAAA","tx_id":0}}
</code>```

I have searched for this problem on the internet but there is no solution, asking here is the last solution

Body:
I'm new to python, I use pandas to read log files in cvs format and the information I want to use is all in the raw column. Is there any way for me use pandas or something else to detach information such as "timestamp", "src_ip", "proto",... into separate columns or a new sheet ?

Raw column:

{"timestamp":"2022-12-05T21:12:45.189212+0700","flow_id":12004372636444,"in_iface":"em0","event_type":"dns","src_ip":"192.168.x.xx","src_port":56490,"dest_ip":"8.8.8.8","dest_port":53,"proto":"UDP","dns":{"type":"query","id":48818,"rrname":"e123456.api.splkmobile.com","rrtype":"AAAA","tx_id":0}}

I have searched for this problem on the internet but there is no solution, asking here is the last solution


问:
Node.js - how to find ethernet key on different operation system using "os" module or a npm package
I am working with a service in node.js that communicate with different machines.
Each machine should have a unique identifier when the service emit an event to the main server, so we need to use the mac address of ethernet interface.
I am kind of new to the "os module", but there is a  build in method for that:

```<code>const os = require('os');
os.networkInterfaces();
</code>```

I searched for it a lot but I am not quite sure about the names:
when we log  os.networkInterfaces() it gives an object with keys as interface name and values as an array of interfaces info- generally for ipv4 & ipv6.
In linux the name of the ethernet interface should start with: "eth",
in mac: "en", in windows it called "Ethernet" or sometimes: "vEthernet (WSL)",
for example:

```<code>platform:  win32
os.networkInterfaces():  {
  'Ethernet 5': [
    {
      address: 'fe80::dd29:8ae9:2050:2de8',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: 'xx:xx:xx:xx:xx:xx',
      internal: false,
      cidr: 'fe80::dd29:8ae9:2050:2de8/64',
      scopeid: 18
    },
    {
      address: '10.212.134.202',
      netmask: '255.255.255.255',
      family: 'IPv4',
      mac: 'xx:xx:xx:xx:xx:xx',
      internal: false,
      cidr: '10.212.134.202/32'
    }
  ],
</code>```

In general, I can do something like:

```<code>const interfaces = os.networkInterfaces();
let my_mac_address;
    if(os.platform()==='win32') {
      my_mac_address = interfaces['Ethernet 5'].filter(i => i.family === 'IPv4').mac;
    }
</code>```

but is there a clear rule about the names in each os? for example in win it will always include or start with: "Ethernet " etc - if so, I can write a function that search for a value with a given partial key
(something like: how to get value from object with a partial index value javascript).

The reason for this is that those machines are in production and I do not have an access to check the ethernets connections names..
In addition, this method does not show any interfaces which do not have a connection since boot. Meaning if I have several interfaces, say eth0, eth1 where only eth0 has ever been connected. This method will only show eth0 and not eth1.
There are also virtual interfaces which I dont understand the difference between them and the regular.

So how can I be sure that I am taking the proper ethernet interface mac address?

I can also use a npm package: node-macaddress.
According their docs it: "Retrieves the MAC address of the given iface.
If iface is omitted, this function automatically chooses an appropriate device (e.g. eth0 in Linux, en0 in OS X, etc.)."

"This library allows to discover the MAC address per network interface and chooses an appropriate interface if all you're interested in is one MAC address identifying the host system (see API + Examples below)"

But our preference is to work with the build in modules of node and do not install a package since every machine is running with different node version and things might break when we run build.

thanks for any help!

Body:
I am working with a service in node.js that communicate with different machines.
Each machine should have a unique identifier when the service emit an event to the main server, so we need to use the mac address of ethernet interface.
I am kind of new to the "os module", but there is a  build in method for that:

const os = require('os');
os.networkInterfaces();

I searched for it a lot but I am not quite sure about the names:
when we log  os.networkInterfaces() it gives an object with keys as interface name and values as an array of interfaces info- generally for ipv4 & ipv6.
In linux the name of the ethernet interface should start with: "eth",
in mac: "en", in windows it called "Ethernet" or sometimes: "vEthernet (WSL)",
for example:

platform:  win32
os.networkInterfaces():  {
  'Ethernet 5': [
    {
      address: 'fe80::dd29:8ae9:2050:2de8',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: 'xx:xx:xx:xx:xx:xx',
      internal: false,
      cidr: 'fe80::dd29:8ae9:2050:2de8/64',
      scopeid: 18
    },
    {
      address: '10.212.134.202',
      netmask: '255.255.255.255',
      family: 'IPv4',
      mac: 'xx:xx:xx:xx:xx:xx',
      internal: false,
      cidr: '10.212.134.202/32'
    }
  ],

In general, I can do something like:

const interfaces = os.networkInterfaces();
let my_mac_address;
    if(os.platform()==='win32') {
      my_mac_address = interfaces['Ethernet 5'].filter(i => i.family === 'IPv4').mac;
    }

but is there a clear rule about the names in each os? for example in win it will always include or start with: "Ethernet " etc - if so, I can write a function that search for a value with a given partial key
(something like: how to get value from object with a partial index value javascript).

The reason for this is that those machines are in production and I do not have an access to check the ethernets connections names..
In addition, this method does not show any interfaces which do not have a connection since boot. Meaning if I have several interfaces, say eth0, eth1 where only eth0 has ever been connected. This method will only show eth0 and not eth1.
There are also virtual interfaces which I dont understand the difference between them and the regular.

So how can I be sure that I am taking the proper ethernet interface mac address?

I can also use a npm package: node-macaddress.
According their docs it: "Retrieves the MAC address of the given iface.
If iface is omitted, this function automatically chooses an appropriate device (e.g. eth0 in Linux, en0 in OS X, etc.)."

"This library allows to discover the MAC address per network interface and chooses an appropriate interface if all you're interested in is one MAC address identifying the host system (see API + Examples below)"

But our preference is to work with the build in modules of node and do not install a package since every machine is running with different node version and things might break when we run build.

thanks for any help!


问:
Order slider for animation with plotly
I am trying to create an animation for my line chart. The idea is to make the lines appear with a dot on the last value that appeared for each line.

I have 2 problems:

First, the slider is not ordered as my dataframe. I want the rounds to appear from 1 to the last one.

Besides, I would like to make the previous dots disappear once the next one appears.

Here you have my code:

```<code>data = data[order(data$round),]
prep = data[data$year == 2021,] %>% split(.$round) %>% accumulate(., ~bind_rows(.x,.y))%>%
  bind_rows(.id = "frame")
prep%>%
  plot_ly(x = ~round, y = ~points, color = ~factor(name)) %>%
  add_lines(frame = ~frame)%>%
  add_markers(frame = ~frame)
</code>```

And how it is appearing (you can see the order of the slider and the dots all over the chart):

I tried to reorder it as you can see in data = data[order(data$round),] and that did not work.

Title: Order slider for animation with plotly

Body:
I am trying to create an animation for my line chart. The idea is to make the lines appear with a dot on the last value that appeared for each line.

I have 2 problems:

First, the slider is not ordered as my dataframe. I want the rounds to appear from 1 to the last one.

Besides, I would like to make the previous dots disappear once the next one appears.

Here you have my code:

data = data[order(data$round),]
prep = data[data$year == 2021,] %>% split(.$round) %>% accumulate(., ~bind_rows(.x,.y))%>%
  bind_rows(.id = "frame")
prep%>%
  plot_ly(x = ~round, y = ~points, color = ~factor(name)) %>%
  add_lines(frame = ~frame)%>%
  add_markers(frame = ~frame)

And how it is appearing (you can see the order of the slider and the dots all over the chart):

I tried to reorder it as you can see in data = data[order(data$round),] and that did not work.


问:
chaining call and bind with slice() to convert array-like objects to arrays
Mdn has been updating their docs and while I was looking through the documentation for slice I came across the below piece of code.

I understand call, bind and apply but I am having a hard time understanding the chaining of call and bind used together. Bind creates a new function and call invokes a function right away so what is going on here?

According to mdn's docs:

The slice() method is often used with bind() and call() to create a utility method that converts an array-like object into an array.

// slice() is called with `this` passed as the first argument
const slice = Function.prototype.call.bind(Array.prototype.slice);

function list() {
  return slice(arguments);
}

const list1 = list(1, 2, 3);
```


问:
File Uploads - Form submitted without saving file?
I'm trying to upload a file and save it to the server, the types of files will be documents, mostly doc/docx or Pages' file

Why isn't the file being saved for the model Grade, and the attribute Answer?

Here's my Schema.rb file

```<code>ActiveRecord::Schema.define(:version => 20110920230706) do

  create_table "assignments", :force => true do |t|
    t.string   "name"
    t.string   "instructions"
    t.date     "due"
    t.integer  "scribd_id"
    t.decimal  "score"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.binary   "handout"
  end

  create_table "grades", :force => true do |t|
    t.integer  "assignment_id"
    t.integer  "user_id"
    t.integer  "scribd_id"
    t.decimal  "score"
    t.text     "note"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "answer_file_name"
    t.string   "answer_content_type"
    t.integer  "answer_file_size"
    t.datetime "answer_updated_at"
  end

  create_table "users", :force => true do |t|
    t.string   "email",                                 :default => "", :null => false
    t.string   "encrypted_password",     :limit => 128, :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",                         :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

end
</code>```

Grade.rb

```<code>class Grade < ActiveRecord::Base
  belongs_to :assignment

  has_attached_file :answer

end
</code>```

Show.html.erb

```<code><%= stylesheet_link_tag "assignments" %>
<p id="notice"><%= notice %></p>
<div class="show">
  <h2 id="title"><%= @assignment.name %></h2>
  <div id="directions_container">
    <h3>Directions - <div id="directions"><%= @assignment.instructions %></div> </h3>

    <div class="turn_in_container">
    <div class="turn_in_box prepare_for_turn_in" id="turn_in_box">
        <div id="label">
          <h4 id="turn_in_assignment">Turn In Assignment</h4>
          <h6 id="drag">(You can just drag it in here)</h6>
        </div>
      </div>
  <%= form_for @grade, :html => { :multipart => true, :id => "form"} do |f| %>
    <%= f.file_field :answer, :id => "file" %>
  <% end %>
  </div>
</div>
</code>```

assignments.js.coffee

```<code>$(document).ready ->
  $("#file").mouseenter ->
    $("#turn_in_box").css "border", "2px solid #D9D9D9"
    $("#turn_in_box").css "background", "#D9D9D9"
    $("#turn_in_box").css "color", "#393939"
    $("#turn_in_box").css "cursor", "pointer"
    $("#turn_in_box").css "box-shadow" ,"0px 0px 0px transparent"

  $("#file").mouseleave ->
    $("#turn_in_box").css "border", "2px solid #D9D9D9"
    $("#turn_in_box").css "background", "#393939"
    $("#turn_in_box").css "color", "#D9D9D9"
    $("#turn_in_box").css "cursor", "default"
  $("#file").bind 'dragover', (evt) ->
    evt.stopPropagation()
    evt.preventDefault()
  $("#file").bind 'drop', ->
    $("#drag").css "display", "none"
    $("#turn_in_assignment").text "Turning In Assignment..."
    $("#form").submit()
</code>```

development.log

```<code>Started GET "/assignments/2" for 127.0.0.1 at 2011-09-20 16:08:38 -0700
  Processing by AssignmentsController#show as HTML
  Parameters: {"id"=>"2"}
  ←[1m←[36mUser Load (0.0ms)←[0m  ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1←[0m
  ←[1m←[35mAssignment Load (0.0ms)←[0m  SELECT "assignments".* FROM "assignments" WHERE "assignments"."id" = ? LIMIT 1
  ←[1m←[36mGrade Load (0.0ms)←[0m  ←[1mSELECT "grades".* FROM "grades" WHERE "grades"."assignment_id" = 2 AND "grades".
Rendered assignments/show.html.erb within layouts/application (50.0ms)
Completed 200 OK in 183ms (Views: 132.0ms | ActiveRecord: 1.0ms)

Started GET "/assets/assignments.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.css - 304 Not Modified (0ms)

Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /jquery.js - 304 Not Modified (1ms)

Started GET "/assets/grades.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /grades.css - 304 Not Modified (0ms)

Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /application.css - 304 Not Modified (0ms)

Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /jquery_ujs.js - 304 Not Modified (0ms)

Started GET "/assets/assignments.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.js - 304 Not Modified (1ms)

Started GET "/assets/assignments.js.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.js.js - 304 Not Modified (0ms)

Started GET "/assets/grades.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /grades.js - 304 Not Modified (0ms)

Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /application.js - 304 Not Modified (0ms)

Started PUT "/grades/2" for 127.0.0.1 at 2011-09-20 16:08:47 -0700
  Processing by GradesController#update as HTML
  Parameters: {"utf8"=>"Γ£ô", "authenticity_token"=>"/MpatBt5HIrsYPF0PKeyhfsQjY+Z1yDXMRtZjW+fHA8=", "id"=>"2"}
  ←[1m←[35mGrade Load (0.0ms)←[0m  SELECT "grades".* FROM "grades" WHERE "grades"."id" = ? LIMIT 1  [["id", "2"]]
[paperclip] Saving attachments.
Redirected to http://localhost:3000/grades/2
Completed 302 Found in 51ms

Started GET "/grades/2" for 127.0.0.1 at 2011-09-20 16:08:47 -0700
  Processing by GradesController#show as HTML
  Parameters: {"id"=>"2"}
  ←[1m←[36mGrade Load (1.0ms)←[0m  ←[1mSELECT "grades".* FROM "grades" WHERE "grades"."id" = ? LIMIT 1←[0m  [["id", "2"
Rendered grades/show.html.erb within layouts/application (11.0ms)
Completed 200 OK in 28ms (Views: 25.0ms | ActiveRecord: 1.0ms)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to upload a file and save it to the server, the types of files will be documents, mostly doc/docx or Pages' file

Why isn't the file being saved for the model Grade, and the attribute Answer?

Here's my Schema.rb file

ActiveRecord::Schema.define(:version => 20110920230706) do

  create_table "assignments", :force => true do |t|
    t.string   "name"
    t.string   "instructions"
    t.date     "due"
    t.integer  "scribd_id"
    t.decimal  "score"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.binary   "handout"
  end

  create_table "grades", :force => true do |t|
    t.integer  "assignment_id"
    t.integer  "user_id"
    t.integer  "scribd_id"
    t.decimal  "score"
    t.text     "note"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "answer_file_name"
    t.string   "answer_content_type"
    t.integer  "answer_file_size"
    t.datetime "answer_updated_at"
  end

  create_table "users", :force => true do |t|
    t.string   "email",                                 :default => "", :null => false
    t.string   "encrypted_password",     :limit => 128, :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",                         :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

end

Grade.rb

class Grade < ActiveRecord::Base
  belongs_to :assignment

  has_attached_file :answer

end

Show.html.erb

<%= stylesheet_link_tag "assignments" %>

<%= notice %>

<%= @assignment.name %>

Directions -
<%= @assignment.instructions %>

Turn In Assignment

(You can just drag it in here)

  <%= form_for @grade, :html => { :multipart => true, :id => "form"} do |f| %>
    <%= f.file_field :answer, :id => "file" %>
  <% end %>

assignments.js.coffee

$(document).ready ->
  $("#file").mouseenter ->
    $("#turn_in_box").css "border", "2px solid #D9D9D9"
    $("#turn_in_box").css "background", "#D9D9D9"
    $("#turn_in_box").css "color", "#393939"
    $("#turn_in_box").css "cursor", "pointer"
    $("#turn_in_box").css "box-shadow" ,"0px 0px 0px transparent"

  $("#file").mouseleave ->
    $("#turn_in_box").css "border", "2px solid #D9D9D9"
    $("#turn_in_box").css "background", "#393939"
    $("#turn_in_box").css "color", "#D9D9D9"
    $("#turn_in_box").css "cursor", "default"
  $("#file").bind 'dragover', (evt) ->
    evt.stopPropagation()
    evt.preventDefault()
  $("#file").bind 'drop', ->
    $("#drag").css "display", "none"
    $("#turn_in_assignment").text "Turning In Assignment..."
    $("#form").submit()

development.log

Started GET "/assignments/2" for 127.0.0.1 at 2011-09-20 16:08:38 -0700
  Processing by AssignmentsController#show as HTML
  Parameters: {"id"=>"2"}
  ←[1m←[36mUser Load (0.0ms)←[0m  ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1←[0m
  ←[1m←[35mAssignment Load (0.0ms)←[0m  SELECT "assignments".* FROM "assignments" WHERE "assignments"."id" = ? LIMIT 1
  ←[1m←[36mGrade Load (0.0ms)←[0m  ←[1mSELECT "grades".* FROM "grades" WHERE "grades"."assignment_id" = 2 AND "grades".
Rendered assignments/show.html.erb within layouts/application (50.0ms)
Completed 200 OK in 183ms (Views: 132.0ms | ActiveRecord: 1.0ms)

Started GET "/assets/assignments.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.css - 304 Not Modified (0ms)

Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /jquery.js - 304 Not Modified (1ms)

Started GET "/assets/grades.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /grades.css - 304 Not Modified (0ms)

Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /application.css - 304 Not Modified (0ms)

Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /jquery_ujs.js - 304 Not Modified (0ms)

Started GET "/assets/assignments.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.js - 304 Not Modified (1ms)

Started GET "/assets/assignments.js.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.js.js - 304 Not Modified (0ms)

Started GET "/assets/grades.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /grades.js - 304 Not Modified (0ms)

Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /application.js - 304 Not Modified (0ms)

Started PUT "/grades/2" for 127.0.0.1 at 2011-09-20 16:08:47 -0700
  Processing by GradesController#update as HTML
  Parameters: {"utf8"=>"Γ£ô", "authenticity_token"=>"/MpatBt5HIrsYPF0PKeyhfsQjY+Z1yDXMRtZjW+fHA8=", "id"=>"2"}
  ←[1m←[35mGrade Load (0.0ms)←[0m  SELECT "grades".* FROM "grades" WHERE "grades"."id" = ? LIMIT 1  [["id", "2"]]
[paperclip] Saving attachments.
Redirected to http://localhost:3000/grades/2
Completed 302 Found in 51ms

Started GET "/grades/2" for 127.0.0.1 at 2011-09-20 16:08:47 -0700
  Processing by GradesController#show as HTML
  Parameters: {"id"=>"2"}
  ←[1m←[36mGrade Load (1.0ms)←[0m  ←[1mSELECT "grades".* FROM "grades" WHERE "grades"."id" = ? LIMIT 1←[0m  [["id", "2"
Rendered grades/show.html.erb within layouts/application (11.0ms)
Completed 200 OK in 28ms (Views: 25.0ms | ActiveRecord: 1.0ms)


问:
How to store a array of vue components and retrieve it
This is how the UI looks

I have been working on the media mix (video editing) kinda project.

Every time a button is clicked a new clip (component) will be added to the array and I'm using v-for to display them on the left side, on the right side I have this clip Editor component, where we can add images, videos, texts, so what I want is to store these contents of each clip (image, text, videos) unique to them.

I'm storing these contents in an array, but what I want is I need to store these contents and be able to retrieve them, for example, if clip 1 is created and I add an image to it it should be stored, then if clip 2 is created the clip Editor on right should be empty and if I add a video to it it should also be stored, and if I click on clip 1 the stored image of the clip 1 should display, and then if I click clip 2 the video of clip 2 should display.

I have tried local storage it didn't work the new content is overriding the previous content, and I don't know how to use Vuex store.

I tried to save the contents array in local storage, and don't know how to use Vuex (i tried to learn but it's confusing and not working as well)


问:
flutter migration to null-safety - how fix "Bad state: Error: package has unmigrated dependencies"?
I have a pretty big Flutter project, I'm currently adding null-safety support. My project consists of several parts - the "core" and  "client".
"Client" used "core"

```<code>environment:
   sdk: ">=2.10.0 <3.0.0"
.....
 app_core:
   path: ../core
</code>```

First I updated the core with command

```<code>dart migrate
</code>```

Now I when run "dart migrate"(in core) - I get this result:

```<code> All sources appear to be already migrated.  Nothing to do.
</code>```

Now I try to update the "client" part, I run the following commands

```<code>dart pub outdated --mode=null-safety

[✗] indicates versions without null safety support.
[✓] indicates versions opting in to null safety.

All your dependencies declare support for null-safety.
</code>```

Next step:

```<code>dart pub upgrade --null-safety
Changed 1 dependency!
1 package is discontinued.
24 packages have newer versions incompatible with dependency constraints.
Try `dart pub outdated` for more information.

No changes to pubspec.yaml!
</code>```

Next step:

```<code>dart pub get
</code>```

When I run

```<code>dart migrate
</code>```

I get these messages:

```<code>Bad state: Error: package has unmigrated dependencies.

Before migrating your package, we recommend ensuring that every library it
(either directly or indirectly) has been migrated to null safety, so
that you will be able to run your unit tests in sound null checking mode.  You
are currently importing the following non-null-safe libraries:
...//file list
..............
Please upgrade the packages containing these libraries to null
safe versions
before continuing.  To see what null safe package versions are
available, run
the following command: `dart pub outdated --mode=null-safety`.

To skip this check and try to migrate anyway, re-run with the
flag
`--skip-import-check`.
</code>```

"file list" - is a large list of files from  "client" (I did not find any regularity in it). Also, these files have no errors.

What is the reason for these warnings?
How can I fix it? Any advice - I will be grateful.

Body:
I have a pretty big Flutter project, I'm currently adding null-safety support. My project consists of several parts - the "core" and  "client".
"Client" used "core"

environment:
   sdk: ">=2.10.0 <3.0.0"
.....
 app_core:
   path: ../core

First I updated the core with command

dart migrate

Now I when run "dart migrate"(in core) - I get this result:

 All sources appear to be already migrated.  Nothing to do.

Now I try to update the "client" part, I run the following commands

dart pub outdated --mode=null-safety

[✗] indicates versions without null safety support.
[✓] indicates versions opting in to null safety.

All your dependencies declare support for null-safety.

Next step:

dart pub upgrade --null-safety
Changed 1 dependency!
1 package is discontinued.
24 packages have newer versions incompatible with dependency constraints.
Try `dart pub outdated` for more information.

No changes to pubspec.yaml!

Next step:

dart pub get

When I run

dart migrate

I get these messages:

Bad state: Error: package has unmigrated dependencies.

Before migrating your package, we recommend ensuring that every library it
(either directly or indirectly) has been migrated to null safety, so
that you will be able to run your unit tests in sound null checking mode.  You
are currently importing the following non-null-safe libraries:
...//file list
..............
Please upgrade the packages containing these libraries to null
safe versions
before continuing.  To see what null safe package versions are
available, run
the following command: `dart pub outdated --mode=null-safety`.

To skip this check and try to migrate anyway, re-run with the
flag
`--skip-import-check`.

"file list" - is a large list of files from  "client" (I did not find any regularity in it). Also, these files have no errors.

What is the reason for these warnings?
How can I fix it? Any advice - I will be grateful.


问:
Options while installing software
When I often install software there are listed installation options for specific features what is shown in the image:
https://i.stack.imgur.com/KoNNH.png
Could anyone explain me what are the differences between these options?</p>

Title: Options while installing software


问:
CyberPanel Installation Syntax Error on Hostinger: newline unexpected
I am quite new at Ubuntu, but I am trying to install Cyberpanel to my VPS with Ubuntu 20.04 64bit on Hostinger.

I have tried to use the command below from the documentation (https://community.cyberpanel.net/docs?category=9&topic=82):

sh <(curl https://cyberpanel.net/install.sh || wget -O - https://cyberpanel.net/install.sh)

And also other commands like curl -0 http://cyberpanel.net/install.sh | sudo sh, from this SO question (Syntax error: newline unexpected node.js rpm) or the commands from this tutorial https://blog.eldernode.com/setup-cyberpanel-on-ubuntu-20-04/, but it doesn't matter which command I use, I get the error below:

./cyberpanel.sh: 2: Syntax error: newline unexpected

or

sh: 2: Syntax error: newline unexpected

I am connected to my VPS as root, but I really don't know what to do. Can anyone help please?


问:
Cassandra Connection with karate>> how to pass the query from feature file to database utility using java.I have written DB utility code for reference
I have written this code in DB utility and here I am passing a configuration from property file and select query in same method just to check DB connection.
But now my requirement is to pass query and configuration from feature file itself.
So that we can use this utility everywhere in the framework. Please refer the code</p>
```<code>package Utilities;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class DatabaseConnectionUtils {
    public static Properties readPropertiesFile(String fileName) throws IOException {
        FileInputStream fis = null;
        Properties prop = null;
        try {
            fis = new FileInputStream(fileName);
            prop = new Properties();
            prop.load(fis);
        } catch(FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } finally {
            fis.close();
        }
        return prop;
    }

    public static void connect(String serverIP, Integer port, String keyspace, String username, String password) {
        Cluster cluster;
        Session session;
        Cluster.Builder b = Cluster.builder().addContactPoint(serverIP);
        if (port != null) {
            b.withPort(port).withCredentials(username,password);
        }
        cluster = b.build();
        session = cluster.connect(keyspace);

        String cqlStatement = "select * from partner_configuration where partnerid='15918' allow filtering;";
        for (Row row : session.execute(cqlStatement)) {
            System.out.println(row.toString());
        }
        session.close();
    }

    public static void main(String[] args) throws IOException {

        Properties prop = readPropertiesFile("C:\\NMS-Framework\\untitled\\src\\test\\resources\\DB-Credentials.properties");
        String address=prop.getProperty("ServerIP");
        int port= Integer.parseInt(prop.getProperty("port"));
        String keyspace=prop.getProperty("keyspace");
        String username=prop.getProperty("username");
        String password= prop.getProperty("password");

        connect(address,port,keyspace,username,password);

    }
    }
</code>```

Body:
I have written this code in DB utility and here I am passing a configuration from property file and select query in same method just to check DB connection.
But now my requirement is to pass query and configuration from feature file itself.
So that we can use this utility everywhere in the framework. Please refer the code

package Utilities;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class DatabaseConnectionUtils {
    public static Properties readPropertiesFile(String fileName) throws IOException {
        FileInputStream fis = null;
        Properties prop = null;
        try {
            fis = new FileInputStream(fileName);
            prop = new Properties();
            prop.load(fis);
        } catch(FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } finally {
            fis.close();
        }
        return prop;
    }

    public static void connect(String serverIP, Integer port, String keyspace, String username, String password) {
        Cluster cluster;
        Session session;
        Cluster.Builder b = Cluster.builder().addContactPoint(serverIP);
        if (port != null) {
            b.withPort(port).withCredentials(username,password);
        }
        cluster = b.build();
        session = cluster.connect(keyspace);

        String cqlStatement = "select * from partner_configuration where partnerid='15918' allow filtering;";
        for (Row row : session.execute(cqlStatement)) {
            System.out.println(row.toString());
        }
        session.close();
    }

    public static void main(String[] args) throws IOException {

        Properties prop = readPropertiesFile("C:\\NMS-Framework\\untitled\\src\\test\\resources\\DB-Credentials.properties");
        String address=prop.getProperty("ServerIP");
        int port= Integer.parseInt(prop.getProperty("port"));
        String keyspace=prop.getProperty("keyspace");
        String username=prop.getProperty("username");
        String password= prop.getProperty("password");

        connect(address,port,keyspace,username,password);

    }
    }


问:
PS command on this program
In an assignment, I wrote 2 programs that do the same thing, but one of them uses threads. What I'm asked to do is to stop the programs while they are running and use the ps command to compare the two programs, the problem is that I don't know how to do this, I wanted to try stopping the programs using ^z but the programs execute so fast that I can't even do it, is there a way to do what I'm asked to do? is using functions like sleep will help me? or does it affect the results of the ps command?

Here're the programs that I wrote in case it helps and I can modify them to do what I want.

without threads:

```<code>#include <stdio.h>

int main(void) {
    int mat[100][100];  // Declare the array

    // Generate the values for the array
    for (int row = 0; row < 100; row++) {
        for (int col = 0; col < 100; col++) {
            mat[row][col] = row * 5 + col / 3 + col;
        }
    }

    // Sum up the values in the array
    int sum = 0;
    for (int row = 0; row < 100; row++) {
        for (int col = 0; col < 100; col++) {
            sum += mat[row][col];
        }
    }

    // Print the result
    printf("Sum of all values in mat: %d\n", sum);

    return 0;
}

</code>```

with threads:

```<code>#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 100  // Number of threads (one for each column)
#define ROWS 100  // Number of rows in the array
#define COLS 100  // Number of columns in the array

int mat[ROWS][COLS];  // Array to store the values
int sums[COLS];  // Array to store the sums for each column

// Thread function to sum up a column of the array
void* sum_column(void* arg) {
    int col = (int)arg;  // Column to sum up

    // Sum up the values in the column
    int sum = 0;
    for (int row = 0; row < ROWS; row++) {
        sum += mat[row][col];
    }

    // Store the result in the sums array
    sums[col] = sum;

    return NULL;
}

int main(void) {
    pthread_t threads[NUM_THREADS];  // Threads

    // Generate the values for the array
    for (int row = 0; row < ROWS; row++) {
        for (int col = 0; col < COLS; col++) {
            mat[row][col] = row * 5 + col / 3 + col;
        }
    }

    // Create a thread for each column to sum it up
    for (int col = 0; col < COLS; col++) {
        pthread_create(&threads[col], NULL, sum_column, (void*)col);
    }

    // Wait for all threads to finish
    for (int col = 0; col < COLS; col++) {
        pthread_join(threads[col], NULL);
    }

    // Sum up the values in the sums array
    int sum = 0;
    for (int col = 0; col < COLS; col++) {
        sum += sums[col];
    }

    // Print the result
    printf("Sum of all values in mat: %d\n", sum);

    return 0;
}

</code>```

Title: PS command on this program

Body:
In an assignment, I wrote 2 programs that do the same thing, but one of them uses threads. What I'm asked to do is to stop the programs while they are running and use the ps command to compare the two programs, the problem is that I don't know how to do this, I wanted to try stopping the programs using ^z but the programs execute so fast that I can't even do it, is there a way to do what I'm asked to do? is using functions like sleep will help me? or does it affect the results of the ps command?

Here're the programs that I wrote in case it helps and I can modify them to do what I want.

without threads:

#include <stdio.h>

int main(void) {
    int mat[100][100];  // Declare the array

    // Generate the values for the array
    for (int row = 0; row < 100; row++) {
        for (int col = 0; col < 100; col++) {
            mat[row][col] = row * 5 + col / 3 + col;
        }
    }

    // Sum up the values in the array
    int sum = 0;
    for (int row = 0; row < 100; row++) {
        for (int col = 0; col < 100; col++) {
            sum += mat[row][col];
        }
    }

    // Print the result
    printf("Sum of all values in mat: %d\n", sum);

    return 0;
}

with threads:

#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 100  // Number of threads (one for each column)
#define ROWS 100  // Number of rows in the array
#define COLS 100  // Number of columns in the array

int mat[ROWS][COLS];  // Array to store the values
int sums[COLS];  // Array to store the sums for each column

// Thread function to sum up a column of the array
void* sum_column(void* arg) {
    int col = (int)arg;  // Column to sum up

    // Sum up the values in the column
    int sum = 0;
    for (int row = 0; row < ROWS; row++) {
        sum += mat[row][col];
    }

    // Store the result in the sums array
    sums[col] = sum;

    return NULL;
}

int main(void) {
    pthread_t threads[NUM_THREADS];  // Threads

    // Generate the values for the array
    for (int row = 0; row < ROWS; row++) {
        for (int col = 0; col < COLS; col++) {
            mat[row][col] = row * 5 + col / 3 + col;
        }
    }

    // Create a thread for each column to sum it up
    for (int col = 0; col < COLS; col++) {
        pthread_create(&threads[col], NULL, sum_column, (void*)col);
    }

    // Wait for all threads to finish
    for (int col = 0; col < COLS; col++) {
        pthread_join(threads[col], NULL);
    }

    // Sum up the values in the sums array
    int sum = 0;
    for (int col = 0; col < COLS; col++) {
        sum += sums[col];
    }

    // Print the result
    printf("Sum of all values in mat: %d\n", sum);

    return 0;
}


问:
How to assign data without repetition in SQL
I need to create automatic weekly assignments of items to sites for my employees.

The items table items_bank looks like that(of course there will be a lot of items with few more languages) :

```<code>**item_id**     **item_name**           **language**
   1            Jorge Garcia              English
   2            Chrissy Metz              English
   3             Nina Hagen               German
   4           Harald Glööckle            German
   5           Melissa Anderson           French
   6           Pauley Perrette            French

</code>```

My second table is the sites table :

```<code>**site_id**   **site_name**
    1             DR
    2             LI
    3             IG

</code>```

I need to assign every week items to the sites with the following constraints :

For each site assign at least X items of English, Y items of German, and so on...
we want to create diversity - so we would like to avoid repeating the assignments of the 2 weeks before
I think we need to create another table in which we can save there the history of the last 2 weeks' assignments.

right now I managed to create an SQL query that assigns items but I don't know how to take the constraints under consideration this is what I create so far :

```<code>WITH numbered_tasks AS (
SELECT t.*, row_number() OVER (ORDER BY rand()) item_number, count(*) OVER () total_items
FROM item_bank t
),
numbered_employees AS (
SELECT e.*,row_number() OVER (ORDER BY rand()) site_number,
count(*) OVER () total_sites
FROM sites_bank e
)
SELECT     nt.item_name,
           ne.acronym
FROM       numbered_tasks nt
INNER JOIN numbered_employees ne
ON ne.site_number-1 = mod(nt.item_number-1, ne.total_sites)

</code>```

Expected results are for the example which says :
site_id=1 have to get 1 item with the English language

site_id=2 have to get 1 item with the German language

site_id=1 have to get 1 item with the French language

```<code>**item_id**   **language**    **Week_number**    **site**
   1            English             1               1
   4            German              1               2
   5            French              1               3

</code>```

Any help will be appreciated!

Body:
I need to create automatic weekly assignments of items to sites for my employees.

The items table items_bank looks like that(of course there will be a lot of items with few more languages) :

**item_id**     **item_name**           **language**
   1            Jorge Garcia              English
   2            Chrissy Metz              English
   3             Nina Hagen               German
   4           Harald Glööckle            German
   5           Melissa Anderson           French
   6           Pauley Perrette            French

My second table is the sites table :

**site_id**   **site_name**
    1             DR
    2             LI
    3             IG

I need to assign every week items to the sites with the following constraints :

For each site assign at least X items of English, Y items of German, and so on...
we want to create diversity - so we would like to avoid repeating the assignments of the 2 weeks before
I think we need to create another table in which we can save there the history of the last 2 weeks' assignments.

right now I managed to create an SQL query that assigns items but I don't know how to take the constraints under consideration this is what I create so far :

WITH numbered_tasks AS (
SELECT t.*, row_number() OVER (ORDER BY rand()) item_number, count(*) OVER () total_items
FROM item_bank t
),
numbered_employees AS (
SELECT e.*,row_number() OVER (ORDER BY rand()) site_number,
count(*) OVER () total_sites
FROM sites_bank e
)
SELECT     nt.item_name,
           ne.acronym
FROM       numbered_tasks nt
INNER JOIN numbered_employees ne
ON ne.site_number-1 = mod(nt.item_number-1, ne.total_sites)

Expected results are for the example which says :
site_id=1 have to get 1 item with the English language

site_id=2 have to get 1 item with the German language

site_id=1 have to get 1 item with the French language

**item_id**   **language**    **Week_number**    **site**
   1            English             1               1
   4            German              1               2
   5            French              1               3

Any help will be appreciated!


问:
From the two same lines, one is generating an error relative to FutureOrNull
Thos are the two  function from the same class I wrote: The first has the error:

A value of type 'Future<String?>' can't be returned by the 'onError' handler because it must be assignable to 'FutureOr'.

while the second is OK and I don't understand why.

Can you tell me please?

  /// Creates or update the User collection
  Future<String?> _createOrUpdateUser(User user) {
    final email = user.email;
    final nameFromEmail =
        email!.substring(0, email.indexOf('@')).replaceAll(".", " ").trim();

    return FirebaseFirestore.instance.collection('users').doc(user.uid).set({
      'id': user.uid,
      'screenName': '',
      'displayName': user.displayName ?? nameFromEmail,
      'photoUrl': user.photoURL,
      'bio': '',
      'darkMode': false,
      'email': user.email,
    }).then((_) {
      debugPrint("User ${user.displayName} is created");
      return null;
    }).catchError((e) {
      debugPrint(e.toString());
      return Future<String?>.error(e);  // <<<<< Error here: A value of type 'Future<String?>' can't be returned by the 'onError' handler because it must be assignable to 'FutureOr<Null>'.
    });
  }

  Future<String?> _authUser(BuildContext context, LoginData data) {
    debugPrint('Name: ${data.name}, Password: ${data.password}');

    return auth
        .signInWithEmailAndPassword(email: data.name, password: data.password)
        .then((credential) {
      try {
        final user = credential.user;

        if (user == null) {
          return 'Password does not match';
        } else {
          _createOrUpdateUser(user);

          // == Tell the app we just signed in
          Provider.of<StateModel>(context, listen: false).signedIn = user;
          return null;
        }
      } catch (e) {
        return 'User not exists';
      }
    }).catchError((e) {
      if (e.code == 'weak-password') {
        debugPrint('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        debugPrint('The account already exists for that email.');
      } else {
        debugPrint(e.toString());
      }

      return Future<String?>.error(e);    // <<<<< No problem here
    });
  }
```


问:
index.html:308 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or
getting
index.html:308 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.</p>
```<code>$("#file-picker")[0].onchange = function() {
        $("#EnterWrapper").hide();
        $(".ContainerWrapper").show();
        var c = document.getElementsByClassName('demo-canvas');
        var ctx = c[0].getContext("2d");
        img = $("#file-picker")[0];
        console.log(typeof img[this.spriteCostumeCount])
        ctx.drawImage(img, 10, 10, 150, 180);
};
</code>```

Body:
getting
index.html:308 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.

$("#file-picker")[0].onchange = function() {
        $("#EnterWrapper").hide();
        $(".ContainerWrapper").show();
        var c = document.getElementsByClassName('demo-canvas');
        var ctx = c[0].getContext("2d");
        img = $("#file-picker")[0];
        console.log(typeof img[this.spriteCostumeCount])
        ctx.drawImage(img, 10, 10, 150, 180);
};


问:
pydantic package ImportError (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))
my system: macos Ventura 13.0
CPU: AppleM2
python: 3.10.0

heroku: heroku/7.67.1 darwin-x64 node-v14.19.0
pydantic: 1.10.2

when i run command "heroku local web", i got the error, apple m2 is ARM arch, why the error is "need x86_64"? if someone meet the problem, how can i fix it?

```<code>9:19:25 PM web.1 |      from fastapi import params
9:19:25 PM web.1 |    File "/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/fastapi/params.py", line 4, in <module>
9:19:25 PM web.1 |      from pydantic.fields import FieldInfo, Undefined
9:19:25 PM web.1 |  ImportError: dlopen(/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so, 0x0002): tried: '/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-M
9:19:25 PM web.1 |  >  QQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so' (no such file), '/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))
[DONE] Killing all processes with signal  SIGINT
9:19:25 PM web.1 Exited with exit code null
</code>```

poetry show:

```<code>alembic            1.8.1     A database migration tool for SQLAlchemy.
amqp               5.1.1     Low-level AMQP client for Python (fork of amqplib).
anyio              3.6.2     High level compatibility layer for multiple asynchronous event loop implementations
asgiref            3.5.2     ASGI specs, helper code, and adapters
async-timeout      4.0.2     Timeout context manager for asyncio programs
asyncpg            0.27.0    An asyncio PostgreSQL driver
attrs              22.1.0    Classes Without Boilerplate
billiard           3.6.4.0   Python multiprocessing fork with improvements and bugfixes
black              22.12.0   The uncompromising code formatter.
celery             5.2.7     Distributed Task Queue.
certifi            2022.12.7 Python package for providing Mozilla's CA Bundle.
click              8.1.3     Composable command line interface toolkit
click-didyoumean   0.3.0     Enables git-like *did-you-mean* feature in click
click-plugins      1.1.1     An extension module for click to enable registering CLI commands via setuptools entry-points.
click-repl         0.2.0     REPL plugin for Click
fastapi            0.86.0    FastAPI framework, high performance, easy to learn, fast to code, ready for production
fastapi-camelcase  1.0.5     Package provides an easy way to have camelcase request/response bodies for Pydantic
flake8             3.9.2     the modular source code checker: pep8 pyflakes and co
gevent             22.10.2   Coroutine-based network library
greenlet           2.0.1     Lightweight in-process concurrent programming
h11                0.14.0    A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
httpcore           0.16.2    A minimal low-level HTTP client.
httptools          0.5.0     A collection of framework independent HTTP protocol utils.
httpx              0.23.1    The next generation HTTP client.
idna               3.4       Internationalized Domain Names in Applications (IDNA)
iniconfig          1.1.1     iniconfig: brain-dead simple config-ini parsing
kombu              5.2.4     Messaging library for Python.
mako               1.2.4     A super-fast templating language that borrows the best ideas from the existing templating languages.
markupsafe         2.1.1     Safely add untrusted strings to HTML/XML markup.
mccabe             0.6.1     McCabe checker, plugin for flake8
mypy-extensions    0.4.3     Experimental type system extensions for programs checked with the mypy typechecker.
packaging          22.0      Core utilities for Python packages
pathspec           0.10.3    Utility library for gitignore style pattern matching of file paths.
platformdirs       2.6.0     A small Python package for determining appropriate platform-specific dirs, e.g. a "user data dir".
pluggy             1.0.0     plugin and hook calling mechanisms for python
prompt-toolkit     3.0.36    Library for building powerful interactive command lines in Python
pycodestyle        2.7.0     Python style guide checker
pycountry          22.3.5    ISO country, subdivision, language, currency and script definitions and their translations
pydantic           1.10.2    Data validation and settings management using python type hints
pyflakes           2.3.1     passive checker of Python programs
pyhumps            3.8.0       Convert strings (and dictionary keys) between snake case, camel case and pascal case in Python. Inspired by Humps for Node
pytest             7.2.0     pytest: simple powerful testing with Python
python-dotenv      0.21.0    Read key-value pairs from a .env file and set them as environment variables
python-json-logger 2.0.4     A python library adding a json log formatter
pytz               2022.6    World timezone definitions, modern and historical
pyyaml             6.0       YAML parser and emitter for Python
redis              4.4.0     Python client for Redis database and key-value store
rfc3986            1.5.0     Validating URI References per RFC 3986
setuptools         65.6.3    Easily download, build, install, upgrade, and uninstall Python packages
six                1.16.0    Python 2 and 3 compatibility utilities
sniffio            1.3.0     Sniff out which async library your code is running under
sqlalchemy         1.4.45    Database Abstraction Library
starlette          0.20.4    The little ASGI library that shines.
typing-extensions  4.4.0     Backported and Experimental Type Hints for Python 3.7+
uvicorn            0.19.0    The lightning-fast ASGI server.
uvloop             0.17.0    Fast implementation of asyncio event loop on top of libuv
vine               5.0.0     Promises, promises, promises.
watchfiles         0.18.1    Simple, modern and high performance file watching and code reload in python.
wcwidth            0.2.5     Measures the displayed width of unicode strings in a terminal
websockets         10.4      An implementation of the WebSocket Protocol (RFC 6455 & 7692)
zope-event         4.6       Very basic event publishing system
zope-interface     5.5.2     Interfaces for Python
</code>```

i execute the code:

```<code>python3 -c "import pydantic.utils; print(pydantic.utils.version_info())"
</code>```

output:

```<code>pydantic version: 1.10.2
            pydantic compiled: True
                 install path: /Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)]
                     platform: macOS-13.0-arm64-arm-64bit
     optional deps. installed: ['dotenv', 'typing-extensions']
</code>```

Body:
my system: macos Ventura 13.0
CPU: AppleM2
python: 3.10.0

heroku: heroku/7.67.1 darwin-x64 node-v14.19.0
pydantic: 1.10.2

when i run command "heroku local web", i got the error, apple m2 is ARM arch, why the error is "need x86_64"? if someone meet the problem, how can i fix it?

9:19:25 PM web.1 |      from fastapi import params
9:19:25 PM web.1 |    File "/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/fastapi/params.py", line 4, in <module>
9:19:25 PM web.1 |      from pydantic.fields import FieldInfo, Undefined
9:19:25 PM web.1 |  ImportError: dlopen(/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so, 0x0002): tried: '/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-M
9:19:25 PM web.1 |  >  QQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so' (no such file), '/Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic/__init__.cpython-311-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))
[DONE] Killing all processes with signal  SIGINT
9:19:25 PM web.1 Exited with exit code null

poetry show:

alembic            1.8.1     A database migration tool for SQLAlchemy.
amqp               5.1.1     Low-level AMQP client for Python (fork of amqplib).
anyio              3.6.2     High level compatibility layer for multiple asynchronous event loop implementations
asgiref            3.5.2     ASGI specs, helper code, and adapters
async-timeout      4.0.2     Timeout context manager for asyncio programs
asyncpg            0.27.0    An asyncio PostgreSQL driver
attrs              22.1.0    Classes Without Boilerplate
billiard           3.6.4.0   Python multiprocessing fork with improvements and bugfixes
black              22.12.0   The uncompromising code formatter.
celery             5.2.7     Distributed Task Queue.
certifi            2022.12.7 Python package for providing Mozilla's CA Bundle.
click              8.1.3     Composable command line interface toolkit
click-didyoumean   0.3.0     Enables git-like *did-you-mean* feature in click
click-plugins      1.1.1     An extension module for click to enable registering CLI commands via setuptools entry-points.
click-repl         0.2.0     REPL plugin for Click
fastapi            0.86.0    FastAPI framework, high performance, easy to learn, fast to code, ready for production
fastapi-camelcase  1.0.5     Package provides an easy way to have camelcase request/response bodies for Pydantic
flake8             3.9.2     the modular source code checker: pep8 pyflakes and co
gevent             22.10.2   Coroutine-based network library
greenlet           2.0.1     Lightweight in-process concurrent programming
h11                0.14.0    A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
httpcore           0.16.2    A minimal low-level HTTP client.
httptools          0.5.0     A collection of framework independent HTTP protocol utils.
httpx              0.23.1    The next generation HTTP client.
idna               3.4       Internationalized Domain Names in Applications (IDNA)
iniconfig          1.1.1     iniconfig: brain-dead simple config-ini parsing
kombu              5.2.4     Messaging library for Python.
mako               1.2.4     A super-fast templating language that borrows the best ideas from the existing templating languages.
markupsafe         2.1.1     Safely add untrusted strings to HTML/XML markup.
mccabe             0.6.1     McCabe checker, plugin for flake8
mypy-extensions    0.4.3     Experimental type system extensions for programs checked with the mypy typechecker.
packaging          22.0      Core utilities for Python packages
pathspec           0.10.3    Utility library for gitignore style pattern matching of file paths.
platformdirs       2.6.0     A small Python package for determining appropriate platform-specific dirs, e.g. a "user data dir".
pluggy             1.0.0     plugin and hook calling mechanisms for python
prompt-toolkit     3.0.36    Library for building powerful interactive command lines in Python
pycodestyle        2.7.0     Python style guide checker
pycountry          22.3.5    ISO country, subdivision, language, currency and script definitions and their translations
pydantic           1.10.2    Data validation and settings management using python type hints
pyflakes           2.3.1     passive checker of Python programs
pyhumps            3.8.0       Convert strings (and dictionary keys) between snake case, camel case and pascal case in Python. Inspired by Humps for Node
pytest             7.2.0     pytest: simple powerful testing with Python
python-dotenv      0.21.0    Read key-value pairs from a .env file and set them as environment variables
python-json-logger 2.0.4     A python library adding a json log formatter
pytz               2022.6    World timezone definitions, modern and historical
pyyaml             6.0       YAML parser and emitter for Python
redis              4.4.0     Python client for Redis database and key-value store
rfc3986            1.5.0     Validating URI References per RFC 3986
setuptools         65.6.3    Easily download, build, install, upgrade, and uninstall Python packages
six                1.16.0    Python 2 and 3 compatibility utilities
sniffio            1.3.0     Sniff out which async library your code is running under
sqlalchemy         1.4.45    Database Abstraction Library
starlette          0.20.4    The little ASGI library that shines.
typing-extensions  4.4.0     Backported and Experimental Type Hints for Python 3.7+
uvicorn            0.19.0    The lightning-fast ASGI server.
uvloop             0.17.0    Fast implementation of asyncio event loop on top of libuv
vine               5.0.0     Promises, promises, promises.
watchfiles         0.18.1    Simple, modern and high performance file watching and code reload in python.
wcwidth            0.2.5     Measures the displayed width of unicode strings in a terminal
websockets         10.4      An implementation of the WebSocket Protocol (RFC 6455 & 7692)
zope-event         4.6       Very basic event publishing system
zope-interface     5.5.2     Interfaces for Python

i execute the code:

python3 -c "import pydantic.utils; print(pydantic.utils.version_info())"

output:

pydantic version: 1.10.2
            pydantic compiled: True
                 install path: /Users/wj/Library/Caches/pypoetry/virtualenvs/fuse-hotel-MQQZRb-z-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)]
                     platform: macOS-13.0-arm64-arm-64bit
     optional deps. installed: ['dotenv', 'typing-extensions']


问:
Eclipse Java Custom stream log (System.out custom)
is there a way in eclipse to have a log on a separate window?
Like System out/err but on a separate tab. It's just for debugging and then I'll remove the command.
I wouldn't want to create any other appenders in Log4j or similar.

In my case I want to keep the list of names by iterating around 100k variables.

```<code>for (VariableBean var : variables) {

    if("Integer".equals(var.getType())) {
        // do something
    } if("String".equals(var.getType())) {
        // do something
    } if("Data".equals(var.getType())) {

        System.....println("Data Variable: " + var);

    } else {
        // do something else
    }
}
</code>```

Thanks!

Body:
is there a way in eclipse to have a log on a separate window?
Like System out/err but on a separate tab. It's just for debugging and then I'll remove the command.
I wouldn't want to create any other appenders in Log4j or similar.

In my case I want to keep the list of names by iterating around 100k variables.

for (VariableBean var : variables) {

    if("Integer".equals(var.getType())) {
        // do something
    } if("String".equals(var.getType())) {
        // do something
    } if("Data".equals(var.getType())) {

        System.....println("Data Variable: " + var);

    } else {
        // do something else
    }
}

Thanks!


问:
Mark for add does not work to add new file in Eclipse with perforce plugin
I use Eclipse with perforce plugin.

And currently in eclipse when I edit some files which I've already added to changelist, it is ok, I'm able to edit it in changelist.

But if I want to add new file to changelist using right click on file -> Mark for add. Nothing happenned and the file does not add to perforce.

How can I add newly added file to changelist via eclipse?


问:
How to call expect in @testing-library/react
Here is my code:

```<code>import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import user  from '@testing-library/user-event';
import FirebaseLogin from './AuthLogin';
import i18n from '../../../../i18nForTests';
import { I18nextProvider } from 'react-i18next';

test('shows error message when email is empty', async () => {
      i18n.changeLanguage('en');
      const comp = render(<I18nextProvider i18n={i18n}><FirebaseLogin /></I18nextProvider>);
      const emailInput = getEmail();
      await user.click(screen.getByRole('button', { name: /sign in/i }));

      await waitFor(() => {
        expect(getEmail()).toHaveErrorMessage('Email is required');
      });
  });

  function getEmail() {
    return screen.getByRole('textbox', {  name: /email address/i});
  }
</code>```

When I run this test via npm test, it write the following error:

```<code>TypeError: expect(...).toHaveErrorMessage is not a function
</code>```

Do you know, what is wrong wiht my settings or code?

Body:
Here is my code:

import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import user  from '@testing-library/user-event';
import FirebaseLogin from './AuthLogin';
import i18n from '../../../../i18nForTests';
import { I18nextProvider } from 'react-i18next';

test('shows error message when email is empty', async () => {
      i18n.changeLanguage('en');
      const comp = render(<I18nextProvider i18n={i18n}><FirebaseLogin /></I18nextProvider>);
      const emailInput = getEmail();
      await user.click(screen.getByRole('button', { name: /sign in/i }));

      await waitFor(() => {
        expect(getEmail()).toHaveErrorMessage('Email is required');
      });
  });

  function getEmail() {
    return screen.getByRole('textbox', {  name: /email address/i});
  }

When I run this test via npm test, it write the following error:

TypeError: expect(...).toHaveErrorMessage is not a function

Do you know, what is wrong wiht my settings or code?


问:
Selenium with Cloudflare problems: Cant Login or send forms
i want to make a small automation to sign in for shoe raffles when im sending my discord bot a link for a shoe raffle.

The site I am visiting is: bstn
The shoe raffle i want to sign in: raffle

Its no problem to pass the cloudflare protection, i use undetected_chromedriver and this works perfectly.

Here is my code:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
from csv_data import user_e_mail,user_vorname,user_nachname,user_straße,user_postleitzahl,user_hausnummer,user_stadt,user_instagram
import undetected_chromedriver as uc
from selenium.webdriver.support import expected_conditions as EC
import pickle
from fake_useragent import UserAgent
from selenium_stealth import stealth

def bstn_login_and_cookie_save(browser):

    accept_cookies = browser.find_element(By.CLASS_NAME, "cf2Lf6")
    accept_cookies.click()

    time.sleep(2)

    log_in = browser.find_element(By.CLASS_NAME, "icon.header-button__icon")
    log_in.click()

    time.sleep(2)

    e_maxxil_field = browser.find_element(By.ID, "email")
    e_mail_field.send_keys("xxx")

    time.sleep(1)

    password_field = browser.find_element(By.ID, "pass")
    password_field.send_keys("xxx\n")

    time.sleep(1)

    time.sleep(5)
    cookies = browser.get_cookies()
    pickle.dump(cookies, open("cookies_bstn.pkl", "wb"))

    time.sleep(10)

def bstn_raffle(url):

    if __name__ == '__main__':

        browser = uc.Chrome()
        browser.get("https://bstn.com")

        time.sleep(5)

        try:
            cookies = pickle.load(open("cookies_bstn.pkl", "rb"))

            for cookie in cookies:
                cookie['domain'] = ".bstn.com"

                try:
                    browser.add_cookie(cookie)

                except Exception as e:
                    print(e)

        except:

            print("Keine cookies gefunden, logge ein und speichere cookies")
            bstn_login_and_cookie_save(browser)
            print("Cookies erstellt")

        browser.get(url)
        time.sleep(5)

        size = browser.find_element(By.XPATH, "//div[text()='44,5']")
        size.click()

        time.sleep(2)
        try:
            instagram = browser.find_element(By.ID, "instagram_name")
            instagram.send_keys("habinef")

            time.sleep(1)

            anwenden = browser.find_element(By.CLASS_NAME, "Button_secondary__XJln1.Button_button__Bq8yb")
            anwenden.click()
            time.sleep(1)
        except:
            time.sleep(1)

        checkbox = browser.find_element(By.XPATH, "/html/body/div[1]/main/div/div[2]/div[3]/div[3]/div[5]/div[2]/div/div/div/div/label/span")
        browser.execute_script("arguments[0].click()", checkbox)

        time.sleep(1)

        enter_raffle = browser.find_element(By.CLASS_NAME, "Button_primary__4kM2r.Button_button__Bq8yb")
        enter_raffle.click()

        time.sleep(10)

bstn_raffle("https://raffle.bstn.com/eu_de/jordan-air-jordan-2-retro-chicago-dx2454-106-0279577")

</code>```

It doesnt matter if im visiting the raffle shoe page directly and log in or visit the main page > log in > got to the product page to sign in

Every time I press the enter raffle button i got a red message in the bottom that its not possible to sign in in this raffle. Cloudflare is detecting Selenium in any kind but dont know how to solve it.

I also figured out when im use this code here:

```<code>import undetected_chromedriver as uc
from selenium import webdriver
import time

browser = uc.Chrome()
browser.get("https://bot.sannysoft.com/")
time.sleep(1)
browser.switch_to.new_window('tab')
browser.get("https://raffle.bstn.com/eu_de/jordan-air-jordan-2-retro-chicago-dx2454-106-0279577")
time.sleep(1000)
</code>```

and then try to sign in for the raffle manually i also get the red response message, but when i run this code here:

```<code>import undetected_chromedriver as uc
from selenium import webdriver
import time

browser = uc.Chrome()
browser.get("https://bot.sannysoft.com/")
time.sleep(10000)
</code>```

and i open MANUAL a new tab, type in the product page for the raffle i can enter the raffle.

Anyone knows what is happening here and can help me? If you want to run this code, make sure to use the german language.

Body:
i want to make a small automation to sign in for shoe raffles when im sending my discord bot a link for a shoe raffle.

The site I am visiting is: bstn
The shoe raffle i want to sign in: raffle

Its no problem to pass the cloudflare protection, i use undetected_chromedriver and this works perfectly.

Here is my code:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
from csv_data import user_e_mail,user_vorname,user_nachname,user_straße,user_postleitzahl,user_hausnummer,user_stadt,user_instagram
import undetected_chromedriver as uc
from selenium.webdriver.support import expected_conditions as EC
import pickle
from fake_useragent import UserAgent
from selenium_stealth import stealth

def bstn_login_and_cookie_save(browser):

    accept_cookies = browser.find_element(By.CLASS_NAME, "cf2Lf6")
    accept_cookies.click()

    time.sleep(2)

    log_in = browser.find_element(By.CLASS_NAME, "icon.header-button__icon")
    log_in.click()

    time.sleep(2)

    e_maxxil_field = browser.find_element(By.ID, "email")
    e_mail_field.send_keys("xxx")

    time.sleep(1)

    password_field = browser.find_element(By.ID, "pass")
    password_field.send_keys("xxx\n")

    time.sleep(1)

    time.sleep(5)
    cookies = browser.get_cookies()
    pickle.dump(cookies, open("cookies_bstn.pkl", "wb"))

    time.sleep(10)

def bstn_raffle(url):

    if __name__ == '__main__':

        browser = uc.Chrome()
        browser.get("https://bstn.com")

        time.sleep(5)

        try:
            cookies = pickle.load(open("cookies_bstn.pkl", "rb"))

            for cookie in cookies:
                cookie['domain'] = ".bstn.com"

                try:
                    browser.add_cookie(cookie)

                except Exception as e:
                    print(e)

        except:

            print("Keine cookies gefunden, logge ein und speichere cookies")
            bstn_login_and_cookie_save(browser)
            print("Cookies erstellt")

        browser.get(url)
        time.sleep(5)

        size = browser.find_element(By.XPATH, "//div[text()='44,5']")
        size.click()

        time.sleep(2)
        try:
            instagram = browser.find_element(By.ID, "instagram_name")
            instagram.send_keys("habinef")

            time.sleep(1)

            anwenden = browser.find_element(By.CLASS_NAME, "Button_secondary__XJln1.Button_button__Bq8yb")
            anwenden.click()
            time.sleep(1)
        except:
            time.sleep(1)

        checkbox = browser.find_element(By.XPATH, "/html/body/div[1]/main/div/div[2]/div[3]/div[3]/div[5]/div[2]/div/div/div/div/label/span")
        browser.execute_script("arguments[0].click()", checkbox)

        time.sleep(1)

        enter_raffle = browser.find_element(By.CLASS_NAME, "Button_primary__4kM2r.Button_button__Bq8yb")
        enter_raffle.click()

        time.sleep(10)

bstn_raffle("https://raffle.bstn.com/eu_de/jordan-air-jordan-2-retro-chicago-dx2454-106-0279577")

It doesnt matter if im visiting the raffle shoe page directly and log in or visit the main page > log in > got to the product page to sign in

Every time I press the enter raffle button i got a red message in the bottom that its not possible to sign in in this raffle. Cloudflare is detecting Selenium in any kind but dont know how to solve it.

I also figured out when im use this code here:

import undetected_chromedriver as uc
from selenium import webdriver
import time

browser = uc.Chrome()
browser.get("https://bot.sannysoft.com/")
time.sleep(1)
browser.switch_to.new_window('tab')
browser.get("https://raffle.bstn.com/eu_de/jordan-air-jordan-2-retro-chicago-dx2454-106-0279577")
time.sleep(1000)

and then try to sign in for the raffle manually i also get the red response message, but when i run this code here:

import undetected_chromedriver as uc
from selenium import webdriver
import time

browser = uc.Chrome()
browser.get("https://bot.sannysoft.com/")
time.sleep(10000)

and i open MANUAL a new tab, type in the product page for the raffle i can enter the raffle.

Anyone knows what is happening here and can help me? If you want to run this code, make sure to use the german language.


问:
How to publish Facebook post link+picture without this #100 error?
I have some working code which is posting in a facebook page feed a link + message/caption.
This is working fine.

When I add the picture field which is one image url in my domain I get response error

```<code>{
    "error": {
        "message": "(#100) Only owners of the URL have the ability to specify the picture, name, thumbnail or description params.",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "dfaafdadfs\/Ie6"
    }
}
</code>```

Let us consider the domain is example.com
I have already verified this domain in facebook business manager via DNS TXT entry lookup.
Also I have added the page app under this domain.

I don't know what is wrong here.

The failing request is something like this

```<code>POST /myPageId/feed?access_token=at&link=https://example.com/somepath&message=somemessage=picture=https://example.com/images/someimage.jpg
</code>```

If I remove picture parameter posting works fine without the error.

Any input here? The link without a picture does not get any attention or impressions so we want to publish the image as well.

PS:
The documentation in facebook is located at
https://developers.facebook.com/docs/graph-api/reference/v15.0/page/feed

and this section (no hash available so you need to scroll down to see the first screenshoot)

This second image was found at another page in fb site. Neither of them work with picture. Again I have added and verified my example.com example domain under business manager. Both the link + image url are from example.com domain.

Body:
I have some working code which is posting in a facebook page feed a link + message/caption.
This is working fine.

When I add the picture field which is one image url in my domain I get response error

{
    "error": {
        "message": "(#100) Only owners of the URL have the ability to specify the picture, name, thumbnail or description params.",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "dfaafdadfs\/Ie6"
    }
}

Let us consider the domain is example.com
I have already verified this domain in facebook business manager via DNS TXT entry lookup.
Also I have added the page app under this domain.

I don't know what is wrong here.

The failing request is something like this

POST /myPageId/feed?access_token=at&link=https://example.com/somepath&message=somemessage=picture=https://example.com/images/someimage.jpg

If I remove picture parameter posting works fine without the error.

Any input here? The link without a picture does not get any attention or impressions so we want to publish the image as well.

PS:
The documentation in facebook is located at
https://developers.facebook.com/docs/graph-api/reference/v15.0/page/feed

and this section (no hash available so you need to scroll down to see the first screenshoot)

This second image was found at another page in fb site. Neither of them work with picture. Again I have added and verified my example.com example domain under business manager. Both the link + image url are from example.com domain.


问:
AWS DataPipeline ShellCommandActivity alternative
What can be an equivalent service to AWS DataPipeline ShellCommandActivity? I want the activity to trigger a command on the local environment, can we achieve this using Step Functions? If not, what can be the other AWS solutions?</p>


问:
how to run Kafka command in gitlab CI/CD pipeline?
I am new to GitLab and Kafka and do not have more ideas on how to run the Kafka command using shell script through the GitLab CI/CD pipeline.

Following configuration I am using to achieve this but getting exceptions, is there anything I am missing or configured incorrectly? Please suggest

In .gitlab-ci.yml

```<code>run_kafka:
  image: confluentinc/cp-kafka
  script :
       - . demo.sh
</code>```

In demo.sh

```<code>   kafka-consumer-groups --command-config ./config.properties --bootstrap-server "pkc-6ojv2.us-west4.gcp.confluent.cloud:9092" --group my-created-consumer-group --topic SampleTopic --reset-offsets --to-current
</code>```

In config.properties

```<code>bootstrap.servers=pkc-confluent.cloud:9092
ssl.endpoint.identification.algorithm=https
security.protocol=SASL_SSL
sasl.mechanism=PLAIN
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="" password="";
</code>```

exception getting when pipeline is running

```<code>Error: Executing consumer group command failed due to org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment. Call: describeGroups(api=FIND_COORDINATOR)
 java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment. Call: describeGroups(api=FIND_COORDINATOR)
    at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
    at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:165)
    at kafka.admin.ConsumerGroupCommand$ConsumerGroupService.$anonfun$resetOffsets$1(ConsumerGroupCommand.scala:434)
    at scala.collection.IterableOnceOps.foldLeft(IterableOnce.scala:675)
    at scala.collection.IterableOnceOps.foldLeft$(IterableOnce.scala:669)
    at scala.collection.AbstractIterable.foldLeft(Iterable.scala:933)
    at kafka.admin.ConsumerGroupCommand$ConsumerGroupService.resetOffsets(ConsumerGroupCommand.scala:432)
    at kafka.admin.ConsumerGroupCommand$.run(ConsumerGroupCommand.scala:76)
    at kafka.admin.ConsumerGroupCommand$.main(ConsumerGroupCommand.scala:59)
    at kafka.admin.ConsumerGroupCommand.main(ConsumerGroupCommand.scala)
 Caused by: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment. Call: describeGroups(api=FIND_COORDINATOR)
</code>```

Body:
I am new to GitLab and Kafka and do not have more ideas on how to run the Kafka command using shell script through the GitLab CI/CD pipeline.

Following configuration I am using to achieve this but getting exceptions, is there anything I am missing or configured incorrectly? Please suggest

In .gitlab-ci.yml

run_kafka:
  image: confluentinc/cp-kafka
  script :
       - . demo.sh

In demo.sh

   kafka-consumer-groups --command-config ./config.properties --bootstrap-server "pkc-6ojv2.us-west4.gcp.confluent.cloud:9092" --group my-created-consumer-group --topic SampleTopic --reset-offsets --to-current

In config.properties

bootstrap.servers=pkc-confluent.cloud:9092
ssl.endpoint.identification.algorithm=https
security.protocol=SASL_SSL
sasl.mechanism=PLAIN
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="" password="";

exception getting when pipeline is running

Error: Executing consumer group command failed due to org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment. Call: describeGroups(api=FIND_COORDINATOR)
 java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment. Call: describeGroups(api=FIND_COORDINATOR)
    at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
    at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:165)
    at kafka.admin.ConsumerGroupCommand$ConsumerGroupService.$anonfun$resetOffsets$1(ConsumerGroupCommand.scala:434)
    at scala.collection.IterableOnceOps.foldLeft(IterableOnce.scala:675)
    at scala.collection.IterableOnceOps.foldLeft$(IterableOnce.scala:669)
    at scala.collection.AbstractIterable.foldLeft(Iterable.scala:933)
    at kafka.admin.ConsumerGroupCommand$ConsumerGroupService.resetOffsets(ConsumerGroupCommand.scala:432)
    at kafka.admin.ConsumerGroupCommand$.run(ConsumerGroupCommand.scala:76)
    at kafka.admin.ConsumerGroupCommand$.main(ConsumerGroupCommand.scala:59)
    at kafka.admin.ConsumerGroupCommand.main(ConsumerGroupCommand.scala)
 Caused by: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment. Call: describeGroups(api=FIND_COORDINATOR)


问:
Can I show the source code of a Python file with extension pyd?
Can I show the source code of a Python file with extension pyd? Or is there a way to protect your code to make anyone unable to show your code?

You can uncompile the pyc code in Python using this tool uncompyle6 and show the source code of the pyc file.

But what about pyd files? Can I do the same thing?