问:
Error: no adapter attached in Kotlin with RecyclerView
I have an error telling me that my adapter is not attached anywhere. Yet I initialize it well in the mainActivity, so I don't understand my mistake. Nothing appears in my list.

Here is my code below (hope you see where I made a mistake thanks in advance):

MainActivity :

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)

        binding.rvMangaList.layoutManager = LinearLayoutManager(this)
        binding.rvMangaList.setHasFixedSize(true)
        getMangaData { mangas : List<Manga> ->
            binding.rvMangaList.adapter = MangaAdapter(mangas)
        }

        setContentView(binding.root)

    }

    private fun getMangaData(callback: (List<Manga>) -> Unit) {
        val retrofit = Retrofit.Builder()
            .baseUrl("https://kitsu.io/api/edge/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val apiService = retrofit.create(WebServiceInterface::class.java)
        apiService.getListTrendingManga().enqueue(object: Callback<MangaData>{
            override fun onResponse(call: Call<MangaData>, response: Response<MangaData>) {
                return callback(response.body()!!.mangas)
            }

            override fun onFailure(call: Call<MangaData>, t: Throwable) {
                Log.d("ERR", t.message!!)
            }

        })
    }
}```
</div>
</div>
</p>
<p>My Adapter :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class MangaAdapter(
    private val mangas: List<Manga>
): RecyclerView.Adapter<MangaAdapter.MangaViewHolder>(){

    class MangaViewHolder(mangaItemBinding: MangaItemBinding): RecyclerView.ViewHolder(mangaItemBinding.root){
        private val binding = mangaItemBinding
        fun bindManga(manga: Manga) {
            binding.mangaTitle.text = manga.titles.titleEnJp
            binding.startDate.text = manga.startDate
            //Picasso.get().load(manga.posterImage.imageTiny).into(binding.mangaImage)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MangaViewHolder {
        val mangaItemBinding = MangaItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MangaViewHolder(mangaItemBinding)
    }

    override fun onBindViewHolder(holder: MangaViewHolder, position: Int) {
        holder.bindManga(mangas[position])
    }

    override fun getItemCount(): Int {
        return mangas.size
    }
}</code>```

答:
move this line
setContentView(binding.root)
under
 binding = ActivityMainBinding.inflate(layoutInflater)

Body:
I have an error telling me that my adapter is not attached anywhere. Yet I initialize it well in the mainActivity, so I don't understand my mistake. Nothing appears in my list.

Here is my code below (hope you see where I made a mistake thanks in advance):

MainActivity :

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)

        binding.rvMangaList.layoutManager = LinearLayoutManager(this)
        binding.rvMangaList.setHasFixedSize(true)
        getMangaData { mangas : List<Manga> ->
            binding.rvMangaList.adapter = MangaAdapter(mangas)
        }

        setContentView(binding.root)

    }

    private fun getMangaData(callback: (List<Manga>) -> Unit) {
        val retrofit = Retrofit.Builder()
            .baseUrl("https://kitsu.io/api/edge/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val apiService = retrofit.create(WebServiceInterface::class.java)
        apiService.getListTrendingManga().enqueue(object: Callback<MangaData>{
            override fun onResponse(call: Call<MangaData>, response: Response<MangaData>) {
                return callback(response.body()!!.mangas)
            }

            override fun onFailure(call: Call<MangaData>, t: Throwable) {
                Log.d("ERR", t.message!!)
            }

        })
    }
}

My Adapter :

class MangaAdapter(
    private val mangas: List<Manga>
): RecyclerView.Adapter<MangaAdapter.MangaViewHolder>(){

    class MangaViewHolder(mangaItemBinding: MangaItemBinding): RecyclerView.ViewHolder(mangaItemBinding.root){
        private val binding = mangaItemBinding
        fun bindManga(manga: Manga) {
            binding.mangaTitle.text = manga.titles.titleEnJp
            binding.startDate.text = manga.startDate
            //Picasso.get().load(manga.posterImage.imageTiny).into(binding.mangaImage)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MangaViewHolder {
        val mangaItemBinding = MangaItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MangaViewHolder(mangaItemBinding)
    }

    override fun onBindViewHolder(holder: MangaViewHolder, position: Int) {
        holder.bindManga(mangas[position])
    }

    override fun getItemCount(): Int {
        return mangas.size
    }
}


来源: stackexchange

问:
Cannot export Interface in Typescirpt - the requested module does not provide an export named Settings
I am trying to export/import an interface in Typescript but I am getting this error, I am not sure what I am doing wrong here

Uncaught SyntaxError: The requested module '/src/types/settings.ts' does not provide an export named 'Settings'

In my types/settings.ts I have this

```<code>export interface Settings {
    activeUser: number
}
</code>```

And I import it like this

```<code>import { Settings } from '@/types/settings'
</code>```

And here is my tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "esnext",
    "baseUrl": "./src/",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "paths": {
      "@/*": ["src/*"],
    },
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "isolatedModules": false
  },

  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

</code>```

I am using Vue/Vite with Typescript

答:
It is weird that npm run build will work fine, but npm run dev will throw SyntaxError.

I was forced to use import type { ... which in consequence also required same touch for Ref from vue.

Workaround was posted on GitHub for Vite issue 731

ContentLicense: CC BY-SA 4.0

Body:
I am trying to export/import an interface in Typescript but I am getting this error, I am not sure what I am doing wrong here

Uncaught SyntaxError: The requested module '/src/types/settings.ts' does not provide an export named 'Settings'

In my types/settings.ts I have this

export interface Settings {
    activeUser: number
}

And I import it like this

import { Settings } from '@/types/settings'

And here is my tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "baseUrl": "./src/",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "paths": {
      "@/*": ["src/*"],
    },
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "isolatedModules": false
  },

  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

I am using Vue/Vite with Typescript


问:
Python: while followed by elif
I thought else if and elif are logically identical.

But when I try elif after while, I get a syntax error.

However, else is OK after while, as shown here (see comments A & B):

```<code>MENU_COMMANDS = {
'goal': 'the objective of the game is .... ',
'close': 'exit menu',
'menu': 'show all menu commands',
'quit': 'quit game' }

GAME_KEYBOARD = {
'1': 1,
'2': 2 }

def turn1():
key = input("Player 1, make your move")  # == 'goal'

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

# elif key not in GAME_KEYBOARD:  # why won't this work? :(    COMMENT B
#     print("invalid move")
#     return False
</code>```

Is this the only way to execute this logic, or is there a better one?

Thank you!

答:
For loop control, else is a special case vs standard conditional statement.

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.

https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

>>> c = 0
>>> while c < 10:
...    break
... else:
...    print("caught a break")
...
>>> while c < 10:
...    c+=2
... else:
...    print("no break")
...
no break
```

Title: Python: while followed by elif

Body:
I thought else if and elif are logically identical.

But when I try elif after while, I get a syntax error.

However, else is OK after while, as shown here (see comments A & B):

MENU_COMMANDS = {
'goal': 'the objective of the game is .... ',
'close': 'exit menu',
'menu': 'show all menu commands',
'quit': 'quit game' }

GAME_KEYBOARD = {
'1': 1,
'2': 2 }

def turn1():
key = input("Player 1, make your move")  # == 'goal'

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

# elif key not in GAME_KEYBOARD:  # why won't this work? :(    COMMENT B
#     print("invalid move")
#     return False

Is this the only way to execute this logic, or is there a better one?

Thank you!


问:
Shared Preferences on a Null Object Reference Android
I am new to android developing maybe its a silly question but please help me. I am getting this error while trying to save an int value.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

And here is my code

```<code>SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
String value = "com.example.app.value";
int i = prefs.getInt(value, 0);
</code>```

And for write

```<code>prefs.edit().putInt(number, i).apply();
</code>```

I just want to set a SharedPreferences and want to read it at the first and write it inside the Activity. How can I solve it?

EDIT

```<code>public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "myprefs";
public static final  String value = "key";

int i = sharedpreferences.getInt(value, 0);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
public void sendMessage(View view) {
    i += 1;
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putInt(value, i);
    editor.apply();
}
</code>```

I managed to save preferences with a different way but I couldn't manage to read it in MainActivity extends Activity class.

log :

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference

答:
In my case this was the issues :
https://stackoverflow.com/a/43160497/321015

I was calling shared prefereance before context was set. ideal way to call the context

newContextbase.getSharedPreferences(..

Body:
I am new to android developing maybe its a silly question but please help me. I am getting this error while trying to save an int value.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

And here is my code

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
String value = "com.example.app.value";
int i = prefs.getInt(value, 0);

And for write

prefs.edit().putInt(number, i).apply();

I just want to set a SharedPreferences and want to read it at the first and write it inside the Activity. How can I solve it?

EDIT

public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "myprefs";
public static final  String value = "key";

int i = sharedpreferences.getInt(value, 0);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
public void sendMessage(View view) {
    i += 1;
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putInt(value, i);
    editor.apply();
}

I managed to save preferences with a different way but I couldn't manage to read it in MainActivity extends Activity class.

log :

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference


问:
Improve execution time with Multithreading in python
How can I implement multithreading to make this process faster? The program generates 1million random numbers and writes them on a file. It takes just over 2 seconds, but I'm wondering if multithreading would make it any faster.</p>
```<code>import random
import time

startTime = time.time()

data = open("file2.txt", "a+")

for i in range(1000000):
  number = str(random.randint(1, 9999))
  data.write(number + '\n')
data.close()

executionTime = (time.time() - startTime)
print('Execution time in seconds: ', + str(executionTime))
</code>```

答:
The short answer: Not easily.

Here is an example of using a multiprocessing pool to speed up your code:

import random
import time
from multiprocessing import Pool

startTime = time.time()

def f(_):
    number = str(random.randint(1, 9999))
    data.write(number + '\n')

data = open("file2.txt", "a+")
with Pool() as p:
    p.map(f, range(1000000))
data.close()

executionTime = (time.time() - startTime)
print(f'Execution time in seconds: {executionTime})')
```
<p>Looks good? Wait! This is not a drop-in replacement as it lacks synchronization of the processes so not all 1000000 line will be written (some will be overwritten in the same buffer)!
See Python multiprocessing safely writing to a file</p>
<p>So we need to separate computing the numbers (in parallel) from writing them (in serial). We can do this as follows:</p>
<pre class="lang-py prettyprint-override"><code>import random
import time
from multiprocessing import Pool

startTime = time.time()

def f(_):
    return str(random.randint(1, 9999))

with Pool() as p:
    output = p.map(f, range(1000000))

with open("file2.txt", "a+") as data:
    data.write('\n'.join(output) + '\n')

executionTime = (time.time() - startTime)
print(f'Execution time in seconds: {executionTime})')

</code>```

With that fixed, note that this is not multithreading but uses multiple processes. You can change it to multithreading with a different pool object:

```<code>from multiprocessing.pool import ThreadPool as Pool
</code>```

On my system, I get from 1 second to 0.35 seconds with the processing pool. With the ThreadPool however it takes up to 2 seconds!

The reason is that Python's global interpreter lock prevents from multiple threads to process your task efficiently, see What is the global interpreter lock (GIL) in CPython?

To conclude, multithreading is not always the right answer:

In your scenario, one limit is the file access, only one thread can write to the file, or you would need to introduce locking, making any performance gain moot

Also in Python multithreading is only suitable for specific tasks, e.g. long computations that happen in a library below python and can therefore run in parallel. In your scenario, the overhead of multithreading negates the small potential for a performance benefit.

The upside: Yes, with multiprocessing instead of multithreading I got a 3x speedup on my system.

Body:
How can I implement multithreading to make this process faster? The program generates 1million random numbers and writes them on a file. It takes just over 2 seconds, but I'm wondering if multithreading would make it any faster.

import random
import time

startTime = time.time()

data = open("file2.txt", "a+")

for i in range(1000000):
  number = str(random.randint(1, 9999))
  data.write(number + '\n')
data.close()

executionTime = (time.time() - startTime)
print('Execution time in seconds: ', + str(executionTime))

Body:
The short answer: Not easily.

Here is an example of using a multiprocessing pool to speed up your code:

import random
import time
from multiprocessing import Pool

startTime = time.time()

def f(_):
    number = str(random.randint(1, 9999))
    data.write(number + '\n')

data = open("file2.txt", "a+")
with Pool() as p:
    p.map(f, range(1000000))
data.close()

executionTime = (time.time() - startTime)
print(f'Execution time in seconds: {executionTime})')

Looks good? Wait! This is not a drop-in replacement as it lacks synchronization of the processes so not all 1000000 line will be written (some will be overwritten in the same buffer)!
See Python multiprocessing safely writing to a file

So we need to separate computing the numbers (in parallel) from writing them (in serial). We can do this as follows:

import random
import time
from multiprocessing import Pool

startTime = time.time()

def f(_):
    return str(random.randint(1, 9999))

with Pool() as p:
    output = p.map(f, range(1000000))

with open("file2.txt", "a+") as data:
    data.write('\n'.join(output) + '\n')

executionTime = (time.time() - startTime)
print(f'Execution time in seconds: {executionTime})')

With that fixed, note that this is not multithreading but uses multiple processes. You can change it to multithreading with a different pool object:

from multiprocessing.pool import ThreadPool as Pool

On my system, I get from 1 second to 0.35 seconds with the processing pool. With the ThreadPool however it takes up to 2 seconds!

The reason is that Python's global interpreter lock prevents from multiple threads to process your task efficiently, see What is the global interpreter lock (GIL) in CPython?

To conclude, multithreading is not always the right answer:

In your scenario, one limit is the file access, only one thread can write to the file, or you would need to introduce locking, making any performance gain moot

Also in Python multithreading is only suitable for specific tasks, e.g. long computations that happen in a library below python and can therefore run in parallel. In your scenario, the overhead of multithreading negates the small potential for a performance benefit.

The upside: Yes, with multiprocessing instead of multithreading I got a 3x speedup on my system.


问:
Beautiful soup returns empty while using class name to filter datas
Im trying to retrieve the product names, weight and price in a list from the following site.

https://www.licious.in/seafood

my code to find the products list :

```<code>  import requests
  from bs4 import BeautifulSoup

  URL = 'https://www.licious.in/seafood'
  r = requests.get(URL)
  soup = BeautifulSoup(r.content, 'lxml')

  productlist = soup.find_all('div', class_="card")

  productlinks = []

  for card in productlist:
        for link in card.find_all('a', href=True):
  print(link['href'])
</code>```

Can I use css selector for the product prices and product weight ?

答:
I see several issues here:

Missing indentation

Product images you are trying to get with soup.find_all("div", {"class": "product_image"}) are img elements, not div

img1 object received by item.find("img") is not printable.

This should work better:

import requests,
from bs4 import BeautifulSoup

URL = 'https://www.licious.in/seafood'
r = requests.get(URL)
soup = BeautifulSoup(r.text)
product_list = soup.find_all("div", {"class": "item-details"})

for item in product_list:

    product_names = item.find_all("div", {"class":  "item-title"})
# I see no point where detail_link_h2, detail_link_h3 and detail_link_h4 are defined so this will not work
#print(detail_link_h2 + ", " + detail_link_h3 + ", " + detail_link_h4)

product_images = soup.find_all("img", {"class": "product_image"})

for image in product_images:

    img1 = image.find("img")
#    print(img1)
```

Body:
Im trying to retrieve the product names, weight and price in a list from the following site.

https://www.licious.in/seafood

my code to find the products list :

  import requests
  from bs4 import BeautifulSoup

  URL = 'https://www.licious.in/seafood'
  r = requests.get(URL)
  soup = BeautifulSoup(r.content, 'lxml')

  productlist = soup.find_all('div', class_="card")

  productlinks = []

  for card in productlist:
        for link in card.find_all('a', href=True):
  print(link['href'])

Can I use css selector for the product prices and product weight ?


问:
Bootstrap carousel & Google Font Issues
I know this has been asked many times, but I still cannot seem to fix my code. As you can see, I am copied the code directly from bootstrap, and I was able to get my buttons to appear, but they are not activating. Also, google fonts was directly imported, but it too is not changing my fonts as it should. It is remaining as default.

#title {
  background-color: #FF4C68;
  color: WHITE;
}
.container-fluid{
  padding: 3% 15%;
}
/* H1 FONT FAMILY NOT WORKING */
h1 {
  font-family: "Montserrat-Black";
  font-size: 3.5rem;
  line-height: 1.5;
}
h2 {
  font-family: "Montserrat-Bold";
  font-size: 3rem;
  line-height: 1.5;
}
h3{
  font-family: "Montserrat-Bold";
  font-size: 1.5rem;
}
p{
  color: #8F8F8F;
}
body {
  font-family: "Montserrat";
}
/* NAVIGATION BAR */

.navbar {
  padding-bottom: 4.5rem;
}

.navbar-brand {
  font-family: 'Ubuntu';
  font-size: 2.5rem;
  font-weight: bold;
  color: yellow;
}

.nav-item {
  padding: 0 18px;
}

.nav-link {
  font-size: 1.2rem;
  font-family: "Montserrat-Light";
}

/* DOWNLOAD BUTTONS */
.download-button {
  margin: 5% 3% 5%;
}

/* TITLE IMAGE */
.title-image {
  width: 60%;
  transform: rotate(45deg);
}

/* FEATURES SECTION */
#features {
  padding: 7% 15%;
  text-align: center;
  padding: 5%;
}
/* CHANGE PADDING ABOVE IF FIRST BODY ISNT LOOKING RIGHT */

.icon{
  color: #ef8172;
  margin-bottom: 1rem;
}
.icon:hover{
  color: #ff4c68;
}

/* TESTIMONIAL SECTION */
#testimonials {
  text-align: center;
  background-color: #ef8172;
  color: #fff;
}
.testimonial-img{
  width: 10%;
  border-radius: 100%;
  margin: 20px;
}
#press {
  background-color: #ef8172;
  text-align: center;
  padding-bottom: 3%;
}
.press-logo {
  width: 15%;
  margin: 20px 20px 50px;
}
.carousel-item {
  padding: 7% 15%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>TinDog</title>

  <!-- BOOTSTRAP SCRIPTS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <!-- Google Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;900&family=Ubuntu&display=swap" rel="stylesheet">

  <!-- CSS STYLESHEETS -->
  <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Ubuntu&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/styles.css">

  <!-- C:\Users\dparr\Downloads\TinDog-Start-master\TinDog-Start-master\css\styles.css -->

  <!-- FONT AWESOME -->
  <script src="https://kit.fontawesome.com/849c3de797.js" crossorigin="anonymous"></script>

</head>

<body>

  <section id="title">
    <div class="container-fluid">

      <!-- Nav Bar -->
      <nav class="navbar navbar-expand-lg navbar-dark">
        Tindog
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              Contact
            </li>
            <li class="nav-item">
              Pricing
            </li>
            <li class="nav-item">
              Download
            </li>
          </ul>
        </div>

      </nav>

      <!-- Title -->

      <div class="row">
        <div class="col-lg-6">
          <h1>Meet new and interesting dogs nearby.</h1>
          <button type="button" class="btn btn-primary btn-lg download-button"><i class="fa-brands fa-apple"></i> Download</button>
          <button type="button" class="btn btn-outline-light btn-lg download-button"><i class="fa-brands fa-google-play"></i> Download</button>
        </div>

        <div class="col-lg-6">
          <img class="title-image" src="images/iphone6.png" alt="iphone-mockup">
        </div>
      </div>
  </section>

  <!-- Features -->

  <section id="features">

    <div class="row">
      <div class="feature-box col-lg-4">
        <i class="icon fa-solid fa-circle-check fa-4x"></i>
        <h3>Easy to use.</h3>
        <p>So easy to use, even your dog could do it.</p>
      </div>

      <div class="feature-box col-lg-4">
        <i class="icon fa-solid fa-bullseye fa-4x"></i>
        <h3>Elite Clientele</h3>
        <p>We have all the dogs, the greatest dogs.</p>
      </div>

      <div class="feature-box col-lg-4">
        <i class="icon fa-solid fa-heart fa-4x"></i>
        <h3>Guaranteed to work.</h3>
        <p>Find the love of your dog's life or your money back.</p>
      </div>
    </div>

  </section>

  <!-- Testimonials -->

  <section id="testimonials">

    <div id="#testimonial-carousel" class="carousel slide" data-bs-ride="false" data-pause="hover">
      <div class="carousel-inner">
        <div class="carousel-item active">
          <h2>I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.</h2>
          <img class="testimonial-img" src="images/dog-img.jpg" alt="dog-profile">
          <em>Pebbles, New York</em>
        </div>
        <div class="carousel-item">
          <h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2>
          <img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile">
          <em>Beverly, Illinois</em>
        </div>
      </div>
      <button class="carousel-control-prev" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
    </div>

  </section>

  <!-- Press -->

  <section id="press">
    <img class="press-logo" src="images/techcrunch.png" alt="tc-logo">
    <img class="press-logo" src="images/tnw.png" alt="tnw-logo">
    <img class="press-logo" src="images/bizinsider.png" alt="biz-insider-logo">
    <img class="press-logo" src="images/mashable.png" alt="mashable-logo">

  </section>

  <!-- Pricing -->

  <section id="pricing">

    <h2>A Plan for Every Dog's Needs</h2>
    <p>Simple and affordable price plans for your and your dog.</p>

    <h3>Chihuahua</h3>
    <h2>Free</h2>
    <p>5 Matches Per Day</p>
    <p>10 Messages Per Day</p>
    <p>Unlimited App Usage</p>
    <button type="button">Sign Up</button>

    <h3>Labrador</h3>
    <h2>$49 / mo</h2>
    <p>Unlimited Matches</p>
    <p>Unlimited Messages</p>
    <p>Unlimited App Usage</p>
    <button type="button">Sign Up</button>

    <h3>Mastiff</h3>
    <h2>$99 / mo</h2>
    <p>Pirority Listing</p>
    <p>Unlimited Matches</p>
    <p>Unlimited Messages</p>
    <p>Unlimited App Usage</p>
    <button type="button">Sign Up</button>

  </section>

  <!-- Call to Action -->

  <section id="cta">

    <h3>Find the True Love of Your Dog's Life Today.</h3>
    <button type="button">Download</button>
    <button type="button">Download</button>

  </section>

  <!-- Footer -->

  <footer id="footer">

    <p>© Copyright TinDog</p>

  </footer>

</body>

</html></code>```

答:
Remove # in the carousel ID id="testimonial-carousel" and everything will work
Also set the font style like this font-family: 'Montserrat', sans-serif;

/* TESTIMONIAL SECTION */
#testimonials {
  text-align: center;
  background-color: #ef8172;
  color: #fff;
}
.testimonial-img{
  width: 10%;
  border-radius: 100%;
  margin: 20px;
}
#press {
  background-color: #ef8172;
  text-align: center;
  padding-bottom: 3%;
}
.press-logo {
  width: 15%;
  margin: 20px 20px 50px;
}
.carousel-item {
  padding: 7% 15%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <!-- BOOTSTRAP SCRIPTS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <!-- FONT AWESOME -->
  <script src="https://kit.fontawesome.com/849c3de797.js" crossorigin="anonymous"></script>

</head>

<body>

  <!-- Testimonials -->

  <section id="testimonials">

    <div id="testimonial-carousel" class="carousel slide" data-bs-ride="false" data-pause="hover">
      <div class="carousel-inner">
        <div class="carousel-item active">
          <h2>I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.</h2>
          <img class="testimonial-img" src="images/dog-img.jpg" alt="dog-profile">
          <em>Pebbles, New York</em>
        </div>
        <div class="carousel-item">
          <h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2>
          <img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile">
          <em>Beverly, Illinois</em>
        </div>
      </div>
      <button class="carousel-control-prev" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
    </div>

  </section>

</body>

</html></code>```

Title: Bootstrap carousel & Google Font Issues

Body:
I know this has been asked many times, but I still cannot seem to fix my code. As you can see, I am copied the code directly from bootstrap, and I was able to get my buttons to appear, but they are not activating. Also, google fonts was directly imported, but it too is not changing my fonts as it should. It is remaining as default.

#title {
  background-color: #FF4C68;
  color: WHITE;
}
.container-fluid{
  padding: 3% 15%;
}
/* H1 FONT FAMILY NOT WORKING */
h1 {
  font-family: "Montserrat-Black";
  font-size: 3.5rem;
  line-height: 1.5;
}
h2 {
  font-family: "Montserrat-Bold";
  font-size: 3rem;
  line-height: 1.5;
}
h3{
  font-family: "Montserrat-Bold";
  font-size: 1.5rem;
}
p{
  color: #8F8F8F;
}
body {
  font-family: "Montserrat";
}
/* NAVIGATION BAR */

.navbar {
  padding-bottom: 4.5rem;
}

.navbar-brand {
  font-family: 'Ubuntu';
  font-size: 2.5rem;
  font-weight: bold;
  color: yellow;
}

.nav-item {
  padding: 0 18px;
}

.nav-link {
  font-size: 1.2rem;
  font-family: "Montserrat-Light";
}

/* DOWNLOAD BUTTONS */
.download-button {
  margin: 5% 3% 5%;
}

/* TITLE IMAGE */
.title-image {
  width: 60%;
  transform: rotate(45deg);
}

/* FEATURES SECTION */
#features {
  padding: 7% 15%;
  text-align: center;
  padding: 5%;
}
/* CHANGE PADDING ABOVE IF FIRST BODY ISNT LOOKING RIGHT */

.icon{
  color: #ef8172;
  margin-bottom: 1rem;
}
.icon:hover{
  color: #ff4c68;
}

/* TESTIMONIAL SECTION */
#testimonials {
  text-align: center;
  background-color: #ef8172;
  color: #fff;
}
.testimonial-img{
  width: 10%;
  border-radius: 100%;
  margin: 20px;
}
#press {
  background-color: #ef8172;
  text-align: center;
  padding-bottom: 3%;
}
.press-logo {
  width: 15%;
  margin: 20px 20px 50px;
}
.carousel-item {
  padding: 7% 15%;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>TinDog</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;900&family=Ubuntu&display=swap" rel="stylesheet">

  <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Ubuntu&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/styles.css">

        Tindog
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Contact

              Pricing

              Download

Meet new and interesting dogs nearby.

          <button type="button" class="btn btn-primary btn-lg download-button"> Download</button>
          <button type="button" class="btn btn-outline-light btn-lg download-button"> Download</button>

Easy to use.

So easy to use, even your dog could do it.

Elite Clientele

We have all the dogs, the greatest dogs.

Guaranteed to work.

Find the love of your dog's life or your money back.

I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.

          Pebbles, New York

My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.

          Beverly, Illinois

      <button class="carousel-control-prev" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="prev">

        Previous
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="next">

        Next
      </button>

A Plan for Every Dog's Needs

Simple and affordable price plans for your and your dog.

Chihuahua

Free

5 Matches Per Day

10 Messages Per Day

Unlimited App Usage

    <button type="button">Sign Up</button>

Labrador

$49 / mo

Unlimited Matches

Unlimited Messages

Unlimited App Usage

    <button type="button">Sign Up</button>

Mastiff

$99 / mo

Pirority Listing

Unlimited Matches

Unlimited Messages

Unlimited App Usage

    <button type="button">Sign Up</button>

Find the True Love of Your Dog's Life Today.

    <button type="button">Download</button>
    <button type="button">Download</button>

© Copyright TinDog

Body:
Remove # in the carousel ID id="testimonial-carousel" and everything will work
Also set the font style like this font-family: 'Montserrat', sans-serif;

/* TESTIMONIAL SECTION */
#testimonials {
  text-align: center;
  background-color: #ef8172;
  color: #fff;
}
.testimonial-img{
  width: 10%;
  border-radius: 100%;
  margin: 20px;
}
#press {
  background-color: #ef8172;
  text-align: center;
  padding-bottom: 3%;
}
.press-logo {
  width: 15%;
  margin: 20px 20px 50px;
}
.carousel-item {
  padding: 7% 15%;
}

<!DOCTYPE html>
<html>

<head>
  <!-- BOOTSTRAP SCRIPTS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <!-- FONT AWESOME -->
  <script src="https://kit.fontawesome.com/849c3de797.js" crossorigin="anonymous"></script>

</head>

<body>

  <!-- Testimonials -->

  <section id="testimonials">

    <div id="testimonial-carousel" class="carousel slide" data-bs-ride="false" data-pause="hover">
      <div class="carousel-inner">
        <div class="carousel-item active">
          <h2>I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.</h2>
          <img class="testimonial-img" src="images/dog-img.jpg" alt="dog-profile">
          <em>Pebbles, New York</em>
        </div>
        <div class="carousel-item">
          <h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2>
          <img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile">
          <em>Beverly, Illinois</em>
        </div>
      </div>
      <button class="carousel-control-prev" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
    </div>

  </section>

</body>

</html>


问:
Can not use restored data on new portainer (docker swarm): Environment is unreachable
I have a single server with Portainer (docker swarm, one simple node). I am going to migrate it to another server so I took a backup and restored it successfully but can not connect to the new primary environment. It says:

Failed loading environment Environment is unreachable. Connect to
another swarm manager.

There is no special configuration I just used 'swarm init' during Portainer installation process. I generally know it is a problem with the manager and agent on the new server but I don't know what should I do to make it work.

Here is the log:
dial tcp: lookup tasks.agent on 172.26.0.2:53: no such host"

答: The problem was fixed by transferring 'volumes' folder to the new server!</p>


问:
What is the time complexity of concatenating two vectors in scala?
Given two vectors of length n and m respectively, what is the time complexity of concatenating them using the ++ operator? For lists, I believe it's O(n+m). Is it any better for vectors? Does any collection in scala have a better concatenation time than O(n+m)?
Thanks for your help. :)

答:
Adding a vector of length m to a vector of length n (len_n ++ len_m) takes O(m).

You can find the performance characteristics of each data structure on this page.

ContentLicense: CC BY-SA 3.0


问:
How to add a row to a dataframe modifying only some columns
In order to prepare the data for plotting I need to add a new row to the data:

I have this dataframe:

```<code>df <- data.frame(
  test_id = c(1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1),
  region = c("A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2)
)

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
</code>```

I would like to add a row to this dataframe so the desired output should be:

```<code>  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75
</code>```

As you can see: column 1 and column 2 are the same value, column 3 changed to 'mean' and column 4 is the mean of row1-4.

I have tried to use add_row from tibble package which gives an error:

```<code>library(dpylr)
library(tibble)

df %>%
  mutate(mean1 = mean(test_value)) %>%
  add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))

Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found
</code>```

答:
If we want to use the OP's method without calling the .$, use exposition pipe (%$%) from magrittr.  This have similarity using the with (from base R)

```<code>library(magrittr)
library(dplyr)
df %$%
  add_row(., test_id = first(test_id), test_nr = first(test_nr),
    region = "mean", test_value = mean(test_value))
  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75
</code>```

Body:
In order to prepare the data for plotting I need to add a new row to the data:

I have this dataframe:

df <- data.frame(
  test_id = c(1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1),
  region = c("A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2)
)

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2

I would like to add a row to this dataframe so the desired output should be:

  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75

As you can see: column 1 and column 2 are the same value, column 3 changed to 'mean' and column 4 is the mean of row1-4.

I have tried to use add_row from tibble package which gives an error:

library(dpylr)
library(tibble)

df %>%
  mutate(mean1 = mean(test_value)) %>%
  add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))

Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found

Body:
If we want to use the OP's method without calling the .$, use exposition pipe (%$%) from magrittr.  This have similarity using the with (from base R)

library(magrittr)
library(dplyr)
df %$%
  add_row(., test_id = first(test_id), test_nr = first(test_nr),
    region = "mean", test_value = mean(test_value))
  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75


问:
faster membership testing in python than set()
I have to check presence of millions of elements (20-30 letters str) in the list containing 10-100k of those elements. Is there faster way of doing that in python than set() ?

```<code>import sys
#load ids
ids = set( x.strip() for x in open(idfile) )

for line in sys.stdin:
    id=line.strip()
    if id in ids:
        #print fastq
        print id
        #update ids
        ids.remove( id )
</code>```

答:
set is as fast as it gets.

However, if you rewrite your code to create the set once, and not change it, you can use the frozenset built-in type. It's exactly the same except immutable.

If you're still having speed problems, you need to speed your program up in other ways, such as by using PyPy instead of cPython.

Body:
I have to check presence of millions of elements (20-30 letters str) in the list containing 10-100k of those elements. Is there faster way of doing that in python than set() ?

import sys
#load ids
ids = set( x.strip() for x in open(idfile) )

for line in sys.stdin:
    id=line.strip()
    if id in ids:
        #print fastq
        print id
        #update ids
        ids.remove( id )


问:
Why my web traffic is redirected via IP 10.0.0.11 address on my Mac?
I know nothing about networking. so I need serious help here. I was on a Zoom call with my mentor and we were talking about the difference between HTTP, HTTP1, and HTTP2. Then he noticed that even websites which are supposed to use HTTP1 all of them were showing as if they are using HTTP2.

He mentioned possible problems are:

I'm using VPN

or my web traffic is redirected via a Proxy server. (which I'm not since I work from home via my wifi provided to me via fiber optic cable)

I suspect that there is some kind of proxy malware on my laptop. Can anybody tell me how can i detect any possible malware and find out in general what is wrong? (if anything is wrong at all)

Thanks in advance.

答:
The range from 10.0.0.0 to 10.255.255.255 is one of the private IP Ranges and as you are using wifi its normally assigned by your wifi-router/accesspoint to your computer using dhcp.

But seriously, a professor who thinks he is capable talking about http(x) should know the very basics of the protocol stack. If he doesn't know such simple things, you better get someone better.


问:
Pygame window crashing on run
I am trying to make a hangman game that has a window which shows the hangman being drawn every time you make a wrong guess.. i am using pygame library for it but when i run the program it opens the window and then crashes. How to fix?

Here's the code:

```<code>import pygame

def wait():
    result=None
    import msvcrt
    result=msvcrt.getch()
    return result

window=pygame.display.set_mode((600, 600))
window.fill((0, 0, 0))

running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    if running==False:
        pygame.quit()

    print ("Press any key to start a game")
    wait()

    Wrong=0
    Word=list(input("Give the hidden word"))
    Hidden=[]
    Guess=input("Guess a letter or the word")

    for j in range(len(Word)):
        Hidden.append("_")

    if Guess in Word:
        for i in range(len(Word)):
            if Guess==Word[i]:
                Hidden.pop(i)
                Hidden.insert(i,Guess)
                print (Hidden)
    else:
        Wrong+=1

    if Wrong==1:
        White=pygame.draw.circle(window, (255, 255, 255),[300, 80], 50, 3)
        pygame.display.update()
    elif Wrong==2:
        Blue=pygame.draw.line(window, (0, 0, 255),[300, 130],[300, 350], 3)
        pygame.display.update()
    elif Wrong==3:
        Green=pygame.draw.line(window, (0, 255, 0),[300, 200],[400, 300], 3)
        pygame.display.update()
    elif Wrong==4:
        Red=pygame.draw.line(window, (255, 0, 0),[300, 200],[200, 300], 3)
        pygame.display.update()
    elif Wrong==5:
        Cyan=pygame.draw.line(window, (0, 255, 255),[300, 350],[200, 500], 3)
        pygame.display.update()
    elif Wrong==6:
        Yellow=pygame.draw.line(window, (0, 255, 255),[300, 350],[400, 500], 3)
        pygame.display.update()
    elif Wrong==7:
        print ("You Lost")
</code>```

答:
Every pygame program needs pygame.init() at the beginning

Use pygame.display.update() only once at the end of the program

Your program freezes because input() breaks the main loop of your program

Pygame start file:

```<code>import pygame
from sys import exit

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    #Your code...

    pygame.display.update()
    clock.tick(FPS)
</code>```

You can solve this by adding an input box to the pygame window: https://stackoverflow.com/a/46390412/15500012

I hope it will help you, Adam

Title: Pygame window crashing on run

Body:
I am trying to make a hangman game that has a window which shows the hangman being drawn every time you make a wrong guess.. i am using pygame library for it but when i run the program it opens the window and then crashes. How to fix?

Here's the code:

import pygame

def wait():
    result=None
    import msvcrt
    result=msvcrt.getch()
    return result

window=pygame.display.set_mode((600, 600))
window.fill((0, 0, 0))

running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    if running==False:
        pygame.quit()

    print ("Press any key to start a game")
    wait()

    Wrong=0
    Word=list(input("Give the hidden word"))
    Hidden=[]
    Guess=input("Guess a letter or the word")

    for j in range(len(Word)):
        Hidden.append("_")

    if Guess in Word:
        for i in range(len(Word)):
            if Guess==Word[i]:
                Hidden.pop(i)
                Hidden.insert(i,Guess)
                print (Hidden)
    else:
        Wrong+=1

    if Wrong==1:
        White=pygame.draw.circle(window, (255, 255, 255),[300, 80], 50, 3)
        pygame.display.update()
    elif Wrong==2:
        Blue=pygame.draw.line(window, (0, 0, 255),[300, 130],[300, 350], 3)
        pygame.display.update()
    elif Wrong==3:
        Green=pygame.draw.line(window, (0, 255, 0),[300, 200],[400, 300], 3)
        pygame.display.update()
    elif Wrong==4:
        Red=pygame.draw.line(window, (255, 0, 0),[300, 200],[200, 300], 3)
        pygame.display.update()
    elif Wrong==5:
        Cyan=pygame.draw.line(window, (0, 255, 255),[300, 350],[200, 500], 3)
        pygame.display.update()
    elif Wrong==6:
        Yellow=pygame.draw.line(window, (0, 255, 255),[300, 350],[400, 500], 3)
        pygame.display.update()
    elif Wrong==7:
        print ("You Lost")

Body:
Every pygame program needs pygame.init() at the beginning

Use pygame.display.update() only once at the end of the program

Your program freezes because input() breaks the main loop of your program

Pygame start file:

import pygame
from sys import exit

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    #Your code...

    pygame.display.update()
    clock.tick(FPS)

You can solve this by adding an input box to the pygame window: https://stackoverflow.com/a/46390412/15500012

I hope it will help you, Adam


问:
how to extract data from an xml file using plutil?
This is my file.xml

```<code><key>FairPlayKeyData</key>
    <data>
    LS0tLS1CRUdJTiBD....S0tCg==
    </data>
</code>```

I want the output to be: LS0tLS1CRUdJTiBD....S0tCg==

i try: plutil -key FairPlayKeyData file.xml

but output: unrecognized option: -key

答:
Use the -extract option:

-extract keypath fmt

outputs the value at 'keypath' in the property list as a new plist of type 'fmt'

fmt is one of: xml1 binary1 json raw

an additional "-expect type" option can be provided to test that the value at the specified keypath is of the specified "type", which can be one of: bool, integer, float, string, date, data, dictionary, array

```<code>plutil -extract FairPlayKeyData raw file.xml
</code>```

Body:
This is my file.xml

<key>FairPlayKeyData</key>
    <data>
    LS0tLS1CRUdJTiBD....S0tCg==
    </data>

I want the output to be: LS0tLS1CRUdJTiBD....S0tCg==

i try: plutil -key FairPlayKeyData file.xml

but output: unrecognized option: -key

Body:
Use the -extract option:

-extract keypath fmt

outputs the value at 'keypath' in the property list as a new plist of type 'fmt'

fmt is one of: xml1 binary1 json raw

an additional "-expect type" option can be provided to test that the value at the specified keypath is of the specified "type", which can be one of: bool, integer, float, string, date, data, dictionary, array

plutil -extract FairPlayKeyData raw file.xml


问:
Fluent Nhibernate problem
I have this in my entity:

```<code>public virtual Iesi.Collections.Generic.ISet<long> Blas { get; set; }
</code>```

and this for my mapping:

```<code>mapping.HasMany(x => x.Blas).AsSet().Element("Value", m => m.Type<long>());
</code>```

This creates the relevant tables and I add data like this:

```<code>X.Blas = new Iesi.Collections.Generic.HashedSet<long>();
X.Blas.Add(some_long);
</code>```

This adds values to the object but the values in Blas are never persisted (everything else of X is).

Can anyone see anything wrong?

Thanks.

Christian

答:
Try adding a cascade setting.

```<code>mapping.HasMany(x => x.Blas).AsSet()
       .Element("Value", m => m.Type<long>())
       .Cascade.AllDeleteOrphan();
</code>```

Also you should just be able to use ICollection and a regular Hashset instead of Iesi. Provided you're using at least version 3 (it might work with 2.1.2 or higher as well)

Title: Fluent Nhibernate problem

Body:
I have this in my entity:

public virtual Iesi.Collections.Generic.ISet<long> Blas { get; set; }

and this for my mapping:

mapping.HasMany(x => x.Blas).AsSet().Element("Value", m => m.Type<long>());

This creates the relevant tables and I add data like this:

X.Blas = new Iesi.Collections.Generic.HashedSet<long>();
X.Blas.Add(some_long);

This adds values to the object but the values in Blas are never persisted (everything else of X is).

Can anyone see anything wrong?

Thanks.

Christian

Body:
Try adding a cascade setting.

mapping.HasMany(x => x.Blas).AsSet()
       .Element("Value", m => m.Type<long>())
       .Cascade.AllDeleteOrphan();

Also you should just be able to use ICollection and a regular Hashset instead of Iesi. Provided you're using at least version 3 (it might work with 2.1.2 or higher as well)


问:
Create objects of the same class with different variables
I would like to know if it is possible to create objects of the same class with different variables each time in Java.

Example:

This method returns data from a URL with a JSON file and I would like to use it to create a post object.

```<code>ObjectMapper mapper = new ObjectMapper();

public Post getData(String ... url) throws StreamReadException, DatabindException, MalformedURLException, IOException {
    return mapper.readValue(new URL(url[0]), Post.class);
}
</code>```

But the .JSON may be:

```<code>{ "name": "Bob" }
</code>```

But also:

```<code>{ "color": "Red", "width": "200", "height": "150" }
</code>```

Or anything else.

答:
If Post is a subclass of Map or JsonNode, then yes, it can hold any key-value pairs.

If Post looks like this, then no, it's strictly defined as only having one field.

```<code>public class Post {
  String name;
}
</code>```

Body:
I would like to know if it is possible to create objects of the same class with different variables each time in Java.

Example:

This method returns data from a URL with a JSON file and I would like to use it to create a post object.

ObjectMapper mapper = new ObjectMapper();

public Post getData(String ... url) throws StreamReadException, DatabindException, MalformedURLException, IOException {
    return mapper.readValue(new URL(url[0]), Post.class);
}

But the .JSON may be:

{ "name": "Bob" }

But also:

{ "color": "Red", "width": "200", "height": "150" }

Or anything else.

Body:
If Post is a subclass of Map or JsonNode, then yes, it can hold any key-value pairs.

If Post looks like this, then no, it's strictly defined as only having one field.

public class Post {
  String name;
}


问:
PyUSB, No backend available. How to specify custom location of libusb?
System setup

M1 Mac

Brew installed libusb /opt/homebrew/Cellar/libusb/1.0.24/lib/libusb-1.0.0.dylib

Anacada python 3.10

The No backend available problem see be a known issue with newer python and ARM-based Macs. I am failing to arrive at a solution from that link.

I would like to place a copy of libusb in the project folder and specify that as the backend.

Question:
How do I specify the location of libusb-1.0.0.dylib in as a custom backend in find()?

```<code>>>> from usb.core import find
>>> f = find(find_all=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/vincentdavis/opt/anaconda3/envs/py310/lib/python3.10/site-packages/usb/core.py", line 1309, in find
    raise NoBackendError('No backend available')
usb.core.NoBackendError: No backend available
</code>```

I should be able to do something the code below based on this post LINK.

```<code>backend = usb.backend.libusb1.get_backend(find_library="/opt/homebrew/Cellar/libusb/1.0.24/lib/libusb-1.0.0.dylib")

f = find(backend=backend, find_all=True)
</code>```

答:
Solution:

```<code>import usb.core
import usb.backend.libusb1
backend = usb.backend.libusb1.get_backend(find_library=lambda x: "/usr/lib/libusb-1.0.so")
dev = usb.core.find(..., backend=backend)
</code>```

From: https://github.com/walac/pyusb/blob/master/docs/tutorial.rst

Alternative

Try putting instead the contents of /opt/homebrew/Cellar/libusb/1.0.24/lib/ into /usr/local/lib and it should work.

This is one of the paths searched by find_library() of the Python ctypes module on Mac OS (source: https://stackoverflow.com/a/31148541/18197137)

Body:
System setup

M1 Mac

Brew installed libusb /opt/homebrew/Cellar/libusb/1.0.24/lib/libusb-1.0.0.dylib

Anacada python 3.10

The No backend available problem see be a known issue with newer python and ARM-based Macs. I am failing to arrive at a solution from that link.

I would like to place a copy of libusb in the project folder and specify that as the backend.

Question:
How do I specify the location of libusb-1.0.0.dylib in as a custom backend in find()?

>>> from usb.core import find
>>> f = find(find_all=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/vincentdavis/opt/anaconda3/envs/py310/lib/python3.10/site-packages/usb/core.py", line 1309, in find
    raise NoBackendError('No backend available')
usb.core.NoBackendError: No backend available

I should be able to do something the code below based on this post LINK.

backend = usb.backend.libusb1.get_backend(find_library="/opt/homebrew/Cellar/libusb/1.0.24/lib/libusb-1.0.0.dylib")

f = find(backend=backend, find_all=True)

Body:
Solution:

import usb.core
import usb.backend.libusb1
backend = usb.backend.libusb1.get_backend(find_library=lambda x: "/usr/lib/libusb-1.0.so")
dev = usb.core.find(..., backend=backend)

From: https://github.com/walac/pyusb/blob/master/docs/tutorial.rst

Alternative

Try putting instead the contents of /opt/homebrew/Cellar/libusb/1.0.24/lib/ into /usr/local/lib and it should work.

This is one of the paths searched by find_library() of the Python ctypes module on Mac OS (source: https://stackoverflow.com/a/31148541/18197137)


问:
Linux server programming
I got this code from Andy Tanenbaum's book. I am trying to run it. It compiles and waits for connection. But when I type localhost:886, I see no effect either in the browser or the terminal. (It should echo a new connection string as per the code).

```<code>#define     SERVER_PORT         886     /* The port at which the server listens */
#define     BUF_SIZE        64032       /* The size of buffer for request and response */
#define     QUEUE_SIZE      10      /* Block transfer size */

int main (int argc, char* argv[]) {

    int     sock = 0, bnd = 0, lst = 0, fd = 0, sa = 0, bytes = 0, on = 1, conn_count = 0;
    char    buf[BUF_SIZE];
    struct  sockaddr_in channel;            /* IP address holder */

    /* The address structure that binds with the socket */

    memset (&channel, 0, sizeof(channel));

    channel.sin_family      =   AF_INET;
    channel.sin_addr.s_addr     =   htonl (INADDR_ANY);
    channel.sin_port        =   htons (SERVER_PORT);

    /* Parital opening of the socket, while waiting for connection */

    sock                =   socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); /* Creates a new socket */
    if (sock < 0)
        printf ("Partial opening of the socket failed! Error: %d", sock);

    setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));

    bnd             =   bind (sock, (struct sockaddr *) &channel, sizeof(channel));
    if (bnd < 0)
        printf ("Binding failure! Error: %d", bnd);

    lst             =   listen (sock, QUEUE_SIZE);
    if (lst < 0)
        printf ("Unable to listen on the socket! Error: %d", lst);

    /* The socket has been set-up. Wait for the connection and process it. */

    while (1) {

        conn_count      +=  1;
        printf ("Received connection: %d", conn_count);
        sa          =   accept (sock, 0, 0);
        if (sa < 0)
            puts ("Unable to accept the socket opened for connection.");

        read (sa, buf, BUF_SIZE);

        puts (buf);     /* Output the string to the screen */

        close (sa);
    }
}
</code>```

答:
Rather than using printf() and stdout, try changing all your outputs to fprintf() and stderr which has no buffering ... I would do the same for the error messages as well so that they are output immediately when called and not buffered by stdout.

Finally, if you want to see what the error messages mean, use strerror() with the error number.  So you could so something like:

```<code>if (bnd < 0)
{
    fprintf(stderr, "Binding failure! Error: %s", strerror(bnd));
    exit(1);
}
</code>```

Make sure for strerror() you also do an include<string.h> somewhere at the start of your code module.

Title: Linux server programming

Body:
I got this code from Andy Tanenbaum's book. I am trying to run it. It compiles and waits for connection. But when I type localhost:886, I see no effect either in the browser or the terminal. (It should echo a new connection string as per the code).

#define     SERVER_PORT         886     /* The port at which the server listens */
#define     BUF_SIZE        64032       /* The size of buffer for request and response */
#define     QUEUE_SIZE      10      /* Block transfer size */

int main (int argc, char* argv[]) {

    int     sock = 0, bnd = 0, lst = 0, fd = 0, sa = 0, bytes = 0, on = 1, conn_count = 0;
    char    buf[BUF_SIZE];
    struct  sockaddr_in channel;            /* IP address holder */

    /* The address structure that binds with the socket */

    memset (&channel, 0, sizeof(channel));

    channel.sin_family      =   AF_INET;
    channel.sin_addr.s_addr     =   htonl (INADDR_ANY);
    channel.sin_port        =   htons (SERVER_PORT);

    /* Parital opening of the socket, while waiting for connection */

    sock                =   socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); /* Creates a new socket */
    if (sock < 0)
        printf ("Partial opening of the socket failed! Error: %d", sock);

    setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));

    bnd             =   bind (sock, (struct sockaddr *) &channel, sizeof(channel));
    if (bnd < 0)
        printf ("Binding failure! Error: %d", bnd);

    lst             =   listen (sock, QUEUE_SIZE);
    if (lst < 0)
        printf ("Unable to listen on the socket! Error: %d", lst);

    /* The socket has been set-up. Wait for the connection and process it. */

    while (1) {

        conn_count      +=  1;
        printf ("Received connection: %d", conn_count);
        sa          =   accept (sock, 0, 0);
        if (sa < 0)
            puts ("Unable to accept the socket opened for connection.");

        read (sa, buf, BUF_SIZE);

        puts (buf);     /* Output the string to the screen */

        close (sa);
    }
}

Body:
Rather than using printf() and stdout, try changing all your outputs to fprintf() and stderr which has no buffering ... I would do the same for the error messages as well so that they are output immediately when called and not buffered by stdout.

Finally, if you want to see what the error messages mean, use strerror() with the error number.  So you could so something like:

if (bnd < 0)
{
    fprintf(stderr, "Binding failure! Error: %s", strerror(bnd));
    exit(1);
}

Make sure for strerror() you also do an include<string.h> somewhere at the start of your code module.


问:
How do I count the NaN values in a column in pandas DataFrame?
I want to find the number of NaN in each column of my data.

答:
You can use df.iteritems() to loop over the data frame. Set a conditional within a for loop to calculate the NaN values percent for each column, and drop those that contain a value of NaNs over your set threshold:</p>
```<code>for col, val in df.iteritems():
    if (df[col].isnull().sum() / len(val) * 100) > 30:
        df.drop(columns=col, inplace=True)
</code>```

Body:
You can use df.iteritems() to loop over the data frame. Set a conditional within a for loop to calculate the NaN values percent for each column, and drop those that contain a value of NaNs over your set threshold:

for col, val in df.iteritems():
    if (df[col].isnull().sum() / len(val) * 100) > 30:
        df.drop(columns=col, inplace=True)


问:
Unable to load .pb while converting PyTorch model to tf.keras

Context

I'm using tf.keras for a personal project and I need to retrieve a pretrained Alexnet model.
Unfortunately, this model is not directly accessible using tf.keras only, so I downloaded the pretrained model using PyTorch, converted it into an onnx file and then exported it as a .pb file with the following code :

```<code>torch_pretrained = torchvision.models.alexnet()
torch_pretrained.load_state_dict(torch.load("alexnet.pth"))

dummy_input = Variable(torch.randn(1, 3, 224, 224))
torch.onnx.export(torch_pretrained, dummy_input, "alexnet_pretrained.onnx")

onnx_pretrained = onnx.load("alexnet_pretrained.onnx")
onnx_pretrained = prepare(onnx_pretrained)
onnx_pretrained.export_graph('alexnet')
</code>```

Issue

I'm now trying to retrieve the .pb file using keras as explained here with the following code :

```<code>model = tf.keras.models.load_model("alexnet")
model.summary()
</code>```

And i get an error :

AttributeError: '_UserObject' object has no attribute 'summary'

I also get a warning while loading the model, but I don't think it's relevant :

WARNING:tensorflow:SavedModel saved prior to TF 2.5 detected when loading Keras model. Please ensure that you are saving the model with model.save() or tf.keras.models.save_model(), NOT tf.saved_model.save(). To confirm, there should be a file named "keras_metadata.pb" in the SavedModel directory.

The loaded model has a very obscure type as you can see :

<tensorflow.python.saved_model.load.Loader._recreate_base_user_object.._UserObject object at 0x0000023137981BB0>

While doing my researches, I found this which means I'm not the only one to face this issue.

Question

The easiest way would be to solve this specific issue, but if anyone knows of another way to load a pretrained Alexnet model to tf.keras, this would also solve my actual problem.

Specs

```<code>Windows 10
python 3.9.7
tensorflow 2.6.0
torch 1.10.2
torchvision 0.11.3
onnx 1.10.2
onnx-tf 1.9.0
</code>```

答:
Solution

I followed the suggestion of Jakub : I installed "pytorch2keras" (see this).
I just ran the function to convert directly the pytorch model into a keras model, and it actually worked.

I only had to modify the code of the module as there were some depencies issues (they are using onnx.optimizer, which is now called onnxoptimizer) so I just changed the import line in  :

from

```<code>from onnx import optimizer
</code>```

to

```<code>import onnxoptimizer as optimizer
</code>```

Body:
Context

I'm using tf.keras for a personal project and I need to retrieve a pretrained Alexnet model.
Unfortunately, this model is not directly accessible using tf.keras only, so I downloaded the pretrained model using PyTorch, converted it into an onnx file and then exported it as a .pb file with the following code :

torch_pretrained = torchvision.models.alexnet()
torch_pretrained.load_state_dict(torch.load("alexnet.pth"))

dummy_input = Variable(torch.randn(1, 3, 224, 224))
torch.onnx.export(torch_pretrained, dummy_input, "alexnet_pretrained.onnx")

onnx_pretrained = onnx.load("alexnet_pretrained.onnx")
onnx_pretrained = prepare(onnx_pretrained)
onnx_pretrained.export_graph('alexnet')

Issue

I'm now trying to retrieve the .pb file using keras as explained here with the following code :

model = tf.keras.models.load_model("alexnet")
model.summary()

And i get an error :

AttributeError: '_UserObject' object has no attribute 'summary'

I also get a warning while loading the model, but I don't think it's relevant :

WARNING:tensorflow:SavedModel saved prior to TF 2.5 detected when loading Keras model. Please ensure that you are saving the model with model.save() or tf.keras.models.save_model(), NOT tf.saved_model.save(). To confirm, there should be a file named "keras_metadata.pb" in the SavedModel directory.

The loaded model has a very obscure type as you can see :

<tensorflow.python.saved_model.load.Loader._recreate_base_user_object.._UserObject object at 0x0000023137981BB0>

While doing my researches, I found this which means I'm not the only one to face this issue.

Question

The easiest way would be to solve this specific issue, but if anyone knows of another way to load a pretrained Alexnet model to tf.keras, this would also solve my actual problem.

Specs

Windows 10
python 3.9.7
tensorflow 2.6.0
torch 1.10.2
torchvision 0.11.3
onnx 1.10.2
onnx-tf 1.9.0

Body:
Solution

I followed the suggestion of Jakub : I installed "pytorch2keras" (see this).
I just ran the function to convert directly the pytorch model into a keras model, and it actually worked.

I only had to modify the code of the module as there were some depencies issues (they are using onnx.optimizer, which is now called onnxoptimizer) so I just changed the import line in  :

from

from onnx import optimizer

to

import onnxoptimizer as optimizer


问:
How to plot interactions of predictors when the response data is ordinal in r?
I have a dataset with an ordinal target variable. I need to draw an interaction plot of one continuous and one categorical value to see if their interaction matters.

Here, I will use diamonds built-in dataset for reproducibility. Let's pretend that "cut" is a target variable. I tried to use this:

```<code>interaction.plot(diamonds$carat, diamonds$clarity, diamonds$cut)
</code>```

which gives me this error:

Error in plot.window(...) : need finite 'ylim' values

It works for continuous target variables. But my data has an ordinal response variable. Should I recode my target variable for this function or is there a better way of plotting it?

The plot should look like this (https://www.statology.org/interaction-plot-r/):

答:
You have to make the binary field numeric for it to work.

```<code>library(tidyverse)

data("diamonds")
str(diamonds)

df1 <- diamonds %>%
  filter(cut %in% c("Fair", "Good")) %>%    # Make it binary
  mutate(cut = ifelse(cut == "Fair", 0, 1)) # Make it numeric

# check it
str(df1)

# plot it
interaction.plot(x.factor = df1$color,
                 trace.factor = df1$clarity,
                 response = df1$cut,
                 trace.label = "Clarity")
</code>```

Body:
I have a dataset with an ordinal target variable. I need to draw an interaction plot of one continuous and one categorical value to see if their interaction matters.

Here, I will use diamonds built-in dataset for reproducibility. Let's pretend that "cut" is a target variable. I tried to use this:

interaction.plot(diamonds$carat, diamonds$clarity, diamonds$cut)

which gives me this error:

Error in plot.window(...) : need finite 'ylim' values

It works for continuous target variables. But my data has an ordinal response variable. Should I recode my target variable for this function or is there a better way of plotting it?

The plot should look like this (https://www.statology.org/interaction-plot-r/):

Body:
You have to make the binary field numeric for it to work.

library(tidyverse)

data("diamonds")
str(diamonds)

df1 <- diamonds %>%
  filter(cut %in% c("Fair", "Good")) %>%    # Make it binary
  mutate(cut = ifelse(cut == "Fair", 0, 1)) # Make it numeric

# check it
str(df1)

# plot it
interaction.plot(x.factor = df1$color,
                 trace.factor = df1$clarity,
                 response = df1$cut,
                 trace.label = "Clarity")


问:
Robocopy -- skip specific file types?
I went through Robocopy's documentation here. https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy

Couldn't figure it out since no examples.

Is there a way to set robocopy so that it skips specific file types (e.g. PDFs)?

答: According to the command reference /xf *.pdf should work, see this section for details.

Title: Robocopy -- skip specific file types?


问:
NoSuchMethod Exception when calling a method
I have this if condition where I am calling a method inside, when reaching that part of the code I get the NoSuchMethodError exception. The called method inside of the if condition works perfectly fine as I do get the OTP code.

```<code>      if (isUserExists) {
        await AmplifyInstance().signInUser(_phoneNumber).then((status) {
          if (status['result']) {
            //some code here
          }
        });
      }
</code>```

Called Method -

```<code>  Future<dynamic> signInUser(userPhoneNumber) async {
    print('SignIn User');
    try {
      await Amplify.Auth.signIn(
        username: userPhoneNumber,
        password: userPhoneNumber + 'Bol',
      );
      statusMessage['result'] = true;
    } on AuthException catch (e) {
      statusMessage['result'] = false;
      statusMessage['errorMessage'] = e.message;
    }
  }
</code>```

Here the statusMessage returns true to the calling method.

Here is the snip of the error I get -

答:
signInUser doesn't return a value. Also since you're using await on line 166, you don't need then and you could access statusMessage variable on the next line.

If statusMessage is not accessible in that scope, you could return statusMessage from signInUser.

Body:
I have this if condition where I am calling a method inside, when reaching that part of the code I get the NoSuchMethodError exception. The called method inside of the if condition works perfectly fine as I do get the OTP code.

      if (isUserExists) {
        await AmplifyInstance().signInUser(_phoneNumber).then((status) {
          if (status['result']) {
            //some code here
          }
        });
      }

Called Method -

  Future<dynamic> signInUser(userPhoneNumber) async {
    print('SignIn User');
    try {
      await Amplify.Auth.signIn(
        username: userPhoneNumber,
        password: userPhoneNumber + 'Bol',
      );
      statusMessage['result'] = true;
    } on AuthException catch (e) {
      statusMessage['result'] = false;
      statusMessage['errorMessage'] = e.message;
    }
  }

Here the statusMessage returns true to the calling method.

Here is the snip of the error I get -


问:
Show duplicate entries removed by a set
I expect the below program to print the duplicate entries, which were removed by the Set.
But it always prints a empty array. What could be wrong?</p>
```<code>
public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

        System.out.println(strList);
    }
}```
</code>```

答:
As others mentioned, error comes from removeAll as it removes all occurences.

Method add in Sets returns true if element was added, otherwise false - for a set that means element already exists in it. I think in your case it's more intuitive to use this method. I'll also use Character for elements in collections, because string with length 1 is basically equivalent to a char.

```<code>public class Duplicates {

    public static void main(String[] args) {
        String str = "HelloWorld";
        //Hold unique elements
        Set<Character> uniqueLetters = new LinkedHashSet<>();
        //Hold duplicates
        List<Character> duplicates = new ArrayList<>();
        for (int charIndex = 0; charIndex < str.length(); charIndex++) {
            char letter = str.charAt(charIndex);
            boolean isAdded = uniqueLetters.add(letter);
            if (!isAdded) {
                //if isAdded is false, letter already exists in set
                duplicates.add(letter);
            }
        }
        System.out.println(uniqueLetters);
        System.out.println(duplicates);
    }
}
</code>```

This will print:

```<code>unique letters - [H, e, l, o, W, r, d]
duplicated letters - [l, o, l]
</code>```

l exists twice, because it existed 3 times(and consequently was a duplicate twice). If you need it to appear only once in duplicates, just change List to a Set.

Title: Show duplicate entries removed by a set

Body:
I expect the below program to print the duplicate entries, which were removed by the Set.
But it always prints a empty array. What could be wrong?

public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

        System.out.println(strList);
    }
}```

Body:
As others mentioned, error comes from removeAll as it removes all occurences.

Method add in Sets returns true if element was added, otherwise false - for a set that means element already exists in it. I think in your case it's more intuitive to use this method. I'll also use Character for elements in collections, because string with length 1 is basically equivalent to a char.

public class Duplicates {

    public static void main(String[] args) {
        String str = "HelloWorld";
        //Hold unique elements
        Set<Character> uniqueLetters = new LinkedHashSet<>();
        //Hold duplicates
        List<Character> duplicates = new ArrayList<>();
        for (int charIndex = 0; charIndex < str.length(); charIndex++) {
            char letter = str.charAt(charIndex);
            boolean isAdded = uniqueLetters.add(letter);
            if (!isAdded) {
                //if isAdded is false, letter already exists in set
                duplicates.add(letter);
            }
        }
        System.out.println(uniqueLetters);
        System.out.println(duplicates);
    }
}

This will print:

unique letters - [H, e, l, o, W, r, d]
duplicated letters - [l, o, l]

l exists twice, because it existed 3 times(and consequently was a duplicate twice). If you need it to appear only once in duplicates, just change List to a Set.


问:
Typeerror during Taylor-approximation
For Uni I'm doing this assignment where I have to approximate the difference between the sine function and its n-th Taylor approximation. When running the code plotting these two functions I run into the following error:

TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the casting rule ''same_kind''

The weird thing (in my opinion) is that the program works fine for n <= 20, but when I choose anything above that, it throws this error.

Does anyone know where in my code the problem may lie? Thanks in advance.

```<code>import matplotlib.pyplot as plt
import numpy as np
import math

def constant(n, x):
    return np.full(x.shape, (2*math.pi)**(n+1)/(math.factorial(n+1)))

def taylor_n(n,x):
    val = 0
    for i in range(1, n+1):
        if i%2 == 1:
            val += (-1)**((i-1)/2)* x**i/math.factorial(i)
    return val

N = [1, 5, 10, 20, 50]
x = np.linspace(0,2*math.pi,100)

for n in N:
    plt.plot(x, abs(np.sin(x) - taylor_n(n, x)))
    plt.plot(x, constant(n, x))
</code>```

答:
Looks like float underflow. If cast to decimal it works:

```<code>import decimal

...

def taylor_n(n,x):
    val = 0
    for i in range(1, n+1):
        if i%2 == 1:
            val += np.array((-1) ** ((i - 1) / 2) * x ** i / math.factorial(i), dtype=np.dtype(decimal.Decimal))
    return val
</code>```

Inside taylor_n function expression ((-1) ** ((i - 1) / 2) * x ** i / math.factorial(i)) has type float64, but when i becomes greater the type of expression becomes complex128 and these types can't be summed.

Problem was only while N=50 (actually, N>20), another values calculated correctly. For N=50 plot is:

Title: Typeerror during Taylor-approximation

Body:
For Uni I'm doing this assignment where I have to approximate the difference between the sine function and its n-th Taylor approximation. When running the code plotting these two functions I run into the following error:

TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the casting rule ''same_kind''

The weird thing (in my opinion) is that the program works fine for n <= 20, but when I choose anything above that, it throws this error.

Does anyone know where in my code the problem may lie? Thanks in advance.

import matplotlib.pyplot as plt
import numpy as np
import math

def constant(n, x):
    return np.full(x.shape, (2*math.pi)**(n+1)/(math.factorial(n+1)))

def taylor_n(n,x):
    val = 0
    for i in range(1, n+1):
        if i%2 == 1:
            val += (-1)**((i-1)/2)* x**i/math.factorial(i)
    return val

N = [1, 5, 10, 20, 50]
x = np.linspace(0,2*math.pi,100)

for n in N:
    plt.plot(x, abs(np.sin(x) - taylor_n(n, x)))
    plt.plot(x, constant(n, x))

Body:
Looks like float underflow. If cast to decimal it works:

import decimal

...

def taylor_n(n,x):
    val = 0
    for i in range(1, n+1):
        if i%2 == 1:
            val += np.array((-1) ** ((i - 1) / 2) * x ** i / math.factorial(i), dtype=np.dtype(decimal.Decimal))
    return val

Inside taylor_n function expression ((-1) ** ((i - 1) / 2) * x ** i / math.factorial(i)) has type float64, but when i becomes greater the type of expression becomes complex128 and these types can't be summed.

Problem was only while N=50 (actually, N>20), another values calculated correctly. For N=50 plot is:


问:
Jira as Test Case Management Tool
I have reviewed several test case management solutions available for Jira such as:

http://www.testandtry.com/2009/07/01/test-case-management-in-jira-1/

http://confluence.atlassian.com/display/CONFEVAL/Customise+JIRA+For+Test+Case+Management

I was wondering if it is possible to expand this test case management solution even more.
I am looking for a Jira solution to have:

Requirements

Test Cases (which go under Requirements)

Test Reports (which go under Test Cases)

The links posted above only ignore the "Requirements" part and focus only on Test Cases and Test Reports. Every Test Case Management tool I have used before has these features like HP QualityCenter.

Is it possible to achieve this in Jira?

TIA

答:
it may be what you want:

http://blogs.atlassian.com/jira/bonfire/

ContentLicense: CC BY-SA 2.5

Title: Jira as Test Case Management Tool


问:
SQL query for last 5 years average calculation for each datapoint?

    WITH temp_tbl_2
                 AS (SELECT
                            state,
                            wk_number,
                            year,
                            maxtemp,
                            Avg(salary)
                              OVER (
                                partition BY state, wk_number
                                ORDER BY wk_number, year rows 4 PRECEDING) AS
                            avg_max_5years
                     FROM   tbl
                     ORDER  BY state,
                               wk_number ASC,
                               year ASC)
            SELECT * FROM  temp_tbl_2
```
<p>QN: Current code-Last 4 and current year records used for avg calculation - Using spark sql to computing the result.
Input columns: STATE, WK_NUMBER, YEAR, MAXTEMP
Calculated Column - avg_value_5years_max</p>
```Current result -
STATE   WK_NUMBER   YEAR    MAXTEMP avg_value_5years_max
A         1         2015    21      21
A         1         2016    19.3    20.15
A         1         2017    18      19.43333333
A         1         2018    21.4    19.925
A         1         2019    24.8    20.9
A         1         2020    21.7    21.04
A         1         2021    22.5    21.68
A         1         2022    20.1    22.1

Current Input :

CREATE TABLE tbl (
   state      char(1)
 , wk_number  int
 , year       date
 , maxtemp    decimal(7,2)
 , salary     decimal(9,2)
);

INSERT INTO tbl VALUES
  ('A',       1,        '2015-01-01',   21)
, ('A',       1,        '2016-01-01',   19.3)
, ('A',       1,        '2018-01-01',   21.4)
, ('A',       1,        '2020-01-01',   21.7)
, ('A',       1,        '2022-01-01',   20.1)
;
```
<p>need to cal 5 year avg considering the missing years -
Expected output</p>
```    +-------+-----------+------------+-------------------------------
    | state | wk_number | year       | maxtemp | avg_value_5years_max
    +-------+-----------+------------+---------- --------------------
    | A     |         1 | 2015       |   21.00 |  21.00
    | A     |         1 | 2016       |   19.30 |  20.15
    | A     |         1 | 2018       |   21.40 |  20.5666
    | A     |         1 | 2020       |   21.70 |  20.8
    | A     |         1 | 2022       |   20.10 |  21.06666
    +-------+-----------+------------+-------------------------------
can someone help me on this? Thanks
```

答:
Update: The question uses AVG(salary) in the SQL example, but your results are averages of the maxtemp.  You also never showed any detail about salary.  I've corrected that below.

The fiddle

If your database supports this and you have or convert to the correct type, this might do what you wish, by specifying a range of the last 5 years.

Note: I used a date type for the year column.

If your year column is an int / numeric type, you can use an expression like RANGE BETWEEN 4 PRECEDING AND CURRENT ROW.

WITH temp_tbl_2 AS (
        SELECT state
             , wk_number
             , year
             , maxtemp
             , AVG(maxtemp) OVER (
                                  PARTITION BY state, wk_number
                                      ORDER BY year rows 4 PRECEDING
                                ) AS avg_max_5years
          FROM tbl
         ORDER BY state
                , wk_number ASC
                , year ASC
     )
SELECT * FROM temp_tbl_2
;
```
<p>The result:</p>
<pre class="lang-none prettyprint-override"><code>+-------+-----------+------+---------+----------------+
| state | wk_number | year | maxtemp | avg_max_5years |
+-------+-----------+------+---------+----------------+
| A     |         1 | 2015 |   21.00 |      21.000000 |
| A     |         1 | 2016 |   19.30 |      20.150000 |
| A     |         1 | 2017 |   18.00 |      19.433333 |
| A     |         1 | 2018 |   21.40 |      19.925000 |
| A     |         1 | 2019 |   24.80 |      20.900000 |
| A     |         1 | 2020 |   21.70 |      21.040000 |
| A     |         1 | 2021 |   22.50 |      21.680000 |
| A     |         1 | 2022 |   20.10 |      22.100000 |
+-------+-----------+------+---------+----------------+
</code>```

Test case for MySQL 8.0:

```<code>CREATE TABLE tbl (
   state      char(1)
 , wk_number  int
 , year       date
 , maxtemp    decimal(7,2)
 , salary     decimal(9,2)
);

INSERT INTO tbl VALUES
  ('A',       1,        '2015-01-01',   21  ,   21)
, ('A',       1,        '2016-01-01',   19.3,   20.15)
, ('A',       1,        '2017-01-01',   18  ,   19.43333333)
, ('A',       1,        '2018-01-01',   21.4,   19.925)
, ('A',       1,        '2019-01-01',   24.8,   20.9)
, ('A',       1,        '2020-01-01',   21.7,   21.04)
, ('A',       1,        '2021-01-01',   22.5,   21.68)
, ('A',       1,        '2022-01-01',   20.1,   22.1)
;
</code>```

Body:
    WITH temp_tbl_2
                 AS (SELECT
                            state,
                            wk_number,
                            year,
                            maxtemp,
                            Avg(salary)
                              OVER (
                                partition BY state, wk_number
                                ORDER BY wk_number, year rows 4 PRECEDING) AS
                            avg_max_5years
                     FROM   tbl
                     ORDER  BY state,
                               wk_number ASC,
                               year ASC)
            SELECT * FROM  temp_tbl_2

QN: Current code-Last 4 and current year records used for avg calculation - Using spark sql to computing the result.
Input columns: STATE, WK_NUMBER, YEAR, MAXTEMP
Calculated Column - avg_value_5years_max

Current result -
STATE   WK_NUMBER   YEAR    MAXTEMP avg_value_5years_max
A         1         2015    21      21
A         1         2016    19.3    20.15
A         1         2017    18      19.43333333
A         1         2018    21.4    19.925
A         1         2019    24.8    20.9
A         1         2020    21.7    21.04
A         1         2021    22.5    21.68
A         1         2022    20.1    22.1

Current Input :

CREATE TABLE tbl (
   state      char(1)
 , wk_number  int
 , year       date
 , maxtemp    decimal(7,2)
 , salary     decimal(9,2)
);

INSERT INTO tbl VALUES
  ('A',       1,        '2015-01-01',   21)
, ('A',       1,        '2016-01-01',   19.3)
, ('A',       1,        '2018-01-01',   21.4)
, ('A',       1,        '2020-01-01',   21.7)
, ('A',       1,        '2022-01-01',   20.1)
;

need to cal 5 year avg considering the missing years -
Expected output

    +-------+-----------+------------+-------------------------------
    | state | wk_number | year       | maxtemp | avg_value_5years_max
    +-------+-----------+------------+---------- --------------------
    | A     |         1 | 2015       |   21.00 |  21.00
    | A     |         1 | 2016       |   19.30 |  20.15
    | A     |         1 | 2018       |   21.40 |  20.5666
    | A     |         1 | 2020       |   21.70 |  20.8
    | A     |         1 | 2022       |   20.10 |  21.06666
    +-------+-----------+------------+-------------------------------
can someone help me on this? Thanks

Body:
Update: The question uses AVG(salary) in the SQL example, but your results are averages of the maxtemp.  You also never showed any detail about salary.  I've corrected that below.

The fiddle

If your database supports this and you have or convert to the correct type, this might do what you wish, by specifying a range of the last 5 years.

Note: I used a date type for the year column.

If your year column is an int / numeric type, you can use an expression like RANGE BETWEEN 4 PRECEDING AND CURRENT ROW.

WITH temp_tbl_2 AS (
        SELECT state
             , wk_number
             , year
             , maxtemp
             , AVG(maxtemp) OVER (
                                  PARTITION BY state, wk_number
                                      ORDER BY year rows 4 PRECEDING
                                ) AS avg_max_5years
          FROM tbl
         ORDER BY state
                , wk_number ASC
                , year ASC
     )
SELECT * FROM temp_tbl_2
;

The result:

+-------+-----------+------+---------+----------------+
| state | wk_number | year | maxtemp | avg_max_5years |
+-------+-----------+------+---------+----------------+
| A     |         1 | 2015 |   21.00 |      21.000000 |
| A     |         1 | 2016 |   19.30 |      20.150000 |
| A     |         1 | 2017 |   18.00 |      19.433333 |
| A     |         1 | 2018 |   21.40 |      19.925000 |
| A     |         1 | 2019 |   24.80 |      20.900000 |
| A     |         1 | 2020 |   21.70 |      21.040000 |
| A     |         1 | 2021 |   22.50 |      21.680000 |
| A     |         1 | 2022 |   20.10 |      22.100000 |
+-------+-----------+------+---------+----------------+

Test case for MySQL 8.0:

CREATE TABLE tbl (
   state      char(1)
 , wk_number  int
 , year       date
 , maxtemp    decimal(7,2)
 , salary     decimal(9,2)
);

INSERT INTO tbl VALUES
  ('A',       1,        '2015-01-01',   21  ,   21)
, ('A',       1,        '2016-01-01',   19.3,   20.15)
, ('A',       1,        '2017-01-01',   18  ,   19.43333333)
, ('A',       1,        '2018-01-01',   21.4,   19.925)
, ('A',       1,        '2019-01-01',   24.8,   20.9)
, ('A',       1,        '2020-01-01',   21.7,   21.04)
, ('A',       1,        '2021-01-01',   22.5,   21.68)
, ('A',       1,        '2022-01-01',   20.1,   22.1)
;


问:
How to call suspend function from Service Android?
How to provide scope or how to call suspend function from Service Android?
Usually, activity or viewmodel provides us the scope, from where we can launch suspend but there is no similar thing in Service</p>

答:
SupervisorJob() (Kotlin GitHub) is a job that provides uniderectional cancellation; it allows for cancellations to propogate downwards only.

The SupervisorJob ... is similar to a regular Job with the only exception that cancellation is propagated only downwards. [KotlinLang.org]

Use case:  You have a service that makes a log entry, checks settings, and depending on those settings goes ahead and performs some actions. Do you want all children jobs of the parent job (scope) to cancel if, for instance, a job run based on settings' values throws an exception?  If not (i.e. you still want your logging and check for settings jobs to complete at the least) then you want to use the SupervisorJob(), or even supervisorScope (Kotlin GitHub) for 'scoped concurrency' [KotlinLang.org], as both provide unidirectional job cancellation - and in that case the provided answer works.

Coroutine Exception Handling - Supervision (KotlinLang.org)

However, there is a more direct solution that answers the question.

To provide to your service a scope with which to run coroutines (or suspending functions) that execute blocking code, you can simply create a new CoroutineScope() with an EmptyCoroutineContext:

(Snippet from CoroutineScope Documentation)

If the given context does not contain a Job element, then a default Job() is created. This way, cancellation or failure of any child coroutine in this scope cancels all the other children, just like inside coroutineScope block [Kotlin GitHub]

class YourClass : Extended() {
    ...

    private val serviceScope: CoroutineScope( EmptyCoroutineContext )

    ...

    private inner class ServiceHandler( looper: Looper ): Handler( looper ) {
        override fun handleMessage( msg: Message ) {
            super.handleMessage( msg )

            serviceScope.launch {
               try{
+              ...
               } catch( e: Exception ) {
+              ...
               } finally {
                   stopSelf( msg.arg1 )
               }
            }
        }
    }

    override fun onCreate(){
+   ...
    }

    override fun onDestroy(){
        /* In a service, unlike in an activity, we do not
           need to make a call to the super implementation */
        //super.onDestory()
        serviceScope.cancel()
    }
}
```


问:
How to delete celery task logs in flower?
I want to be able to delete tasks in the flower successful/failed tasks...

so my idea is to have a scheduled celery beat to delete tasks older than X amount of hours.

Anyone knows how to achieve this, where are the tasks stored... etc ?

Goal: Set a configuration variable that says number of hours let's say 48 hours of keeping the logs, then autodelete

That serves people mostly in europe with GDPR compliance, and also protects customers' privacy

答:
Used celery beat with flower...</p>
```<code>app.config_from_object("django.conf:settings", namespace="CELERY")
app.conf.beat_scheduler = "django_celery_beat.schedulers.DatabaseScheduler"
# app.conf.task_default_queue = 'default'

app.conf.tasks_queues = (
    Queue("default", exchange="default", routing_key="default"),
    Queue("data_queue", exchange="data_queue", routing_key="data"),
    # Queue("cleanup_queue", exchange="cleanup_queue", routing_key="cleanup"), #you don't necessarily need this queue
)

# Load task modules from all registered Django apps.
app.autodiscover_tasks()

app.conf.beat_schedule = {
    "data": {
        "task": "app.name.execute_data_tasks",
        "schedule": crontab(minute="*/3"),
    },
    "cleanup": {
        "task": "app.name.execute_cleanup_tasks",
        "schedule": crontab(minute="*/60"), #you can play around with the config here
    },
}
</code>```

Body:
Used celery beat with flower...

app.config_from_object("django.conf:settings", namespace="CELERY")
app.conf.beat_scheduler = "django_celery_beat.schedulers.DatabaseScheduler"
# app.conf.task_default_queue = 'default'

app.conf.tasks_queues = (
    Queue("default", exchange="default", routing_key="default"),
    Queue("data_queue", exchange="data_queue", routing_key="data"),
    # Queue("cleanup_queue", exchange="cleanup_queue", routing_key="cleanup"), #you don't necessarily need this queue
)

# Load task modules from all registered Django apps.
app.autodiscover_tasks()

app.conf.beat_schedule = {
    "data": {
        "task": "app.name.execute_data_tasks",
        "schedule": crontab(minute="*/3"),
    },
    "cleanup": {
        "task": "app.name.execute_cleanup_tasks",
        "schedule": crontab(minute="*/60"), #you can play around with the config here
    },
}