vpn – OpenVPN client – session-start: ** ERROR ** Failed to start new session: Failed calling D-Bus method Connect: Timeout was reached

First I run: $ openvpn3 config-import --config jethro-cao.ovpn, and get the expected output of: Configuration imported. Configuration path: /net/openvpn/v3/configuration/339401a6xf41ex483ex8ea4x60cfa3e2a844

Now I try to connect like shown below:

$ openvpn3 session-start --config-path /net/openvpn/v3/configuration/339401a6xf41ex483ex8ea4x60cfa3e2a844
Session path: /net/openvpn/v3/sessions/c398f1cesbd60s4ae5sabbbs123b9bb27186
Auth User name: jethro.cao
Auth Password: 
Enter Authenticator Code: 629542

Then after about a 10sec hang, the following error gets displayed:

session-start: ** ERROR ** Failed to start new session: Failed calling D-Bus method Connect: Timeout was reached

My username and password (and OTP too ofc) should all be correct, since I’m able to log into the OpenVPN CWS using the same credentials to manage my profile.

Also running $ openvpn3 sessions-list, after a very long wait of over a minute, I get the following output:

-----------------------------------------------------------------------------
        Path: /net/openvpn/v3/sessions/c398f1cesbd60s4ae5sabbbs123b9bb27186
     Created: Mon Jul 12 18:56:36 2021                  PID: 38321
       Owner: jyscao                                 Device: (None)
 Config name: jethro-cao.ovpn
      Status: (No status)
-----------------------------------------------------------------------------

Anyone have experience with this issue?

Edit: I should add, up until today these commands were working well for me, for about 2 weeks.

javascript – Flask – Calling python function which takes input parameters on button OnClick event

I have a Flask web app with a download button. When I click on the button I would like to execute a python method, not a javascript method. This python method should take as input some recently modified html code from the web page.

Most precisely the following happens: the user is asked to fill the blanks in some text and when she is done clicks on the download button. When the button gets clicked, a python function render_pdf() is executed that converts the html modified text to a pdf by using pdfkit library.

In its most simple version, my project has the following structure:

  • static/sample.pdf
  • templates/index.html
  • main.py

And this is the code I have so far:

main.py

from flask import Flask, render_template
import pdfkit 

app = Flask(__name__)


@app.route("https://stackoverflow.com/")
def index():
    return render_template('index.html')
    
if __name__ == "__main__":
    app.run(debug=True)

index.html

<body>

    <p class="test">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, beatae!
        <span contenteditable="true" class="badge alert-info name" data-placeholder="Enter your name" data-focused-advice="Start typing"></span><i class="fa fa-lg fa-plus-circle"></i>
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Perspiciatis, laboriosam?
    </p>

    <button onclick="render_pdf()"><a href="../static/sample.pdf" download="my_file">Download</a></button>
</body>

The python method I would like to execute should be this one, passing htmlstr as input:

import pdfkit

def render_pdf(htmlstr):
    pdfkit.from_string(htmlstr, './static/sample.pdf') 

I know I can get with javascript the variable htmlstr by doing document.getElementsByClassName("test")(0).innerHTML;

I feel I am super close to get there and I have checked maybe a bit old but very similar questions but I just do not know how to pass the input html to the python method. What am I missing?

flutter – (GETX) Class ‘String’ has no instance getter ‘descricao’.” Tried calling: descricao

Estou tentando fazer 2 DropdownButton, o primeiro que ao selecionar o UF o segundo lista as cidades dele porem não estou conseguindo de jeito nenhum, estou fazendo a requisição e adicionando as cidades dessa requisição na lista de cidades mas ao utilizar ela só da erro, parece que ela não esta adicionando não consegui identificar muito bem o erro, mas já tentei varias coisas e nada… Alguém sabe alguma solução?

Controller:

  List cidades = ().obs;
  var selected = "UF".obs;
  var selectedCidades = "Selecione o Estado".obs;

  void setSelectedCity(var value){
    selectedCidades.value = value;
  }

  void setSelected(var value){
    selected.value = value;
  }
    
getByUf(String uf) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        final id_distribuidor = prefs.getInt('id_distribuidor');
        final token = prefs.getString('access_token');
        try {
          final response = await Dio().get(
              '####################################################',
              options: Options(
                headers: {'Authorization': "Bearer ${token}"},
              ));
          print(response.data);
          final list = response.data;
    
          cidades.clear();
    
          for (var item in list) {
            CidadesModel cidade = new CidadesModel.fromJson(item);
            cidades.add(cidade.descricao);
          }
          return this.cidades;
        } on DioError catch (e) {
          if (e?.response?.statusCode == 401) {
            Get.snackbar(
                'Sem permissão', 'Tente logar novamente!');
          } else if (e?.response?.statusCode == 500) {
            print(e);
            Get.snackbar('Erro', 'Ocorreu um erro inesperado');
          }
        }
      }

Model:

class CidadesModel {
  int idCidade;
  String descricao;
  String uf;
  int codigoIbge;
  String ddd;

  CidadesModel(
      {this.idCidade, this.descricao, this.uf, this.codigoIbge, this.ddd});

  CidadesModel.fromJson(Map<String, dynamic> json) {
    idCidade = json('id_cidade');
    descricao = json('descricao');
    uf = json('uf');
    codigoIbge = json('codigo_ibge');
    ddd = json('ddd');
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data('id_cidade') = this.idCidade;
    data('descricao') = this.descricao;
    data('uf') = this.uf;
    data('codigo_ibge') = this.codigoIbge;
    data('ddd') = this.ddd;
    return data;
  }
}

Dropdown:

              Row(
                children: (
                  Obx(
                    () => DropdownButtonHideUnderline(
                    child: ButtonTheme(
                      child: DropdownButton<String>(
                        value: '${navController.selected}',
                        hint: Text('UF'),
                        onChanged: (String newValue) {
                          navController.setSelected(newValue);
                          navController.getByUf(newValue);
                        },
                        items: Estados.listaEstadosSigla.map((item) {
                              return new DropdownMenuItem(
                                child: new Text(item),
                                value: item,
                              );
                            }).toList(),
                      ),
                    ),
                  ),
                  ),
                ),
              ),
              Row(
                children: (
                  Obx(
                    () => DropdownButtonHideUnderline(
                    child: ButtonTheme(
                      child: DropdownButton<String>(
                        value: '${navController.selectedCidades}',
                        hint: Text('Cidade'),
                        onChanged: (String newValue) {
                          navController.setSelectedCity(newValue);
                        },
                        items: navController.cidades.map((item) {
                              return new DropdownMenuItem(
                                child: new Text(item.descricao),
                                value: item.idCidade.toString(),
                              );
                            }).toList(),
                      ),
                    ),
                  ),
                  ),
                ),
              ),

labels – How can I say “there is a possibility, up to 30 mins delay in the time you booked for calling you” shorter?

It sounds to me like what you really want is for the user to select a one hour time slot instead of a fixed time.

This makes it much clearer that you cannot commit to a specific time and the user must be prepared for an estimated time given a one-hour timeframe.

<select>
    <option>08:30 AM - 09:30 AM</option>
    <option>09:30 AM - 10:30 AM</option>
    <option>11:30 AM - 12:30 PM</option>
    <option>01:30 PM - 02:30 PM</option>
    <option>03:30 PM - 04:30 PM</option>
</select>

I would suggest you include a message above the select control that states something like:

Unfortunately, we cannot offer an exact time to call, and will call within a one-hour window. Select your preferred time slot from the options below.

If you are looking to reduce “text clutter” on your page, then you probably don’t even need this at all. Having the time ranges in the options should be sufficient for the user to understand it is not a fixed time.


A note on implementation. You can still technically only need to store a single time in your database, which would be the middle time. For example, if the user selects 9am-10am, you can just store 9:30am.

My suggested change is more about how the user perceives the options, rather than about what data you actually need to capture.

programming practices – Calling general-purpose methods from the code that clearly needs only specific behavior

Here are a couple of examples in Python:

clearly_even = 2 * get_integer()
print(solve_for_any_integer(clearly_even))

def solve_for_any_integer(x):
  while x % 2 == 1:
    x = make_even_from_odd(x)
  return ... # Solve for even

When it’s clear that an even number is passed, I’d make a solve_for_even function and call it.

for car in list_cars():
  if car.driver is None:
    continue
  if not eligible_to_drive_taxi(driver):
    continue
  print(driver.name)

def eligible_to_drive_taxi(person):
  if person.is_drunk:
    return False
  if person.driver_licence is None:
    return False
  if person.driver_licence.years_of_experience < 3:
    return False
  return True

Assuming that drivers are sober and have a driver’s license, why not making a special function or method that checks ​a license only?

I see several benefits of using more specific code:

  1. Less code to follow through when reading.
  2. Methods have less diverse use cases and, therefore, became simpler.
  3. Using more specific methods gives more insight into assumptions made by the author. Fewer “why” questions and WTF moments.

To me, it’s always been obvious that using a more specific method is the only way to go. Admittedly, it may be controversial, but what are other reasons to stick with either approach?

Although, I see many developers use more generic methods so often so there should be a name and some articles on this phenomenon. Are there any?

labels – How to say “there is a possibility, up to 30 mins delay in the time you booked for calling you” shorter?

I have a reservation web form. There is a field named “time”. It’s a select option like:

# Select a time: 

<select>
    <option>09:00 AM</option>
    <option>10:00 AM</option>
    <option>12:00 PM</option>
    <option>02:00 PM</option>
    <option>04:00 PM</option>
</select>

The user must select one of those times to specify at which time we have to call him/her for finalizing his/her request.

Now, I need to add a short label under that field to mention this possibility:

Probably we call you 30 mins sooner or later than the time you selected

How can I say that sentence much shorter?

wikidata – Is there a way to skip first x lines of a bz2 file in Python without calling next()?

I’m trying to read the latest Wikidata dump while skipping the first, say, 100 lines.

Is there a better way to do this than calling next() repeatedly?

WIKIDATA_JSON_DUMP = bz2.open('latest-all.json.bz2', 'rt')

for n in range(100):
    next(WIKIDATA_JSON_DUMP)

Alternatively, is there a way to split up the file in bash by, say, using bzcat to pipe select chunks to smaller files?

c# – Calling an API endpoint from MVC frontend; GET request with username as parameter

In my application, I only show users their own data. For that, I need to know in the backend, which user is requesting data. I use the username for that and therefore, I need to send the username as part of the GET request.

The method in question – it is called from MVC-controller:

public async Task<IActionResult> Index()
{
    ////Here, I pass username. ApiClient is a HttpClient and has a configured BaseAddress.
    var response = await ApiHelper.ApiClient.GetAsync("username?username=" + User.Identity.Name);
    var result = await response.Content.ReadAsStringAsync();
        
    var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
    List<MatchViewModel> match = JsonSerializer.Deserialize<List<MatchViewModel>>(result, options);
    return View(match);
}

Whatever feedback, advice or critique you might have, I am interested. Thanks in advance.

sql server – Calling simple Execute SQL Task fails with IMultipleResults::GetResults failed

We are executing SSIS packages from a scheduling tool via a custom stored procedure which wires up all the SSIS parameters then executes the SSIS on the SQL server integration services catalog. This has worked for years with no problems. However, recently I had to create a new SSIS package which uses an Execute SQL Task that calls a stored procedure in a accessing a new DB we recently created. I have pretty basic code in the task:

DECLARE @RunDate date = ?
IF @RunDate = '12/30/1899' BEGIN
    SET @RunDate = NULL
END

EXECUTE dbo.<Stored_Procedure> @RunDate

I’ve enabled verbose logging in our execution stored procedure and this is what I’m seeing. The only thing that stands out is the “IMultipleResults::GetResult failed” failed line but the sql does not return any results and the task is not set to expect results.

ExternalRequest_post: ‘ICommand::Execute succeeded’. The external
request has completed.
ExternalRequest_post: ‘IMultipleResults::GetResult failed.’. The
external request has completed.
Execute Extract:Error: Executing the query “DECLARE @RunDate date = ?
IF @RunDate = ’12/30/189…” failed with the following error: ” “.
Possible failure reasons: Problems with the query, “ResultSet”
property not set correctly, parameters not set correctly, or
connection not established correctly.
ExternalRequest_pre: The object is ready to make the following
external request: ‘ITransactionJoin::JoinTransaction’.
ExternalRequest_post: ‘ITransactionJoin::JoinTransaction succeeded’.
The external request has completed.
Execute Extract:The task, ‘Execute Extract’, failed.

There is no ResultSet and the parameters are set correctly. Here’s the strange part, if I execute the SSIS via VS or via SSMS Integration Services or via SSMS calling our SSIS execution sproc works completely fine. However, I enlisted our DBA, who has SA access, to execute our SSIS execution sproc via SSMS and it fails with no significant error message.

enter image description here

I even had another dev run it and succeeds for him. Here is what I and the other dev saw:

enter image description here

javascript – Should try-catch blocks be used when calling functions that already have them?

In JavaScript, if I have try catch blocks in a function that is meant to be called from another function, should I also put them in the calling function or just let the called functions handle them.

Here is some pseudo code to illustrate what I mean. I have two called functions, one and two. They are essentially the same but each calls a different API and throws an error if something goes wrong. Then I have two versions of a third function, one with a try-catch block and one without.

  • Is one of these(function threes) a better practice than the other?
  • Is there a still better way to do it?
 function one async (){        
        try{
            //await some value
              // return the value
            
            // if that doesn't work throw an error
        } catch(error){
            //handle error
        }
    }
    
    function two async (){        
        try{
            //await some value
              // return the value
            
            // if that doesn't work throw an error
        } catch(error){
            //handle error
        }
    }
    
    
    function three-version-1 (){       
        try{
            // await return value from one()
                // do something with it
        
            // if that doesn't work await return value from two()
                // do something with that instead
            
            // if that doesn't work throw an error
        } catch(error){
            //errors are handled in called functions but put handle them here anyway just in case
        }
    }
    
    
    function three-version-2 async (){
        // await return value from one()
           // do something with it
        
        // if that doesn't work await return value from two()
           // do something with that instead
          
        // errors are handled in called functions so no need to handle them here
    }