问:
Recyclerview and OkHttp request synchronisation
I'm trying to fetch some data from LastFm API, process it, and display it in a recycler view. My problem is that because of the way my code is structured I think that I initialize my recycler view before data is fetched so nothing is being shown until I reopen my fragment and I don't know how to fix that.

Here is my fragment code:

```<code>public class TopArtistsFragment extends Fragment {

    private RecyclerView recyclerView;
    private ArtistRecyclerViewAdapter adapter;
    private TopArtistsViewModel mArtistsViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mArtistsViewModel = new ViewModelProvider(this).get(TopArtistsViewModel.class);

        mArtistsViewModel.init();

        mArtistsViewModel.getArtists().observe(this, new Observer<ArrayList<ArtistData>>() {
            @Override
            public void onChanged(ArrayList<ArtistData> artistData) {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

       View view = inflater.inflate(R.layout.fragment_top_artists, container, false);
       recyclerView = view.findViewById(R.id.artistRecyclerView);

       return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initRecyclerView();
    }

    private void initRecyclerView() {
        adapter = new ArtistRecyclerViewAdapter(mArtistsViewModel.getArtists().getValue(), getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }
}
</code>```

This is my ViewModel:

```<code>public class TopArtistsViewModel extends ViewModel {

    private MutableLiveData<ArrayList<ArtistData>> mArtists;
    private ArtistDataRepository mRepo;

    public void init() {
        if(mArtists != null)
                return;
        mRepo = ArtistDataRepository.getInstance();
        mArtists = mRepo.getArtists();
    }

    public LiveData<ArrayList<ArtistData>> getArtists() {
        return mArtists;
    }
}
</code>```

And this is my repository where the work is being done:

```<code>public class ArtistDataRepository {
    private static ArtistDataRepository instance;
    private ArrayList<ArtistData> dataSet = new ArrayList<>();

    public static ArtistDataRepository getInstance() {
        if(instance == null)
            instance = new ArtistDataRepository();
        return instance;
    }

    public MutableLiveData<ArrayList<ArtistData>> getArtists() {
        setArtists();

        MutableLiveData<ArrayList<ArtistData>> data = new MutableLiveData<>();
        data.setValue(dataSet);
        return data;
    }

    private void setArtists () {
        fetchData();
    }

    private void fetchData () {
        final String requestUrl = "https://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=2124b8e156db20ac7a5035fad9c01b8e&format=json";

        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(requestUrl).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("NETWORK FAILURE", "Artist fetch");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                    parseData(response.body().string());
                else Log.d("OKHTTP", "Response not successful");
            }
        });
    }

    private void parseData (String queryResponse) {
        try {
            JSONArray artistResponse = new JSONObject(queryResponse).getJSONObject("artists").getJSONArray("artist");

            for(int i = 0; i < artistResponse.length(); i++) {
                JSONObject artist = artistResponse.getJSONObject(i);

                dataSet.add(new ArtistData(artist.getString("mbid"), artist.getString("playcount"), artist.getString("listeners"),
                        artist.getString("name"), artist.getJSONArray("image").getJSONObject(0).getString("#text")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

I'm just a beginner so right now I'm basically trying to merge code from different tutorials into one. That's why some things you see here probably don't make sense, so please do tell me what I can fix.

答:
Got through this link

first try to learn how to fetch data using retrofit and you won't to parse data their is a library GSON and Moshi which will do all your work you just need to use POJO. Just go through this example

Body:
I'm trying to fetch some data from LastFm API, process it, and display it in a recycler view. My problem is that because of the way my code is structured I think that I initialize my recycler view before data is fetched so nothing is being shown until I reopen my fragment and I don't know how to fix that.

Here is my fragment code:

public class TopArtistsFragment extends Fragment {

    private RecyclerView recyclerView;
    private ArtistRecyclerViewAdapter adapter;
    private TopArtistsViewModel mArtistsViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mArtistsViewModel = new ViewModelProvider(this).get(TopArtistsViewModel.class);

        mArtistsViewModel.init();

        mArtistsViewModel.getArtists().observe(this, new Observer<ArrayList<ArtistData>>() {
            @Override
            public void onChanged(ArrayList<ArtistData> artistData) {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

       View view = inflater.inflate(R.layout.fragment_top_artists, container, false);
       recyclerView = view.findViewById(R.id.artistRecyclerView);

       return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initRecyclerView();
    }

    private void initRecyclerView() {
        adapter = new ArtistRecyclerViewAdapter(mArtistsViewModel.getArtists().getValue(), getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }
}

This is my ViewModel:

public class TopArtistsViewModel extends ViewModel {

    private MutableLiveData<ArrayList<ArtistData>> mArtists;
    private ArtistDataRepository mRepo;

    public void init() {
        if(mArtists != null)
                return;
        mRepo = ArtistDataRepository.getInstance();
        mArtists = mRepo.getArtists();
    }

    public LiveData<ArrayList<ArtistData>> getArtists() {
        return mArtists;
    }
}

And this is my repository where the work is being done:

public class ArtistDataRepository {
    private static ArtistDataRepository instance;
    private ArrayList<ArtistData> dataSet = new ArrayList<>();

    public static ArtistDataRepository getInstance() {
        if(instance == null)
            instance = new ArtistDataRepository();
        return instance;
    }

    public MutableLiveData<ArrayList<ArtistData>> getArtists() {
        setArtists();

        MutableLiveData<ArrayList<ArtistData>> data = new MutableLiveData<>();
        data.setValue(dataSet);
        return data;
    }

    private void setArtists () {
        fetchData();
    }

    private void fetchData () {
        final String requestUrl = "https://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=2124b8e156db20ac7a5035fad9c01b8e&format=json";

        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(requestUrl).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("NETWORK FAILURE", "Artist fetch");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                    parseData(response.body().string());
                else Log.d("OKHTTP", "Response not successful");
            }
        });
    }

    private void parseData (String queryResponse) {
        try {
            JSONArray artistResponse = new JSONObject(queryResponse).getJSONObject("artists").getJSONArray("artist");

            for(int i = 0; i < artistResponse.length(); i++) {
                JSONObject artist = artistResponse.getJSONObject(i);

                dataSet.add(new ArtistData(artist.getString("mbid"), artist.getString("playcount"), artist.getString("listeners"),
                        artist.getString("name"), artist.getJSONArray("image").getJSONObject(0).getString("#text")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

I'm just a beginner so right now I'm basically trying to merge code from different tutorials into one. That's why some things you see here probably don't make sense, so please do tell me what I can fix.


来源: stackexchange

问:
Keyboard shortcut for searching object browser in Visual Studio 2012
I need to frequently search the object browser, so I need to find a way to speed up the process. There is a shortcut key to open object browser CTRL-W CTRL-J, but after the object browser is opened, I still need to use the mouse to move the focus to the search box. CTRL-TAB moves the focus around, but never to the search box.

Is there a built-in keyboard shortcut to search the object browser?

答: In English Visual Studio 2019 the default shortcut seems to be Ctrl-K  Ctrl-R.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Creating a watchdog service with PowerShell
Is it possible to make a watchdog service on Windows Server using PowerShell? If yes, how can I do it?

I am trying to create a watchdog service. It will control services and installation code inside the watchdog and check it if it is working or not. Could you share any material?

答:
You won't be able to create a service as such, but you could have a scheduled task that runs on server startup (as NT AUTHORITY\SYSTEM) that executes a PowerShell script which is essentially a loop that repeats forever. Inside the loop you would, periodically, get the state of other services you're interested in monitoring and start/stop them as required based on what you want to happen.

Example code (though there are probably better ways of writing this and it has no error handling):

```<code># This file contains a two-column list like so:
# servicename,desiredstate
# CryptSvc,running
# AdobeARMservice,stopped
$services = import-csv c:\scripts\services.csv

$loop = $true # loop forever
do
{
    foreach($service in $services)
    {
        $svc = Get-Service $svc.servicename
        if($svc.Status.ToString().ToLower() -ne $service.desiredstate)
        {
            switch($service.desiredstate)
            {
                "stopped"
                {
                    $svc.Stop()
                    break
                }

                "running"
                {
                    $svc.Start()
                    break
                }
            }
        }
    }
    Start-Sleep -Seconds 300 # wait 5 minutes after each loop has ended
} while ($loop -eq $true)
</code>```

Body:
You won't be able to create a service as such, but you could have a scheduled task that runs on server startup (as NT AUTHORITY\SYSTEM) that executes a PowerShell script which is essentially a loop that repeats forever. Inside the loop you would, periodically, get the state of other services you're interested in monitoring and start/stop them as required based on what you want to happen.

Example code (though there are probably better ways of writing this and it has no error handling):

# This file contains a two-column list like so:
# servicename,desiredstate
# CryptSvc,running
# AdobeARMservice,stopped
$services = import-csv c:\scripts\services.csv

$loop = $true # loop forever
do
{
    foreach($service in $services)
    {
        $svc = Get-Service $svc.servicename
        if($svc.Status.ToString().ToLower() -ne $service.desiredstate)
        {
            switch($service.desiredstate)
            {
                "stopped"
                {
                    $svc.Stop()
                    break
                }

                "running"
                {
                    $svc.Start()
                    break
                }
            }
        }
    }
    Start-Sleep -Seconds 300 # wait 5 minutes after each loop has ended
} while ($loop -eq $true)


问:
How to customize default pin marker using Google Cluster Manager?
How to customize default NOT CLUSTER, but red pin marker using Google Cluster Manager? There are some similar questions around but no working answer.
When I using:

```<code>func renderer(_ renderer: GMUClusterRenderer, willRenderMarker marker: GMSMarker) {

        marker.icon = UIImage(named: "my_marker")
        marker.setIconSize(scaledToSize: .init(width: 18, height: 24))

}
</code>```

It customizes clusters and icons too. How to customize pin marker only not cluster marker?

答:
Works in Swift 5

```<code>class POIItem: NSObject, GMUClusterItem {
  var position: CLLocationCoordinate2D
  var name: String!
  var icon: UIImage

  init(position: CLLocationCoordinate2D, name: String, icon: UIImage) {
    self.position = position
    self.name = name
    self.icon = icon
  }
}

class PrincipalViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.google_map.clear()

        let iconGenerator = GMUDefaultClusterIconGenerator()
        let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
        let renderer = GMUDefaultClusterRenderer(mapView: self.google_map, clusterIconGenerator: iconGenerator)
        renderer.delegate = self
        self.clusterManager = GMUClusterManager(map: self.google_map, algorithm: algorithm, renderer: renderer)
        self.clusterManager.setDelegate(self, mapDelegate: self)

        //insert your markers type POIItem
        //self.clusterManager.add(item)

        self.clusterManager.cluster()
    }

}

extension PrincipalViewController: GMUClusterRendererDelegate {
    func renderer(_ renderer: GMUClusterRenderer, willRenderMarker marker: GMSMarker) {

        if marker.userData is POIItem {

            if let item = marker.userData as? POIItem {
                marker.icon = item.icon
                marker.title = item.name
            }

        }

        if marker.userData is GMUStaticCluster {

            if let staticCluster = marker.userData as? GMUStaticCluster {

                //this is a custom UIView (.xib) contain a UIImage with custom marker and one label (countLabel) where show number of grouped markers
                let customClusterMarker:CustomClusterMarker = CustomClusterMarker()

                customClusterMarker.countLabel.text = "\(staticCluster.count)"

                let view = UIView(frame: CGRect(x: 0, y: 0, width: 52, height: 70))

                view.addSubview(customClusterMarker)
                marker.iconView = view

            }
        }

    }
}

extension PrincipalViewController: GMUClusterManagerDelegate {
    func clusterManager(_ clusterManager: GMUClusterManager, didTap clusterItem: GMUClusterItem) -> Bool {
        print("didTap clusterItem")
        return true
    }

    func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
        print("didTap cluster")
        return true
     }
}
</code>```

Body:
How to customize default NOT CLUSTER, but red pin marker using Google Cluster Manager? There are some similar questions around but no working answer.
When I using:

func renderer(_ renderer: GMUClusterRenderer, willRenderMarker marker: GMSMarker) {

        marker.icon = UIImage(named: "my_marker")
        marker.setIconSize(scaledToSize: .init(width: 18, height: 24))

}

It customizes clusters and icons too. How to customize pin marker only not cluster marker?

Body:
Works in Swift 5

class POIItem: NSObject, GMUClusterItem {
  var position: CLLocationCoordinate2D
  var name: String!
  var icon: UIImage

  init(position: CLLocationCoordinate2D, name: String, icon: UIImage) {
    self.position = position
    self.name = name
    self.icon = icon
  }
}

class PrincipalViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.google_map.clear()

        let iconGenerator = GMUDefaultClusterIconGenerator()
        let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
        let renderer = GMUDefaultClusterRenderer(mapView: self.google_map, clusterIconGenerator: iconGenerator)
        renderer.delegate = self
        self.clusterManager = GMUClusterManager(map: self.google_map, algorithm: algorithm, renderer: renderer)
        self.clusterManager.setDelegate(self, mapDelegate: self)

        //insert your markers type POIItem
        //self.clusterManager.add(item)

        self.clusterManager.cluster()
    }

}

extension PrincipalViewController: GMUClusterRendererDelegate {
    func renderer(_ renderer: GMUClusterRenderer, willRenderMarker marker: GMSMarker) {

        if marker.userData is POIItem {

            if let item = marker.userData as? POIItem {
                marker.icon = item.icon
                marker.title = item.name
            }

        }

        if marker.userData is GMUStaticCluster {

            if let staticCluster = marker.userData as? GMUStaticCluster {

                //this is a custom UIView (.xib) contain a UIImage with custom marker and one label (countLabel) where show number of grouped markers
                let customClusterMarker:CustomClusterMarker = CustomClusterMarker()

                customClusterMarker.countLabel.text = "\(staticCluster.count)"

                let view = UIView(frame: CGRect(x: 0, y: 0, width: 52, height: 70))

                view.addSubview(customClusterMarker)
                marker.iconView = view

            }
        }

    }
}

extension PrincipalViewController: GMUClusterManagerDelegate {
    func clusterManager(_ clusterManager: GMUClusterManager, didTap clusterItem: GMUClusterItem) -> Bool {
        print("didTap clusterItem")
        return true
    }

    func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
        print("didTap cluster")
        return true
     }
}


问:
Preventing cross site scripting attack on flash container pages
I have a website with a flex application. The flex application has no user input - except for clicks for navigation. The website also uses no scripting language - i.e. no php, asp, jsp or cfm.

The website just consists of one page which contains the flash file for the flex application. The source code of this page is here: http://pastebin.com/n5b4RxqT

I have been advised (by a software program used by my client) that this website is vulnerable to a reflective type XSS attack and have been advised to 'sanitize' all user input.

I am a noob with respect to XSS and would respectfully like to ask that AFAIK there is no user input. What should I sanitize and how?

Thanks in advance

答: Using AC_OETags is the old way of doing things and is deprecated.  What you want to do is use SWFObject which is now the default in Flash Builder 4.</p>


问:
Is there a function like millis() of Arduino in python?
Is there a function like millis() of Arduino (not delay() function) in python?
I want to stop a specific part of program for a while ,but not the whole program.</p>

答:
This question is a little unclear, since millis() just gives you the time since the program started execution, but you want to pause parts of your program.

A Python script runs as a single-threaded process, if you want to block a specific part of your program while not blocking the rest, you first need to start up additional threads and/or processes and split your logic across them.

https://realpython.com/intro-to-python-threading/

https://docs.python.org/3/library/multiprocessing.html

AFAIK there's no builtin "time since startup" variable (but I might be wrong, of course, happy to learn otherwise), I would add a time.time() call to your __main__ block:

```<code>import time

def main():
    global time_of_startup

    # ... lots of code here ...

    time_since_start = time.time() - time_of_startup

if __name__ == "__main__":
    time_of_startup = time.time()
    main()
</code>```

Body:
This question is a little unclear, since millis() just gives you the time since the program started execution, but you want to pause parts of your program.

A Python script runs as a single-threaded process, if you want to block a specific part of your program while not blocking the rest, you first need to start up additional threads and/or processes and split your logic across them.

https://realpython.com/intro-to-python-threading/

https://docs.python.org/3/library/multiprocessing.html

AFAIK there's no builtin "time since startup" variable (but I might be wrong, of course, happy to learn otherwise), I would add a time.time() call to your __main__ block:

import time

def main():
    global time_of_startup

    # ... lots of code here ...

    time_since_start = time.time() - time_of_startup

if __name__ == "__main__":
    time_of_startup = time.time()
    main()


问:
Flask sqlalchemy.exc.OperationalError: (OperationalError) no such table when trying to update database with SQLAlchemy
I'm new to Flask, and having some issues setting up a very basic Flask app.
Right now, I'm trying to get the user to submit a form on the homepage and then save that form to a SQL database.

However, when the user submits the form, I get the following error

```<code>sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: contact [SQL: 'INSERT INTO contact (name, email) VALUES (?, ?)'] [parameters: ('aaa', 'aaa')] (Background on this error at: http://sqlalche.me/e/e3q8)
</code>```

Relevant code is below:

app/models.py

```<code>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired

class ContactForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = PasswordField('Email', validators=[DataRequired()])
    submit = SubmitField('submit')
</code>```

app/__init__.py

```<code>from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from app import routes, models
</code>```

app/config.py

```<code>import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'some-secret-key'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    enter code here
</code>```

Where could I be going wrong here? Do I have to call db.create_all() somewhere? If so, where?

Thanks!

Edit: I've also run

```<code>flask db init
flask db migrate
flask db upgrade
</code>```

答:
I had the same issue. In my case I was querying the database in a forms.py and this was imported to routes.py.

So the problem was basically that the database was queried in the code before it could be created, as classes are loaded before the server starts and an eventual init happens.

The accepted answer didn't work for me.
Unfortunately, I haven't found a clean solution for this. So I ended up with a workaround for this.

In my case I wanted to show files in a dropdown list, so I initialized them empty the first time:

```<code>try:
    profile_files = [ (file.path, file.filename[:-4])
                        for file in File.query.filter_by(type=2).order_by(File.created.desc()).all()]
except sqlalchemy.exc.OperationalError as e:
    profile_files = []
</code>```

So the general workaround would be:

```<code>try:
    # Your DB query
except sqlalchemy.exc.OperationalError as e:
    # create placeholder until your DB is ready
</code>```

Now I can use all the terminal commands again:

```<code>flask db init
flask db migrate
flask db upgrade
</code>```

Hope this is helpful to someone!

Body:
I'm new to Flask, and having some issues setting up a very basic Flask app.
Right now, I'm trying to get the user to submit a form on the homepage and then save that form to a SQL database.

However, when the user submits the form, I get the following error

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: contact [SQL: 'INSERT INTO contact (name, email) VALUES (?, ?)'] [parameters: ('aaa', 'aaa')] (Background on this error at: http://sqlalche.me/e/e3q8)

Relevant code is below:

app/models.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired

class ContactForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = PasswordField('Email', validators=[DataRequired()])
    submit = SubmitField('submit')

app/__init__.py

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from app import routes, models

app/config.py

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'some-secret-key'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    enter code here

Where could I be going wrong here? Do I have to call db.create_all() somewhere? If so, where?

Thanks!

Edit: I've also run

flask db init
flask db migrate
flask db upgrade

Body:
I had the same issue. In my case I was querying the database in a forms.py and this was imported to routes.py.

So the problem was basically that the database was queried in the code before it could be created, as classes are loaded before the server starts and an eventual init happens.

The accepted answer didn't work for me.
Unfortunately, I haven't found a clean solution for this. So I ended up with a workaround for this.

In my case I wanted to show files in a dropdown list, so I initialized them empty the first time:

try:
    profile_files = [ (file.path, file.filename[:-4])
                        for file in File.query.filter_by(type=2).order_by(File.created.desc()).all()]
except sqlalchemy.exc.OperationalError as e:
    profile_files = []

So the general workaround would be:

try:
    # Your DB query
except sqlalchemy.exc.OperationalError as e:
    # create placeholder until your DB is ready

Now I can use all the terminal commands again:

flask db init
flask db migrate
flask db upgrade

Hope this is helpful to someone!


问:
Error when I try to use my webcam (python)
So, I'm using jupyter in a facial detection project, and when I run the program , this message error appears:

```<code>> (error: OpenCV(4.2.0)
> C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182:
> error: (-215:Assertion failed) !_src.empty() in function
> 'cv::cvtColor') [enter image description here][1]
</code>```

This is the code:

Thank you !

答:
This error happens when frame is empty = image was not captured. You are not checking if video_capture is correctly opened before using video_capture.read(). Try to check if read() returned frame:

...
retval, frame = video_capture.read()
if (!retval):
   print("Error when capturing frame")
   continue # loop until retval is true

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
...
```

The problem can have more causes:

camera is not responding

there are more cameras and you initialized wrong camera id

camera is slow and first few frames are empty/not read

You can identify if it is faulty camera by loading picture with cv2.imread() before cv2.cvtColor() into frame and processing it, if it works, then try to troubleshoot video_capture initialization and camera.

TL;DR: frame is empty when calling cv2.cvtColor(), ensure/check that it isn't

Body:
So, I'm using jupyter in a facial detection project, and when I run the program , this message error appears:

> (error: OpenCV(4.2.0)
> C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182:
> error: (-215:Assertion failed) !_src.empty() in function
> 'cv::cvtColor') [enter image description here][1]

This is the code:

Thank you !

Body:
This error happens when frame is empty = image was not captured. You are not checking if video_capture is correctly opened before using video_capture.read(). Try to check if read() returned frame:

...
retval, frame = video_capture.read()
if (!retval):
   print("Error when capturing frame")
   continue # loop until retval is true

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
...

The problem can have more causes:

camera is not responding

there are more cameras and you initialized wrong camera id

camera is slow and first few frames are empty/not read

You can identify if it is faulty camera by loading picture with cv2.imread() before cv2.cvtColor() into frame and processing it, if it works, then try to troubleshoot video_capture initialization and camera.

TL;DR: frame is empty when calling cv2.cvtColor(), ensure/check that it isn't


问:
How can i use another stream data inside the Main Stream using flink
I have Employee Master data coming as the data stream NIFI connector, also have a KAFA Data Main Stream which contains employee details. Within the Process element, I have to use this Master data stream for doing some calculations. Is there any way we can do it.

My Current Design contains a Data Stream and a broadcast stream(broadCastStream) all the data processing is doing under process element in (mainDataProcessor) which is derived from KeyedBroadcastProcessFunction.
I am connecting my broadcast stream to main stream as mentioned below.
ie. mainStream.connect(broadCastStream).process(new mainDataProcessor())

Now we have an additional need to introduce one more Data Stream which contains a Master data coming from Casandra table with Help OF NIFI COnnector. I need this master table data steam inside the process element to do some calculations with main stream data and broadcast data, is there any way for that.

答:
What you usually want to do is to join the streams on a particular column. For example, using a temporal join.

If you are on DataStream, you can also use a join but you need to be careful with the state size (when can you discard data?).

If you don't have an employee id over which to join, you could also try to use broadcasts, but that's less recommended.

If you need more specific pointers, please update your question and also mention which API you are using.


问:
How to wait for onPaint to finish painting (C#)
Hi based on the thread here: How to create a jpg image dynamically in memory with .NET?

I have this method:

```<code>        int maxVal = 50;
        int maxXCells = r.Next(maxVal);
        int maxYCells = r.Next(maxVal);
        int cellXPosition = r.Next(maxVal);
        int cellYPosition = r.Next(maxVal);
        int boxSize = 10;

        Graphics fg = this.CreateGraphics();

        using (var bmp = new System.Drawing.Bitmap(maxXCells * boxSize + 1, maxYCells * boxSize + 1))
        {

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.Yellow);
                Pen pen = new Pen(Color.Black);
                pen.Width = 1;

                //Draw red rectangle to go behind cross
                Rectangle rect = new Rectangle(boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize, boxSize);
                g.FillRectangle(new SolidBrush(Color.Red), rect);

                //Draw cross
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize * cellXPosition, boxSize * cellYPosition);
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * cellYPosition, boxSize * cellXPosition, boxSize * (cellYPosition - 1));

                //Draw horizontal lines
                for (int i = 0; i <= maxXCells; i++)
                {
                    g.DrawLine(pen, (i * boxSize), 0, i * boxSize, boxSize * maxYCells);
                }

                //Draw vertical lines
                for (int i = 0; i <= maxYCells; i++)
                {
                    g.DrawLine(pen, 0, (i * boxSize), boxSize * maxXCells, i * boxSize);
                }
            }
            fg.DrawImage(bmp, 0, 0);
            fg.Dispose();

        }
</code>```

It fires based on the random event (can be many times in a second). What should I do, to  draw a new image only after current drawing has finished? At the moment, I can seen, that if the event to run this method fires faster than drawing has finished, the screen flickers. What are the common solution to avoiding drawing before previous drawing has finished?

This what I included in OnPaint method:

```<code>   protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        finishedInvalidating = false;
        fg = this.CreateGraphics();
        lock (bmp)
        {
            fg.DrawImage(bmp, 0, 0);
        }
        fg.Dispose();
        finishedInvalidating = true;
</code>```

But this does not solve the problem

---------------------- update ------------------

```<code> public partial class LadderFrm : Form
{
    Bitmap bmp;

    int numCols = 3;
    int colWidth = 100;
    int numRows = 30;
    int rowHeight = 20;
    bool finishedInvalidating = false;

    decimal lastprice;

    public LadderFrm()
    {
        bmp = new System.Drawing.Bitmap(numCols * colWidth + 1, numRows * rowHeight + 1);
        prepareLadderGraphics();
    }

    // prepare initial ladder background
    private void prepareLadderGraphics()
    {

        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.Clear(Color.LightGray);
            Pen pen = new Pen(Color.Black);
            pen.Width = 1;

            // drawCells
            for (int i = 0; i < numCols; i++)
            {
                for (int j = 0; j < numRows; j++)
                {
                    Rectangle rect = new Rectangle(i * colWidth, j * rowHeight, colWidth, rowHeight);
                    g.DrawRectangle(pen, rect);
                }
            }
            g.Dispose();
        }

    }

    protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        Graphics fg = this.CreateGraphics();
        lock (fg)
        {
            lock (bmp)
            {
                fg.DrawImage(bmp, 0, 0);
            }
        }
        fg.Dispose();
    }

    public void OrderBookUpdateFn(OrderBookEvent orderBookEvent)
    {

        if (lastprice != orderBookEvent.ValuationAskPrice)
        {
            lastprice = orderBookEvent.ValuationAskPrice;
            lock (bmp)
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    Pen pen = new Pen(Color.Black);
                    pen.Width = 1;
                    for (int i = 0; i < numRows; i++)
                    {
                        Rectangle rect = new Rectangle(colWidth + 1, i*rowHeight + 1, colWidth - 1, rowHeight - 1);
                        g.FillRectangle(new SolidBrush(Color.LightGray), rect);
                        g.DrawString(lastPrice.ToString(), new Font(FontFamily.GenericSansSerif, 10), new SolidBrush(Color.Black), new Point(colWidth + 1, i*rowHeight + 1));
                    }
                    g.Dispose();
                }
                this.Invalidate(new Rectangle(0, 0, 1, 1));
            }
    }
}
</code>```

Above code works, pretty well, however I am not sure if its correct. This is just for test purpose. Method OrderBookUpdateFn(OrderBookEvent orderBookEvent) gets fired very often (sometimes tens of times a second).

答:
The event handlers all run in the main thread of the application, so it's not possible that a method to handle an event is started before the method that handles the previous event is finished.

If you experience flickering, it's not because of overlapping event handlers.

Body:
Hi based on the thread here: How to create a jpg image dynamically in memory with .NET?

I have this method:

        int maxVal = 50;
        int maxXCells = r.Next(maxVal);
        int maxYCells = r.Next(maxVal);
        int cellXPosition = r.Next(maxVal);
        int cellYPosition = r.Next(maxVal);
        int boxSize = 10;

        Graphics fg = this.CreateGraphics();

        using (var bmp = new System.Drawing.Bitmap(maxXCells * boxSize + 1, maxYCells * boxSize + 1))
        {

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.Yellow);
                Pen pen = new Pen(Color.Black);
                pen.Width = 1;

                //Draw red rectangle to go behind cross
                Rectangle rect = new Rectangle(boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize, boxSize);
                g.FillRectangle(new SolidBrush(Color.Red), rect);

                //Draw cross
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize * cellXPosition, boxSize * cellYPosition);
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * cellYPosition, boxSize * cellXPosition, boxSize * (cellYPosition - 1));

                //Draw horizontal lines
                for (int i = 0; i <= maxXCells; i++)
                {
                    g.DrawLine(pen, (i * boxSize), 0, i * boxSize, boxSize * maxYCells);
                }

                //Draw vertical lines
                for (int i = 0; i <= maxYCells; i++)
                {
                    g.DrawLine(pen, 0, (i * boxSize), boxSize * maxXCells, i * boxSize);
                }
            }
            fg.DrawImage(bmp, 0, 0);
            fg.Dispose();

        }

It fires based on the random event (can be many times in a second). What should I do, to  draw a new image only after current drawing has finished? At the moment, I can seen, that if the event to run this method fires faster than drawing has finished, the screen flickers. What are the common solution to avoiding drawing before previous drawing has finished?

This what I included in OnPaint method:

   protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        finishedInvalidating = false;
        fg = this.CreateGraphics();
        lock (bmp)
        {
            fg.DrawImage(bmp, 0, 0);
        }
        fg.Dispose();
        finishedInvalidating = true;

But this does not solve the problem

---------------------- update ------------------

 public partial class LadderFrm : Form
{
    Bitmap bmp;

    int numCols = 3;
    int colWidth = 100;
    int numRows = 30;
    int rowHeight = 20;
    bool finishedInvalidating = false;

    decimal lastprice;

    public LadderFrm()
    {
        bmp = new System.Drawing.Bitmap(numCols * colWidth + 1, numRows * rowHeight + 1);
        prepareLadderGraphics();
    }

    // prepare initial ladder background
    private void prepareLadderGraphics()
    {

        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.Clear(Color.LightGray);
            Pen pen = new Pen(Color.Black);
            pen.Width = 1;

            // drawCells
            for (int i = 0; i < numCols; i++)
            {
                for (int j = 0; j < numRows; j++)
                {
                    Rectangle rect = new Rectangle(i * colWidth, j * rowHeight, colWidth, rowHeight);
                    g.DrawRectangle(pen, rect);
                }
            }
            g.Dispose();
        }

    }

    protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        Graphics fg = this.CreateGraphics();
        lock (fg)
        {
            lock (bmp)
            {
                fg.DrawImage(bmp, 0, 0);
            }
        }
        fg.Dispose();
    }

    public void OrderBookUpdateFn(OrderBookEvent orderBookEvent)
    {

        if (lastprice != orderBookEvent.ValuationAskPrice)
        {
            lastprice = orderBookEvent.ValuationAskPrice;
            lock (bmp)
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    Pen pen = new Pen(Color.Black);
                    pen.Width = 1;
                    for (int i = 0; i < numRows; i++)
                    {
                        Rectangle rect = new Rectangle(colWidth + 1, i*rowHeight + 1, colWidth - 1, rowHeight - 1);
                        g.FillRectangle(new SolidBrush(Color.LightGray), rect);
                        g.DrawString(lastPrice.ToString(), new Font(FontFamily.GenericSansSerif, 10), new SolidBrush(Color.Black), new Point(colWidth + 1, i*rowHeight + 1));
                    }
                    g.Dispose();
                }
                this.Invalidate(new Rectangle(0, 0, 1, 1));
            }
    }
}

Above code works, pretty well, however I am not sure if its correct. This is just for test purpose. Method OrderBookUpdateFn(OrderBookEvent orderBookEvent) gets fired very often (sometimes tens of times a second).


问:
Power BI - Remove first 7 digits of String
I want to Remove the first 7 digits of a Text using DAX. I know that it's possible to use the RIGHT and LEFT function in Excel, so is there something similar in Power BI?

Body: =SUBSTITUTE([ColumnName];LEFT([ColumnName]; 7);"")


问:
React - Dynamic background colors to parent and child
In React, I have this components hierarchy:

```<code>App
  Header
  WaitingPage
    PlaceInLine
    NextRoom
    EstimatedTime
  Footer
</code>```

I want the background of the elements to be: white-gray-white-gray and so. (For example - white Header, gray PlaceInLine, white NextRoom and so on...).
The problem is that in WaitingPage, it won't always have all of the 3 children. It gets data from the server, and, for example, if it gets place in line, it will show PlaceInLine. Another data can arrive while the website is running.

I tried to create a class called ColorGiver, which every time gives you the next color, but when I passed it as a prop to WaitingPage (after using it for getting the background for the Header), the header of the website and the first child of the WaitingPage where both white. I suppose that it's because of the order of how React renders elements, but I don't know exactly how it's done...

```<code><Header backgroundColor={this.colorGiver.next()} />
<WaitingPage colorGiver={this.colorGiver} />
<Footer backgroundColor={this.colorGiver.next() />

</code>```

What's the best way to implement that?

答:
Pure CSS would be pretty straight forward:</p>

```<code>className:nth-child(even) {background: #CCC}
className:nth-child(odd) {background: #FFF}
</code>```

Body:
In React, I have this components hierarchy:

App
  Header
  WaitingPage
    PlaceInLine
    NextRoom
    EstimatedTime
  Footer

I want the background of the elements to be: white-gray-white-gray and so. (For example - white Header, gray PlaceInLine, white NextRoom and so on...).
The problem is that in WaitingPage, it won't always have all of the 3 children. It gets data from the server, and, for example, if it gets place in line, it will show PlaceInLine. Another data can arrive while the website is running.

I tried to create a class called ColorGiver, which every time gives you the next color, but when I passed it as a prop to WaitingPage (after using it for getting the background for the Header), the header of the website and the first child of the WaitingPage where both white. I suppose that it's because of the order of how React renders elements, but I don't know exactly how it's done...

<WaitingPage colorGiver={this.colorGiver} />

What's the best way to implement that?

Body:
Pure CSS would be pretty straight forward:

className:nth-child(even) {background: #CCC}
className:nth-child(odd) {background: #FFF}


问:
Problem with function that returns the key with most unique values in python
I am trying to implement greedy algorithm where I need to find the alphabet generator with most unique alphabets, process these alphabets and find the next best generator until I have processed all alphabets. However, when I run the function get_next_best_generator the first time it returns the right values but doesn't return anything in the next call with the following error-
0
[]
KeyError: ''
output of first call-generator_2
6
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']

why its not returning anything in the call after the first call?

Here is my code-

```<code># create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','m'], 'generator_4':['p','e','m','g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while len(alphabets_covered) < 13:

    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
</code>```

After making some changes- My function still doesn't return the key with the most unique elements.

Updated code-

```<code># create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :
            if selected_alphabet  in alphabets:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets -= set(best_generator_unique_alphabets)
</code>```

Expected output-
generator_2
8
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
generator_3
3
['x', 'w', 'b']
generator_4
2
['e','g']
generator_1
1
['r']

答:
Most of your errors seem to come down to a confusion in the scope of local and global variables. For example, in your function get_next_best_generator() you have defined the variable best_generator as a string with value ''. You then attempt to reassign the string a new value with the operation best_generator = generator. This is throwing an error. so this needs to either be global or you need to rethink the format you're returning the data in. For example, you could store the variables most_alphabets_count, best_generator_alphabets and best_generator in a list. Then iterate through them when its returned and assign the values IF they've been updated from the last check. here's an example of what I mean based on your code:

```<code># create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={
    'generator_1':['p','q','r'],
    'generator_2':['p','q','k','j','l','m','n','t'],
    'generator_3':['x','m'],
    'generator_4':['p','e','m','g']
    }

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    value_list = []
    print(generator_alphabets_dict)
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        for select_alphabet in alphabets:
            if select_alphabet not in alphabets_covered:
                unique_alphabets_list.append(select_alphabet)
                alphabets_covered.append(select_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            value_list.append(len(unique_alphabets_list))
            value_list.append(alphabets)
            value_list.append(generator)
    return value_list

# Loop until all alphabets have been covered
def mainloop():
    counter = 0
    while len(alphabets_covered) < 13 and len(generator_alphabets_dict.keys()) > 0 and counter < 10:
        counter += 1
        print(f'Loop counter: {counter}')
        try:
            my_values = get_next_best_generator()
            most_alphabets_count = my_values[0]
            best_generator_alphabets = my_values[1]
            best_generator = my_values[2]
        except Exception as e:
            print(f'Error in assigning variables values to most_alphabets_count, best_generator_alphabets, best_generator: {e}')

        print(f'best_generator: {best_generator}')
        print(f'most_alphabets_count: {most_alphabets_count}')
        print(f'best_generator_alphabets: {best_generator_alphabets}')
        try:
            if best_generator in generator_alphabets_dict.keys():
                generator_alphabets_dict.pop((best_generator))
                generator_covered.append(best_generator)
            else:
                print(f'key not found in dict')
        except Exception as e:
            print(f"ERROR: {e}\n")
        else:
            print('process complete with no errors\n')
        finally:
            print('process complete')

def print_dict(my_dict):
    for k, v in my_dict.items:
        print(f'Current values in dict:\n')
        print(f'key:{k}')
        print(f'value:{v}')

if __name__ == '__main__':
    mainloop()
</code>```

I'm not sure this solves the greedy algorithm problem, but it does help see where the errors are coming from and what needs fixed. I've put a counter in on the while loop to stop the machine timing out in an infinite loop.

Body:
I am trying to implement greedy algorithm where I need to find the alphabet generator with most unique alphabets, process these alphabets and find the next best generator until I have processed all alphabets. However, when I run the function get_next_best_generator the first time it returns the right values but doesn't return anything in the next call with the following error-
0
[]
KeyError: ''
output of first call-generator_2
6
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']

why its not returning anything in the call after the first call?

Here is my code-

# create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','m'], 'generator_4':['p','e','m','g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while len(alphabets_covered) < 13:

    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)

After making some changes- My function still doesn't return the key with the most unique elements.

Updated code-

# create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :
            if selected_alphabet  in alphabets:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets -= set(best_generator_unique_alphabets)

Expected output-
generator_2
8
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
generator_3
3
['x', 'w', 'b']
generator_4
2
['e','g']
generator_1
1
['r']

Body:
Most of your errors seem to come down to a confusion in the scope of local and global variables. For example, in your function get_next_best_generator() you have defined the variable best_generator as a string with value ''. You then attempt to reassign the string a new value with the operation best_generator = generator. This is throwing an error. so this needs to either be global or you need to rethink the format you're returning the data in. For example, you could store the variables most_alphabets_count, best_generator_alphabets and best_generator in a list. Then iterate through them when its returned and assign the values IF they've been updated from the last check. here's an example of what I mean based on your code:

# create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={
    'generator_1':['p','q','r'],
    'generator_2':['p','q','k','j','l','m','n','t'],
    'generator_3':['x','m'],
    'generator_4':['p','e','m','g']
    }

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    value_list = []
    print(generator_alphabets_dict)
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        for select_alphabet in alphabets:
            if select_alphabet not in alphabets_covered:
                unique_alphabets_list.append(select_alphabet)
                alphabets_covered.append(select_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            value_list.append(len(unique_alphabets_list))
            value_list.append(alphabets)
            value_list.append(generator)
    return value_list

# Loop until all alphabets have been covered
def mainloop():
    counter = 0
    while len(alphabets_covered) < 13 and len(generator_alphabets_dict.keys()) > 0 and counter < 10:
        counter += 1
        print(f'Loop counter: {counter}')
        try:
            my_values = get_next_best_generator()
            most_alphabets_count = my_values[0]
            best_generator_alphabets = my_values[1]
            best_generator = my_values[2]
        except Exception as e:
            print(f'Error in assigning variables values to most_alphabets_count, best_generator_alphabets, best_generator: {e}')

        print(f'best_generator: {best_generator}')
        print(f'most_alphabets_count: {most_alphabets_count}')
        print(f'best_generator_alphabets: {best_generator_alphabets}')
        try:
            if best_generator in generator_alphabets_dict.keys():
                generator_alphabets_dict.pop((best_generator))
                generator_covered.append(best_generator)
            else:
                print(f'key not found in dict')
        except Exception as e:
            print(f"ERROR: {e}\n")
        else:
            print('process complete with no errors\n')
        finally:
            print('process complete')

def print_dict(my_dict):
    for k, v in my_dict.items:
        print(f'Current values in dict:\n')
        print(f'key:{k}')
        print(f'value:{v}')

if __name__ == '__main__':
    mainloop()

I'm not sure this solves the greedy algorithm problem, but it does help see where the errors are coming from and what needs fixed. I've put a counter in on the while loop to stop the machine timing out in an infinite loop.


问:
GCP AI Platform pipelines kubeflow pipeline is created but can't open pipeline dashboard
I'm following AI Platform Pipelines tutorial to create a Kubeflow pipeline at GCP. First time it worked then I deleted everything as described in the tutorial and tried to create again. Pipeline was created and status of it is ok but I'm getting following error when I click OPEN PIPELINES DASHBOARD.

Status of the Clusters under Kubernetes Engine is also ok. But Kubernetes Applications status is Application Failed. All components of Application are also OK.

答: As mentioned in comments, the issue was solved after re-deploy the application.</p>


问:
Excel: Find words of certain length in string?
I have this file where I want to make a conditional check for any cell that contains the letter combination "_SOL", or where the string is followed by any numeric character like "_SOL1524", and stop looking after that. So I don't want matches for "_SOLUTION" or "_SOLothercharactersthannumeric".

So when I use the following formula, I also get results for words like "_SOLUTION":

```<code>=IF(ISNUMBER(FIND("_SOL",A1))=TRUE,"Yay","")
</code>```

How can I avoid this, and only get matches if the match is "_SOL" or "_SOLnumericvalue" (one numeric character)

Clarification: The whole strings may be "Blabla_SOL_BLABLA", "Blabla_SOLUTION_BLABLA" or "Blabla_SOL1524_BLABLA"

答:
Maybe this, which will check if the character after "_SOL" is numeric.

```<code>=IF(ISNUMBER(VALUE(MID(A1,FIND("_SOL",A1)+4,1))),"Yay","")
</code>```

Or, as per OP's request and suggestion, to include the possibility of an underscore after "SOL"

```<code>=IF(OR(ISNUMBER(VALUE(MID(A1,FIND("_SOL",A1)+4,1))),ISNUMBER(FIND("_SOL_",A1))),"Yay","")
</code>```

Body:
I have this file where I want to make a conditional check for any cell that contains the letter combination "_SOL", or where the string is followed by any numeric character like "_SOL1524", and stop looking after that. So I don't want matches for "_SOLUTION" or "_SOLothercharactersthannumeric".

So when I use the following formula, I also get results for words like "_SOLUTION":

=IF(ISNUMBER(FIND("_SOL",A1))=TRUE,"Yay","")

How can I avoid this, and only get matches if the match is "_SOL" or "_SOLnumericvalue" (one numeric character)

Clarification: The whole strings may be "Blabla_SOL_BLABLA", "Blabla_SOLUTION_BLABLA" or "Blabla_SOL1524_BLABLA"

Body:
Maybe this, which will check if the character after "_SOL" is numeric.

=IF(ISNUMBER(VALUE(MID(A1,FIND("_SOL",A1)+4,1))),"Yay","")

Or, as per OP's request and suggestion, to include the possibility of an underscore after "SOL"

=IF(OR(ISNUMBER(VALUE(MID(A1,FIND("_SOL",A1)+4,1))),ISNUMBER(FIND("_SOL_",A1))),"Yay","")


问:
mvc 3 nested objects binding
I am very new to MVC 3 so this could be an easy one. I have a viewmodel with a nested object like this:

```<code> public class EventViewModel
 {
    public Event Event { get; set; }
 }

 public class Event
 {
    [Required]
    public int Id { get; set; }

    public string Title { get; set; }
 }
</code>```

In my 'create' view I do something like this:

```<code>@model EventViewModel
@Html.EditorFor(model => model.Event.Title)
</code>```

Here's the code form my event controller:

```<code>public class EventController : Controller
{

  [HttpPost]
  public ActionResult Create(EventViewModel @event)
  {
    ...
  }
}
</code>```

This editor is inside of form tag. When i postback to my controller the title of the event is null instead of what i entered in the form. Do I need some kind of custom binder? Am I doing something unconventional when I use nested objects in my viewmodel?

答:
It's the name of your parameter. Change it from @event to eventViewModel. Seems like the model binder cannot bind it like that. Possibly it gets mixed up with the Event property on your model.

```<code>public ActionResult Create(EventViewModel eventViewModel) {..}
</code>```

Edit: Some more rough explanation.

The HtmlHelper creates a form input with the name Event.Title and when you are doing the binding on the post, the binder will first try to bind Event.Title to the parameter named event, to the property called Title. Since there is no such property on the EventViewModel this will be null. You can see test this by changing the parameter type from EventViewModel to Event (which has a property called Title), in which case the binding will not be null.

Instead if the parameter is named something else, it will try to bind it to that parameter by looking first for a property called Event, and then Title instead.

Title: mvc 3 nested objects binding

Body:
I am very new to MVC 3 so this could be an easy one. I have a viewmodel with a nested object like this:

 public class EventViewModel
 {
    public Event Event { get; set; }
 }

 public class Event
 {
    [Required]
    public int Id { get; set; }

    public string Title { get; set; }
 }

In my 'create' view I do something like this:

@model EventViewModel
@Html.EditorFor(model => model.Event.Title)

Here's the code form my event controller:

public class EventController : Controller
{

  [HttpPost]
  public ActionResult Create(EventViewModel @event)
  {
    ...
  }
}

This editor is inside of form tag. When i postback to my controller the title of the event is null instead of what i entered in the form. Do I need some kind of custom binder? Am I doing something unconventional when I use nested objects in my viewmodel?

Body:
It's the name of your parameter. Change it from @event to eventViewModel. Seems like the model binder cannot bind it like that. Possibly it gets mixed up with the Event property on your model.

public ActionResult Create(EventViewModel eventViewModel) {..}

Edit: Some more rough explanation.

The HtmlHelper creates a form input with the name Event.Title and when you are doing the binding on the post, the binder will first try to bind Event.Title to the parameter named event, to the property called Title. Since there is no such property on the EventViewModel this will be null. You can see test this by changing the parameter type from EventViewModel to Event (which has a property called Title), in which case the binding will not be null.

Instead if the parameter is named something else, it will try to bind it to that parameter by looking first for a property called Event, and then Title instead.


问:
Turn off Google Cloud Memorystore?
This might be a stupid question.
I'm just curious. I'm new to Redis and would like to experiment with it.
However, I would like to turn the instance on and off whenever I am experimenting as I want to save on costs rather than have the instance running all the time.

But I don't see a stop button like other products such as compute.
Is there a reason for this?

Thank you

答:
You won't be able to manage a Cloud Memorystore for Redis instance as a Compute Engine instance as they are different products with different billing requirements and therefore you can't stop a Cloud Memorystore for Redis instance. </p>

<p>If you are only interested in learning more about Redis you can always install Redis on a Compute Engine instance (see the following tutorial for a clear path as to how to accomplish this or this other tutorial as to how to accomplish this task using docker) and afterwards delete the Compute Engine instance in order for charges to stop accruing. </p>

Title: Turn off Google Cloud Memorystore?

Body:
You won't be able to manage a Cloud Memorystore for Redis instance as a Compute Engine instance as they are different products with different billing requirements and therefore you can't stop a Cloud Memorystore for Redis instance.

If you are only interested in learning more about Redis you can always install Redis on a Compute Engine instance (see the following tutorial for a clear path as to how to accomplish this or this other tutorial as to how to accomplish this task using docker) and afterwards delete the Compute Engine instance in order for charges to stop accruing.


问:
how to align left and right in border
```<code>Positioned(
                    left: 16,
                    right: 16,
                    child: CircleAvatar(
                      radius: 66,
                    child: response.users.photo != null
                        ? Image.network(Modal.url + response.users.photo, width: 120, height: 140,)
                        : Image.asset(
                            'assets/user-icon.png',
                          ),
                    ),
</code>```

i have a problem, i want image align right and left in the border, please help me!

答:
Best way to handle both case (with and without image) and avoid radius is to use ClipOval and CircleAvatar with proper params.

How to use it

In place where you are using it, you can put:

```<code>child: Container(
  width: 300,
  height: 300,
  child: ClipOval(
    child: buildAvatar(photo),
  ),
),
</code>```

and this is only one place where you are setting dimentions (no radius etc.).

Build avatar

And this method will return two types of Widget base on photo (is it null or not)

```<code>Widget buildAvatar(String photo) {
  if (photo == null) {
    return CircleAvatar(
        child: Container(
      color: Colors.white,
      padding: const EdgeInsets.all(30.0),
      child: Image.asset(
        'assets/user-icon.png',
      ),
    ));
  } else {}
  return CircleAvatar(
    backgroundImage: NetworkImage(
      photo,
    ),
  );
}
</code>```

Demo

In runtime I modify photo (is it null or url) ans size (150x150 and 300x300)

Title: how to align left and right in border

Body:
Positioned(
                    left: 16,
                    right: 16,
                    child: CircleAvatar(
                      radius: 66,
                    child: response.users.photo != null
                        ? Image.network(Modal.url + response.users.photo, width: 120, height: 140,)
                        : Image.asset(
                            'assets/user-icon.png',
                          ),
                    ),

i have a problem, i want image align right and left in the border, please help me!

Body:
Best way to handle both case (with and without image) and avoid radius is to use ClipOval and CircleAvatar with proper params.

How to use it

In place where you are using it, you can put:

child: Container(
  width: 300,
  height: 300,
  child: ClipOval(
    child: buildAvatar(photo),
  ),
),

and this is only one place where you are setting dimentions (no radius etc.).

Build avatar

And this method will return two types of Widget base on photo (is it null or not)

Widget buildAvatar(String photo) {
  if (photo == null) {
    return CircleAvatar(
        child: Container(
      color: Colors.white,
      padding: const EdgeInsets.all(30.0),
      child: Image.asset(
        'assets/user-icon.png',
      ),
    ));
  } else {}
  return CircleAvatar(
    backgroundImage: NetworkImage(
      photo,
    ),
  );
}

Demo

In runtime I modify photo (is it null or url) ans size (150x150 and 300x300)


问:
npm run build in php Laravel hang or exit
I'm trying to deploy a Laravel project to my server with this specs:

OS: CentOS Linux release 7.8.2003

Nodejs: 13.14.0

npm: 6.14.5

1 CPU

4GB Ram

Everything was fine but a step, as I use ReactJS with Laravel I have to run npm run dev to let webpack build my assets files. (This is just the step to build the view, it run fine on my local machine and my friend's, with the different of os, MacOS and Ubuntu).

But when I run npm run dev the system either hang like this

```<code>[spyets@vultr current]$ npm run dev

> @ dev /home/spyets/public_html/yamlive/releases/3
> npm run development

> @ development /home/spyets/public_html/yamlive/releases/3
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

</code>```

or show this error

```<code>Exit Code: 254 (Unknown error)

  Host Name: development

  ================
  bash: fork: retry: No child processes
  bash: fork: retry: No child processes
  bash: fork: retry: No child processes
  bash: fork: retry: No child processes
  bash: fork: Resource temporarily unavailable
</code>```

I don't know if this give you more information, I run a vtop (a terminal management tool?) and every time I run the npm run dev command, vtop just crashed

What I tried:

reboot the server

reinstall nodejs ( I install nodejs directly with yum not using nvm )

upgrade nodejs from 12.20.2 to 13.14.0 ( as it currently in 13.14.0 )

I'm new to Centos and deployment.

Edit

I also tried to make swapfile and add 3GB of swap

I tried remove node_modules and reinstall with npm install multiple times

Running both npm run dev and npm run prod resulted in failed or crash

答:
Just 2 days back I was facing the same problem when running npm run prod. The command would start and then after 2 mins it would terminate, leaving me with nothing.

Then I came across Swap Memory. I followed this answer How do you add swap to an EC2 instance? and added a swap memory to my hosting server.

Here are the steps:

```<code>sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1
</code>```

To confirm this, run htop and you will see Swp [||||     0K/1.00G]

I still recommend going through the post to understand this better.

Body:
I'm trying to deploy a Laravel project to my server with this specs:

OS: CentOS Linux release 7.8.2003

Nodejs: 13.14.0

npm: 6.14.5

1 CPU

4GB Ram

Everything was fine but a step, as I use ReactJS with Laravel I have to run npm run dev to let webpack build my assets files. (This is just the step to build the view, it run fine on my local machine and my friend's, with the different of os, MacOS and Ubuntu).

But when I run npm run dev the system either hang like this

[spyets@vultr current]$ npm run dev

> @ dev /home/spyets/public_html/yamlive/releases/3
> npm run development

> @ development /home/spyets/public_html/yamlive/releases/3
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

or show this error

Exit Code: 254 (Unknown error)

  Host Name: development

  ================
  bash: fork: retry: No child processes
  bash: fork: retry: No child processes
  bash: fork: retry: No child processes
  bash: fork: retry: No child processes
  bash: fork: Resource temporarily unavailable

I don't know if this give you more information, I run a vtop (a terminal management tool?) and every time I run the npm run dev command, vtop just crashed

What I tried:

reboot the server

reinstall nodejs ( I install nodejs directly with yum not using nvm )

upgrade nodejs from 12.20.2 to 13.14.0 ( as it currently in 13.14.0 )

I'm new to Centos and deployment.

Edit

I also tried to make swapfile and add 3GB of swap

I tried remove node_modules and reinstall with npm install multiple times

Running both npm run dev and npm run prod resulted in failed or crash

Body:
Just 2 days back I was facing the same problem when running npm run prod. The command would start and then after 2 mins it would terminate, leaving me with nothing.

Then I came across Swap Memory. I followed this answer How do you add swap to an EC2 instance? and added a swap memory to my hosting server.

Here are the steps:

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1

To confirm this, run htop and you will see Swp [||||     0K/1.00G]

I still recommend going through the post to understand this better.


问:
How to display a fixed image on/with/upon a fixed header on R Shiny Dashboard
I am using the R Shiny Dashboard package in order to create a dashboard. I actually want a fixed header which will not move when I will scroll down. On the upper right side of this header I would like to put a image. My css file is named "remaniement" and is in the the folder \www

First idea: I tried to parametrize the width of each element for example put the width of .skin-blue .main-header .navbar at 80% and the width of my picture at 20% but problems come when the browser window size change.

I tried to put the header width at 100% and to put my image above the header. I don't know why, the image is always under the header even when I put a  z-index: 9999999; on my css file.

For both ideas above, I tried with the picture coded on the functions dashboardBody() or dashboardHeader() whithout success.

Here my ui.R code :

```<code>library(shiny)
library(shinydashboard)

header<-dashboardHeader(title = "Titre",disable = FALSE)
sidebar<-dashboardSidebar(sidebarMenu(menuItem("Home", tabName = "home", icon = icon("home"))))
body<-dashboardBody(
tags$link(rel = "stylesheet", href = "remaniement.css"),
tags$div(class="windows",tags$a(href='https://www.microsoft.com/en-gb/windows',target="_blank",tags$img(src='windows.png',width = 80))))

ui<-dashboardPage(skin = "blue",header,sidebar,body)
</code>```

my server.R code:

```<code>server <- function(input, output,session) {}
</code>```

and my css code:

```<code>/*image that a want to put in the header*/
.windows{
position: fixed;
right: 0;
top: 0;
white-space: nowrap;
overflow: visible;
background-color: #FFFFFF;
z-index:9999999;}

/* logo */
.skin-blue .main-header .logo {
background-color: #3c8dbc;
color: #FFF;
position: fixed;
width: 230px;
white-space: nowrap;
overflow: visible;}

/* navbar (rest of the header) */
.skin-blue .main-header .navbar {
width:80%;
position: fixed;
white-space: nowrap;
overflow: visible;
background: linear-gradient(90deg, #3c8dbc, #ffffff);
z-index:850;}

.skin-blue .main-header .navbar .sidebar-toggle {
position: fixed;
white-space: nowrap;
overflow: visible;}

.sidebar {
color: #FFF;
position: fixed;
width: 220px;
white-space: nowrap;
overflow: visible;}

.content-wrapper,
.right-side,
.main-footer{
-webkit-transition: -webkit-transform 0.3s ease-in-out, margin 0.3s ease-in-out;
-moz-transition: -moz-transform 0.3s ease-in-out, margin 0.3s ease-in-out;
-o-transition: -o-transform 0.3s ease-in-out, margin 0.3s ease-in-out;
transition: transform 0.3s ease-in-out, margin 0.3s ease-in-out;
margin-left: 230px;
z-index: 820;
top:50px;
position: relative;
white-space: nowrap;
overflow: visible;
background-color: #ffffff;}

.main-sidebar,
.left-side {
position: absolute;
top: 0;
left: 0;
padding-top: 50px;
min-height: 100%;
width: 230px;
z-index: 810;
-webkit-transition: -webkit-transform 0.3s ease-in-out, width 0.3s ease-in-out;
-moz-transition: -moz-transform 0.3s ease-in-out, width 0.3s ease-in-out;
-o-transition: -o-transform 0.3s ease-in-out, width 0.3s ease-in-out;
transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;}
</code>```

I am really lost, It's been more than 3 days I am stuck at it...

Thank you in advance !

答:
(edited)

Things are "pretty simple" (but finding it is somewhat harsh).

First, I needed to set the images directory as a "resource path" like this:

addResourcePath("<name for my resource path>", "<actual path>"
```

<p>Prefer using <code>system.file()</code> to define the actual path if possible, it is a clean way. You can also check your current resource paths (shiny defaults + yours) with <code>resourcePath()</code></p>

<p>Then, you can call your newly registered folder with <code>tags$img()</code> in your UI:</p>

<pre class="lang-r prettyprint-override"><code>tags$img("<actual path>/local-path-to-your-image", ...) # ... can contain HTML parameter such as width and height
</code>```

And you shall be done !

Body:
I am using the R Shiny Dashboard package in order to create a dashboard. I actually want a fixed header which will not move when I will scroll down. On the upper right side of this header I would like to put a image. My css file is named "remaniement" and is in the the folder \www

First idea: I tried to parametrize the width of each element for example put the width of .skin-blue .main-header .navbar at 80% and the width of my picture at 20% but problems come when the browser window size change.

I tried to put the header width at 100% and to put my image above the header. I don't know why, the image is always under the header even when I put a  z-index: 9999999; on my css file.

For both ideas above, I tried with the picture coded on the functions dashboardBody() or dashboardHeader() whithout success.

Here my ui.R code :

library(shiny)
library(shinydashboard)

header<-dashboardHeader(title = "Titre",disable = FALSE)
sidebar<-dashboardSidebar(sidebarMenu(menuItem("Home", tabName = "home", icon = icon("home"))))
body<-dashboardBody(
tags$link(rel = "stylesheet", href = "remaniement.css"),
tags$div(class="windows",tags$a(href='https://www.microsoft.com/en-gb/windows',target="_blank",tags$img(src='windows.png',width = 80))))

ui<-dashboardPage(skin = "blue",header,sidebar,body)

my server.R code:

server <- function(input, output,session) {}

and my css code:

/*image that a want to put in the header*/
.windows{
position: fixed;
right: 0;
top: 0;
white-space: nowrap;
overflow: visible;
background-color: #FFFFFF;
z-index:9999999;}

/* logo */
.skin-blue .main-header .logo {
background-color: #3c8dbc;
color: #FFF;
position: fixed;
width: 230px;
white-space: nowrap;
overflow: visible;}

/* navbar (rest of the header) */
.skin-blue .main-header .navbar {
width:80%;
position: fixed;
white-space: nowrap;
overflow: visible;
background: linear-gradient(90deg, #3c8dbc, #ffffff);
z-index:850;}

.skin-blue .main-header .navbar .sidebar-toggle {
position: fixed;
white-space: nowrap;
overflow: visible;}

.sidebar {
color: #FFF;
position: fixed;
width: 220px;
white-space: nowrap;
overflow: visible;}

.content-wrapper,
.right-side,
.main-footer{
-webkit-transition: -webkit-transform 0.3s ease-in-out, margin 0.3s ease-in-out;
-moz-transition: -moz-transform 0.3s ease-in-out, margin 0.3s ease-in-out;
-o-transition: -o-transform 0.3s ease-in-out, margin 0.3s ease-in-out;
transition: transform 0.3s ease-in-out, margin 0.3s ease-in-out;
margin-left: 230px;
z-index: 820;
top:50px;
position: relative;
white-space: nowrap;
overflow: visible;
background-color: #ffffff;}

.main-sidebar,
.left-side {
position: absolute;
top: 0;
left: 0;
padding-top: 50px;
min-height: 100%;
width: 230px;
z-index: 810;
-webkit-transition: -webkit-transform 0.3s ease-in-out, width 0.3s ease-in-out;
-moz-transition: -moz-transform 0.3s ease-in-out, width 0.3s ease-in-out;
-o-transition: -o-transform 0.3s ease-in-out, width 0.3s ease-in-out;
transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;}

I am really lost, It's been more than 3 days I am stuck at it...

Thank you in advance !

Body:
(edited)

Things are "pretty simple" (but finding it is somewhat harsh).

First, I needed to set the images directory as a "resource path" like this:

addResourcePath("<name for my resource path>", "<actual path>"

Prefer using system.file() to define the actual path if possible, it is a clean way. You can also check your current resource paths (shiny defaults + yours) with resourcePath()

Then, you can call your newly registered folder with tags$img() in your UI:

tags$img("<actual path>/local-path-to-your-image", ...) # ... can contain HTML parameter such as width and height

And you shall be done !


问:
bash - loop through subdirectories, cat files and rename with directory name
I have a folder structure like this ...

```<code>data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz
</code>```

I need to go in to each subdirectory (e.g. B1) and perform the following:

```<code>cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz
</code>```

I'm having problems with the file naming part. I can get in directories using the following:

```<code>for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done
</code>```

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

答:
Taking your question verbatim: If you have a variable d, where you know that it ends in / (as is the case in your example), you can get the value with this last character stripped by writing ${d:0:-1} (i.e. the substring starting at the beginning, up to (excluding) the last character.

Of course in your case, I would rather write the loop as

```<code>for d in *; do
</code>```

which already creates the names without a trailing slash. But this is still probably not what you want, because d would assume the name of the entries in the directory you have cd'ed to, but you want the name of the directory itself. You can optain this for instance by $(basename "$PWD"), which turns your loop into (i.e.)

```<code>cd B1
prefix=$(basename "$PWD") # This set prefix to B1
for f in *
do
  # Since your original code indicates that you want to create a *copy* of the file
  # with a new name, I do the same here.
  cp -v "$f" "${prefix}_$f" #
done
</code>```

You can also use cat, as in your original solution, if you prefer.

Body:
I have a folder structure like this ...

data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz

I need to go in to each subdirectory (e.g. B1) and perform the following:

cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz

I'm having problems with the file naming part. I can get in directories using the following:

for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

Body:
Taking your question verbatim: If you have a variable d, where you know that it ends in / (as is the case in your example), you can get the value with this last character stripped by writing ${d:0:-1} (i.e. the substring starting at the beginning, up to (excluding) the last character.

Of course in your case, I would rather write the loop as

for d in *; do

which already creates the names without a trailing slash. But this is still probably not what you want, because d would assume the name of the entries in the directory you have cd'ed to, but you want the name of the directory itself. You can optain this for instance by $(basename "$PWD"), which turns your loop into (i.e.)

cd B1
prefix=$(basename "$PWD") # This set prefix to B1
for f in *
do
  # Since your original code indicates that you want to create a *copy* of the file
  # with a new name, I do the same here.
  cp -v "$f" "${prefix}_$f" #
done

You can also use cat, as in your original solution, if you prefer.


问:
How to get loading progress in React.lazy and Suspense
I'm using lazy to split my routes and I wanna know if there is any way I can get the loading progress in lazy and suspense.

Currently I'm using it like this.

```<code>const Home = lazy(() => import("./Home"));
const About = lazy(() => import("./About"));

function App() {
  return (
    <Router>
      <Switch>
        <Suspense fallback={<div>loading</div>}>
          <Route path="/" exact={true} component={Home} />
          <Route path="/About" component={About} />
        </Suspense>
      </Switch>
    </Router>
  );
}
</code>```

■ But I want to show the loading progress (like youtube).

■ Is there any way I can retrieve the progress for example like below.

```<code><Suspense fallback={({progress}) => <LoadingBar progress={progress}/>}>
</code>```

答:
This is my solution:</p>

```<code>const LazyLoad = () => {
    useEffect(() => {
        NProgress.start();

        return () => {
            NProgress.stop();
        };
    });

    return '';
};

<Suspense fallback={<LazyLoad />}>
</code>```

Body:
I'm using lazy to split my routes and I wanna know if there is any way I can get the loading progress in lazy and suspense.

Currently I'm using it like this.

const Home = lazy(() => import("./Home"));
const About = lazy(() => import("./About"));

function App() {
  return (
    <Router>
      <Switch>
        <Suspense fallback={
loading
}>
          <Route path="/" exact={true} component={Home} />
          <Route path="/About" component={About} />
        </Suspense>
      </Switch>
    </Router>
  );
}

■ But I want to show the loading progress (like youtube).

■ Is there any way I can retrieve the progress for example like below.

<Suspense fallback={({progress}) => <LoadingBar progress={progress}/>}>

Body:
This is my solution:

const LazyLoad = () => {
    useEffect(() => {
        NProgress.start();

        return () => {
            NProgress.stop();
        };
    });

    return '';
};

<Suspense fallback={<LazyLoad />}>


问:
Customize the marker on google map with clusters
I am using google map SDK in my application and plotting marker on selected let long and for making groups on marker i am using GMUClusterManager for adding cluster on marker, but with this i am facing an issue to change the image of marker, with if i draw a marker with GMUClusterManager then there  no option to change marker image. So any one know any other way to make groups of all markers when user zoom in map, or to change the image of maker.</p>

答:
Works in Swift 5</p>

```<code>class POIItem: NSObject, GMUClusterItem {
  var position: CLLocationCoordinate2D
  var name: String!
  var icon: UIImage

  init(position: CLLocationCoordinate2D, name: String, icon: UIImage) {
    self.position = position
    self.name = name
    self.icon = icon
  }
}

class PrincipalViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.google_map.clear()

        let iconGenerator = GMUDefaultClusterIconGenerator()
        let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
        let renderer = GMUDefaultClusterRenderer(mapView: self.google_map, clusterIconGenerator: iconGenerator)
        renderer.delegate = self
        self.clusterManager = GMUClusterManager(map: self.google_map, algorithm: algorithm, renderer: renderer)
        self.clusterManager.setDelegate(self, mapDelegate: self)

        //insert your markers type POIItem
        //self.clusterManager.add(item)

        self.clusterManager.cluster()
    }

}

extension PrincipalViewController: GMUClusterRendererDelegate {
    func renderer(_ renderer: GMUClusterRenderer, markerFor object: Any) -> GMSMarker? {
        switch object {
        case let item as POIItem:

            let marker = GMSMarker()

            marker.position = item.position
            marker.icon = UIImage(named: "your_custom_marker")

            return marker
        case let staticCluster as GMUStaticCluster:

            let marker = GMSMarker()

            marker.position = staticCluster.position
            marker.icon = UIImage(named: "your_gruped_custom_marker")

            return marker
        default:
            return nil
        }
    }
}

extension PrincipalViewController: GMUClusterManagerDelegate {
    func clusterManager(_ clusterManager: GMUClusterManager, didTap clusterItem: GMUClusterItem) -> Bool {
        print("didTap clusterItem")
        return true
    }

    func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
        print("didTap cluster")
        return true
     }
}
</code>```

Body:
Works in Swift 5

class POIItem: NSObject, GMUClusterItem {
  var position: CLLocationCoordinate2D
  var name: String!
  var icon: UIImage

  init(position: CLLocationCoordinate2D, name: String, icon: UIImage) {
    self.position = position
    self.name = name
    self.icon = icon
  }
}

class PrincipalViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.google_map.clear()

        let iconGenerator = GMUDefaultClusterIconGenerator()
        let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
        let renderer = GMUDefaultClusterRenderer(mapView: self.google_map, clusterIconGenerator: iconGenerator)
        renderer.delegate = self
        self.clusterManager = GMUClusterManager(map: self.google_map, algorithm: algorithm, renderer: renderer)
        self.clusterManager.setDelegate(self, mapDelegate: self)

        //insert your markers type POIItem
        //self.clusterManager.add(item)

        self.clusterManager.cluster()
    }

}

extension PrincipalViewController: GMUClusterRendererDelegate {
    func renderer(_ renderer: GMUClusterRenderer, markerFor object: Any) -> GMSMarker? {
        switch object {
        case let item as POIItem:

            let marker = GMSMarker()

            marker.position = item.position
            marker.icon = UIImage(named: "your_custom_marker")

            return marker
        case let staticCluster as GMUStaticCluster:

            let marker = GMSMarker()

            marker.position = staticCluster.position
            marker.icon = UIImage(named: "your_gruped_custom_marker")

            return marker
        default:
            return nil
        }
    }
}

extension PrincipalViewController: GMUClusterManagerDelegate {
    func clusterManager(_ clusterManager: GMUClusterManager, didTap clusterItem: GMUClusterItem) -> Bool {
        print("didTap clusterItem")
        return true
    }

    func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
        print("didTap cluster")
        return true
     }
}


问:
Error: certificate has expired in Node
My production node app on Heroku randomly started throwing the following error:

```<code>Error: certificate has expired
     at Error (native)
     at TLSSocket.<anonymous> (_tls_wrap.js:1060:38)
     at emitNone (events.js:86:13)
     at TLSSocket.emit (events.js:185:7)
     at TLSSocket._finishInit (_tls_wrap.js:584:8)
     at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:416:38)
 error: Forever detected script exited with code: 1
 error: Script restart attempt #1
 Creating a pool connected to blah.thing.com:port
 Running migrations for database 'app_name'...
 events.js:160
       throw er; // Unhandled 'error' event
       ^
</code>```

I'm confused by two things. My certificate is up to date, so I don't know why it's saying it's expired, and second, the only two files called "events.js" in my app directory are in two seemingly irrelevant node modules (inquirer and twilio) and don't even have a line 160. What might be the cause of this and how should I even debug it?

edit: In addition, it's just the production app (of course), not staging or local, which is odd because staging and production both point to the same certificate.

答:
I had similar error in my project

```<code>Error: certificate has expired
at TLSSocket.<anonymous> (_tls_wrap.js:1116:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:643:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:473:38)
at TLSSocket.<anonymous> (_tls_wrap.js:1116:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:643:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:473:38)
</code>```

it turned out that the problem was in the external service that was used for tracking user events (Amplitude). Their Sectigo's legacy AddTrust External CA Root certificate had expired which impacted many companies across the internet. To resolve that issue they had upgraded their package with the new endpoint and a new certificate.

So if someone encounters similar issue, first think of all possible external services that are used within the app.

Title: Error: certificate has expired in Node

Body:
My production node app on Heroku randomly started throwing the following error:

Error: certificate has expired
     at Error (native)
     at TLSSocket.<anonymous> (_tls_wrap.js:1060:38)
     at emitNone (events.js:86:13)
     at TLSSocket.emit (events.js:185:7)
     at TLSSocket._finishInit (_tls_wrap.js:584:8)
     at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:416:38)
 error: Forever detected script exited with code: 1
 error: Script restart attempt #1
 Creating a pool connected to blah.thing.com:port
 Running migrations for database 'app_name'...
 events.js:160
       throw er; // Unhandled 'error' event
       ^

I'm confused by two things. My certificate is up to date, so I don't know why it's saying it's expired, and second, the only two files called "events.js" in my app directory are in two seemingly irrelevant node modules (inquirer and twilio) and don't even have a line 160. What might be the cause of this and how should I even debug it?

edit: In addition, it's just the production app (of course), not staging or local, which is odd because staging and production both point to the same certificate.

Body:
I had similar error in my project

Error: certificate has expired
at TLSSocket.<anonymous> (_tls_wrap.js:1116:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:643:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:473:38)
at TLSSocket.<anonymous> (_tls_wrap.js:1116:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:643:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:473:38)

it turned out that the problem was in the external service that was used for tracking user events (Amplitude). Their Sectigo's legacy AddTrust External CA Root certificate had expired which impacted many companies across the internet. To resolve that issue they had upgraded their package with the new endpoint and a new certificate.

So if someone encounters similar issue, first think of all possible external services that are used within the app.