Thursday, December 23, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Nuxtjs custom module

Posted: 23 Dec 2021 03:26 AM PST

I'm quite new to Nuxtjs so I made a test project which purpose is merely the (of course) testing of Nuxtjs functionalities.

Currently I'm trying to create a simple custom module: afaik a module is basically a wrapper around a vou/js library/plugin, something like a high-level integration used to expose configurations on how the underlying library/plugin is imported and used in the Nuxt application.

So I'm trying with a simple module that declare some plain js classes that I'll use in my application, e.g. Order and Product, and that's what I came out with:

Directory structure

pages    the-page.vue  modules    classes      index.js      order.js  

/modules/classes/index.js

const path = require('path')    export default function (moduleOptions) {      const { nuxt } = this        // add the debug plugin      this.addPlugin({          src: path.resolve(__dirname, 'order.js'),      })  }  

/modules/classes/order.js

class Order {      constructor(id) {          this.id = id;            console.log('created order #' + this.id);      }  }    export {Order};  

/nuxt.config.js

export default {    // ...    buildModules: [      // ...      '~/modules/classes'    ],    // ...  }  

/pages/the-page.vue

<script>  export default {    name: 'ThePage',    data () {      return {      }    },    methods: {      createOrder () {        const order = new Order(123)      }    }  }  </script>  

The error

My defined class are still not imported in my pages:

/app/pages/the-page.vue    18:13  error  'order' is assigned a value but never used  no-unused-vars    18:25  error  'Order' is not defined                      no-undef  

Considerations

Probably I'm missing something about modules usage and/or implementation, but every tutorial I found starts with too complex scenarios, and since I'm at the beginning with Nuxtjs I need something easier to implement.

Java compare strings with .equals()

Posted: 23 Dec 2021 03:26 AM PST

class Main {            public static boolean sameStarChar(String str) {          int i = 1;                    while ( i < str.length()) {              return (str.charAt(i).equals('*') && str.charAt(i - 1).equals(str.charAt(i + 1)));              i++;          }                    return false;      }  }

the program is supposed to check if the Characters before and after a "*" are the same. It seems that the problem is somewhere at charAt(i)

pls help, thx ;_;

How to use bloc to handle CheckBox in StatelessWidget?

Posted: 23 Dec 2021 03:26 AM PST

How to use bloc to handle CheckBox in StatelessWidget?

i've try using StatefulWidget and call setState(()) it's work (checkbox will checked)

but, i try using StatelessWidget and Bloc to handle state, log data look good but checkbox can't be checked

Partner State

class PartnerState extends AppState {    final List<User>? users;      PartnerState({this.users});      PartnerState.initial() : this(users: []);      PartnerState onChanged({      List<User>? users,    }) =>        PartnerState(users: users ?? this.users);      @override    List<Object?> get props => [users];      @override    bool? get stringify => true;  }  

Partner Event

class PartnerEvent extends Event {    final User? user;      PartnerEvent({this.user});  }    class AddPartnerToList extends PartnerEvent {    final User user;      AddPartnerToList({required this.user}) : super(user: user);  }    class RemovePartnerFromList extends PartnerEvent {    final User user;      RemovePartnerFromList({required this.user}) : super(user: user);  }  

Partner Form Bloc

@injectable  class PartnerFormBloc extends Bloc<PartnerState> {    PartnerFormBloc() : super(PartnerState.initial());      @override    Stream<PartnerState> mapEventToState(Event event) async* {      if (event is AddPartnerToList) {        yield currentState.onChanged(users: currentState.users?..add(event.user));      } else if (event is RemovePartnerFromList) {        yield currentState.onChanged(            users: currentState.users?..remove(event.user));      }    }  }  

Invite Partner To List

class InvitePartnerToList extends StatelessWidget {    final int orderId;    const InvitePartnerToList({Key? key, required this.orderId}) : super(key: key);      @override    Widget build(BuildContext context) {      final users = [User(displayName: 'User 1'), User(displayName: 'User 2')];      return Scaffold(        body: BlocProvider<PartnerFormBloc>(          bloc: getIt<PartnerFormBloc>(), child:          SingleChildScrollView(            child: Expanded(              child: Column(                mainAxisSize: MainAxisSize.min,                children: users.map((e) => BlocBuilder<PartnerFormBloc, PartnerState>(builder: (context, state){                  return HCheckBox<User>(value: e, selectedValues: state.users!, onChanged: (user){                    if(state.users!.contains(user)){                      context.read<PartnerFormBloc>().add(RemovePartnerFromList(user: user!));                    } else {                      context.read<PartnerFormBloc>().add(AddPartnerToList(user: user!));                    }                  }, child: PartnerItem(user: e,),);                })).toList(),              ),            ),          )),      );    }  }  

CMake find_package can't find libpng (16)

Posted: 23 Dec 2021 03:26 AM PST

I'm not the first to run into libpng issues, especially when I want to link to self-built sources on Windows. I'm using the libpng 1638 sources from https://github.com/glennrp/libpng. Semi official, the reason for this version is it has a CMake script.

Zlib is built/found and the library installs in c:\Program Files\libpng. I don't have to set CMAKE_INSTALL_PREFIX for this.

The problem occurs when doing a 'find_package(PNG 16)'. With debug flag on, a number of search directories is listed, but ultimately it fails to find the PNGConfig.cmake script that can link up to the installed paths and files.

This the command I used in the script (zlib is already found):

set(CMAKE_FIND_DEBUG_MODE TRUE)  find_package(PNG 16         PATHS "C:\\Program Files\\libpng\\lib\\libpng")  set(CMAKE_FIND_DEBUG_MODE FALSE)  

This is the output of the debug trace:

...  find_package considered the following locations for the Config module:    ...    C:/Program Files/CMake/PNGConfig.cmake    C:/Program Files/CMake/png-config.cmake    C:/Program Files (x86)/PNGConfig.cmake    C:/Program Files (x86)/png-config.cmake    C:/Program Files/libpng/lib/libpng/PNGConfig.cmake    C:/Program Files/libpng/lib/libpng/png-config.cmake  

Indeed, no png-config.cmake file can be found anywhere on my system. If we dive into the source CMakeLists.txt of libpng, we see that the section to create these config scripts has been deliberately disabled for Win_32 systems:

  # Install the pkg-config files.    if(NOT CMAKE_HOST_WIN32 OR CYGWIN OR MINGW)      install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libpng.pc              DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)      install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/libpng-config              DESTINATION ${CMAKE_INSTALL_BINDIR})      install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PNGLIB_NAME}.pc              DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)      install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${PNGLIB_NAME}-config              DESTINATION ${CMAKE_INSTALL_BINDIR})    endif()  

Since I don't want to dabble in the source files (which ultimately are pulled from the web directly), I want to understand. Why would this be disabled for native Win32 builds? (most of the online info uses the linux subsystem or a package manager.. ) obviously other packages like Zlib all have their config files properly copied to the install folders where FindXXX.cmake scripts can pick them up properly.

For completeness, here is the output of the libpng build (msvc)

  -- Install configuration: "Debug"    -- Installing: C:/Program Files/libpng/lib/libpng16d.lib    -- Installing: C:/Program Files/libpng/bin/libpng16d.dll    -- Installing: C:/Program Files/libpng/lib/libpng16_staticd.lib    -- Installing: C:/Program Files/libpng/include/png.h    -- Installing: C:/Program Files/libpng/include/pngconf.h    -- Installing: C:/Program Files/libpng/include/pnglibconf.h    -- Installing: C:/Program Files/libpng/include/libpng16/png.h    -- Installing: C:/Program Files/libpng/include/libpng16/pngconf.h    -- Installing: C:/Program Files/libpng/include/libpng16/pnglibconf.h    -- Installing: C:/Program Files/libpng/bin/pngfix.exe    -- Installing: C:/Program Files/libpng/bin/png-fix-itxt.exe    -- Installing: C:/Program Files/libpng/share/man/man3/libpng.3    -- Installing: C:/Program Files/libpng/share/man/man3/libpngpf.3    -- Installing: C:/Program Files/libpng/share/man/man5/png.5    -- Installing: C:/Program Files/libpng/lib/libpng/libpng16.cmake    -- Installing: C:/Program Files/libpng/lib/libpng/libpng16-debug.cmake  

All insight greatly appreciated!

How to handle the set the timezone to MST in Spring batch application that runs in AKS which follows UTC?

Posted: 23 Dec 2021 03:26 AM PST

I have a Spring batch application running in a VM hosted in MTC timezone. I am migrating this application to AKS which follows UTC.

I want to set MTC as my default timezone due to the business logic.

I could see the below options

  1. Update the individual line of code to convert the UTC to MTC - not an efficient way.
  2. Set the Default timezone - How to do this in spring batch? I could see this for spring boot but not for spring batch
  3. Set Timezone at Container level (https://medium.com/@yildirimabdrhm/kubernetes-timezone-management-8cc139b01f9d)

Please suggest?

Add slides based on slide position numbers using officer package

Posted: 23 Dec 2021 03:26 AM PST

I am creating a Power Point presentation using Officer. Let's say I have created a 10 pages slides (named 10_slides_ppt.pptx) using for loop based a blank.pptx.

My question is, is there a way that I can add one slide before slides with position number of c(3, 6, 9)?

The final ppt will like this:

1, 2, (new slide 1), 3, 4, 5, (new slide 2), 6, 7, 8, (new slide 3), 9, 10

.

Code:

library(officer)    current_pres <- read_pptx('10_slides_ppt.pptx')   # To add new slide 1, but I don't know how to set position of slide  final_pres <- add_slide(current_pres, layout = "Title and Content", master = "Office Theme") %>%     ph_with(my_pres, value = "heading", location = ph_location_type(type = "title")) %>%     add_slide(my_pres, layout = "Title and Content", master = "Office Theme") %>%     ph_with(my_pres, value = "heading", location = ph_location_type(type = "title")) %>%     add_slide(my_pres, layout = "Title and Content", master = "Office Theme") %>%     ph_with(my_pres, value = "heading", location = ph_location_type(type = "title"))  

How to encode nested objects into JSON (Swift)?

Posted: 23 Dec 2021 03:26 AM PST

I have such an object that should be encoded to JSON (My Playground example)

struct Toy: Codable {      var name: String            enum GiftKeys: String, CodingKey {          case toy = "name"      }            func encode(to encoder: Encoder) throws {          var container = encoder.container(keyedBy: GiftKeys.self)          try container.encode(self, forKey: .toy)      }  }    struct Employee: Encodable {      var name: String      var id: Int      var favoriteToy: Toy            enum CodingKeys: CodingKey {          case name, id      }            func encode(to encoder: Encoder) throws {          var container = encoder.container(keyedBy: CodingKeys.self)          try container.encode(name, forKey: .name)          try container.encode(id, forKey: .id)          try favoriteToy.encode(to: encoder)      }  }    do {      let toy = Toy(name: "Teddy Bear")      let employee = Employee(name: "John Appleseed", id: 7, favoriteToy: toy)            let encoder = JSONEncoder()      let nestedData: Data = try encoder.encode(employee)      let nestedString = String(data: nestedData, encoding: .utf8)!      print(nestedString)  }  

What I am going to achieve is that each object knows how to encode itself. So, in my example when I through the employee object to the encoder, so each of the objects (employee and Toy) is responsible for its encoding.

But when I try to run the example in the Playground looks like it comes to the stuck in the line try favoriteToy.encode(to: encoder)

What is the problem here?

Why do I need to add the .js extension when importing files in typescript but not in Angular imports?

Posted: 23 Dec 2021 03:25 AM PST

In my typescript project I need to add the *.js extension when doing imports, otherwise the project will build but it will fail at runtime in the browser because it cannot find the file.

This is what my typescript imports look like:

import {MainApp} from './MainApp.js';    window.onload = () => {    var app = new MainApp(5);    app.doSomething();    };  

From what I have read (Appending .js extension on relative import statements during Typescript compilation (ES6 modules) for example) it seems a normal thing for typescript that I cannot do this: import {MainApp} from './MainApp.js';

But the thing is that in Angular using typescript I can do this:

import {MainApp} from './MainApp';  

So, how it is Angular doing it? There is a way I can replicate that behavior in my non angular, pure typescript project?

SQL Server Sum function Should return 0 for a value 0

Posted: 23 Dec 2021 03:26 AM PST

my data looks like this.

shipped_days Weeks Counts
day1 1 230
day1 1 30
day1 1 20
day2 1 0
day3 1 100
day3 1 230

when I am doing a sum of counts grouping by weeks and shipped_days entire row of day2 is missing in my final report. I still wanted to have that record as 0 this is what I am seeing

shipped_days Weeks Counts
day1 1 280
day3 1 330

but my desired output should be:

shipped_days Weeks Counts
day1 1 280
day2 1 0
day3 1 330

here is my query:

select sum(counts), shipped_days, weeks  from table xyz  group by shipped_days, weeks  

what is that I have to do so that I can have day2 record as well?

Thanks in advance

react-bootstrap positioning of control elements in table header

Posted: 23 Dec 2021 03:25 AM PST

I would like to create a react-bootstrap table with some control elements in the header and I am having trouble getting them to position correctly. Schematically, this is what I'm trying to do:

<th>    <div>Some Title</div>    <Button>B1</Button>    <InputGroup className="flex-nowrap" size="sm">      <Button>B2</Button>      <Button>B3</Button>      <FormControl className="smallInput"/>    </InputGroup>  </th>  

The buttons B1, B2 and B3 should always have their natural width and the FormControl should have a pre-defined width of 3em. I do the latter with the following css:

.smallInput {      flex-grow: 0 !important;      flex-basis: 3em !important;  }  

I want to position the controls on the right side of the header. They should always be as small as they possibly can be and leave the rest of the space for the title.

I have experimented with various combinations of Container, Row, Col, div and CSS classes like w-auto, d-flex, d-inline-block etc. but I can't get the positioning right. Either the controls use up more space then they need to or they get wrapped in various unappealing ways.

I am fairly new to all of React/Bootstrap/CSS, so I'm not really sure what the right approach is here. I've been trying to convince the title div and the controls to use the minimum amount of width possible without wrapping and then use flex-box functionality to push the title div to the left and the rest to the right. Is that even the right way to go about it?

```how i build my team superset,we will need id in product```

Posted: 23 Dec 2021 03:25 AM PST

I use python env and pin install superset , bud it not have superset-ui dir. so, we can not develop. I need use docker or other? thank u,hope have friend answer me.

Retrieved Cloudwatch logs out of order

Posted: 23 Dec 2021 03:25 AM PST

We use AWS Cloudwatch Logs, and are retrieving a set of logs using AWS SDKs cloudwatch client's filterLogEvents function, and are pushing the logs to S3. For log groups with about 5000 events, we could see that the retrieved logs were out of order. For example, we would receive the logs till 11:35 UTC and the next log would be 14:42 UTC. We checked in cloudwatch and found that there were more logs between 11:35 UTC - 14:42 UTC. The logs during that time were present after a bunch of other logs.

I want to know why there is an inconsistency in the logs. Why are some set of logs obtained in the correct order, while some logs are placed somewhere else. All the logs seem to be present when we try to retrieve them, but the order for some of the logs is messed up.

ho can i call getwallet function and filter list which has balance more than 0

Posted: 23 Dec 2021 03:25 AM PST

My data is nested object data (objects) from an apiand data format is { "info": { "makerCommission": "10", "takerCommission": "10", "buyerCommission": "0", "sellerCommission": "0", "canTrade": true, "canWithdraw": true, "canDeposit": true, "updateTime": "1639767562245", "accountType": "SPOT", "balances": [ { "asset": "BTC", "free": 0.00000371, "locked": 0.00000000 }, { "asset": "LTC", "free": 0.00000769, "locked": 0.00000000 } }.I am trying to call a function in datasrc and passing a value info.balances but it is giving an error. i can pass 'info.balances' and access the data but i want to filter the data before passing it to the column so i can get only those value which are greater than 0 so if anyone can help.

<!DOCTYPE html>      <html lang="en">      <head>          <title>Comment</title>          <meta charset="utf-8">          <meta name="viewport" content="width=device-width, initial-scale=1">          <!-- <link rel="stylesheet" type="text/css" href="style.css"> -->                    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>          <!-- CSS only -->      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">      <!-- JavaScript Bundle with Popper -->      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>                  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet">      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js"></script>      </head>      <body>  
<div id="main">      <table id="table_id" cellspacing="0" width="100%">          <thead>              <tr class="bg-dark">                  <th class="grey">asset</th>                  <th class="grey">free</th>                  <th class="grey">locked</th>              </tr>          </thead>      </table>  </div>  
<script>      function getWalletJSON(data) {          console.log(46, data);          let arr = data.filter(function(elem) {              console.log((elem.free > 0));          return (elem.free > 0)          });      }  </script>    <script>      $(document).ready(function(){              $('#table_id').DataTable( {                  ajax: {                      // url: 'https://jsonplaceholder.typicode.com/comments',                      url: 'http://design.trailingcrypto.com/api/trade/balances?exchange=binance',                      dataSrc: getWalletJSON(info.balances)                  },                  columns: [                          // { data: 'asset'},                          {   data: null,                              orderable: false,                              className: 'hvhb',                              render: function (data, type, row, ){                                  let newdata ='';                              //     if(data.free >= 1 ){                              // //    console.log(data.asset);\                              //  newdata = `${data.asset}`                              // // return newdata;                              //     }                              //     return newdata;                              if(data.free >0 ) newdata = newdata + `</br>(${data.asset})`;                              console.log(newdata);                              return newdata;                               }                          },                          // { data: 'free'},                                                    {   data: null,                              orderable: false,                              className: 'hvhb',                              render: function (data, type, row, ){                                  // if(data.free >= 1 ){                              //    console.log(data.free);                              let newdata = `${data.free}`;                              return newdata;                                  }                                                                },                                                    // { data: 'locked'},                      ]          });      })  </script>  

Android : add a button that stay in the bottom of a scrollable page

Posted: 23 Dec 2021 03:25 AM PST

I have a subscription page where I describe all the premium features in the app. You can scroll down the content. I would like to add on top of that content a button "Buy" that sticks to the bottom of the screen even when scrolling.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:app="http://schemas.android.com/apk/res-auto"  android:layout_width="match_parent"  android:layout_height="wrap_content">      <Button      android:id="@+id/button"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:text="BUY"      android:layout_alignParentBottom="true"      app:layout_constraintBottom_toBottomOf="parent"      app:layout_constraintEnd_toEndOf="parent"      app:layout_constraintStart_toStartOf="parent" />    // lots of views :)  <TextView    ...  />    </androidx.constraintlayout.widget.ConstraintLayout>  

This code does not work because the button appears at the bottom of the scrolled content, and does not stick to the bottom of the screen. I have tried with or without android:layout_alignParentBottom="true", but it does not change...

Using insecure protocols with repositories, without explicit opt-in, is unsupported

Posted: 23 Dec 2021 03:24 AM PST

I am using gradle 4.8. I want to create an elasticsearch plugin. I am using jdk9. The elasticsearch version, I am using is 5.6.16. When I clicked on the build button inside intellij idea, It is giving me the below error:

Could not resolve all dependencies for configuration ':classpath'.  

Using insecure protocols with repositories, without explicit opt-in, is unsupported. Switch Maven repository 'maven4(http://35.164.44.153/artifactory/jcenter)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols. See https://docs.gradle.org/7.3.1/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details.

Cannot run peer because error when setting up MSP

Posted: 23 Dec 2021 03:24 AM PST

I have this network structure and I should do the creation, when I launch the create_network.sh script, I get the following error message:
** CET [main] InitCmd -> ERRO 001 Cannot run peer because error when setting up MSP of type bccsp from directory /home/matteo/Immagini/test-network/org2.example.com/org2admin.org2.example.com/channels/mychannel/../../certs/msp: Setup error: nil conf reference**

[docker-compose.yaml][1]      [config.yaml + error][2]    [create_network.sh + docker images][3]      [1]: https://i.stack.imgur.com/bzBDs.png    [2]: https://i.stack.imgur.com/KYFLu.png    [3]: https://i.stack.imgur.com/OTm82.png  

I have test-network tree:

<pre>  <span style="background-color:#26A269"><font color="#12488B">test-network</font></span>  ├── <font color="#12488B"><b>bin</b></font>  │   ├── <font color="#26A269"><b>configtxgen</b></font>  │   ├── <font color="#26A269"><b>configtxlator</b></font>  │   ├── <font color="#26A269"><b>cryptogen</b></font>  │   ├── <font color="#26A269"><b>discover</b></font>  │   ├── <font color="#26A269"><b>fabric-ca-client</b></font>  │   ├── <font color="#26A269"><b>fabric-ca-server</b></font>  │   ├── <font color="#26A269"><b>idemixgen</b></font>  │   ├── <font color="#26A269"><b>orderer</b></font>  │   └── <font color="#26A269"><b>peer</b></font>  ├── <font color="#26A269"><b>bin.sh</b></font>  ├── <font color="#26A269"><b>create_network.sh</b></font>  ├── <font color="#12488B"><b>ordererOrg.example.com</b></font>  │   ├── <font color="#12488B"><b>ca.ordererOrg.example.com</b></font>  │   │   ├── <font color="#12488B"><b>client</b></font>  │   │   │   ├── <font color="#12488B"><b>ca</b></font>  │   │   │   ├── fabric-ca-client-config.yaml  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── config.yaml  │   │   │   │   └── <font color="#12488B"><b>tlscacerts</b></font>  │   │   │   └── <font color="#12488B"><b>tlsca</b></font>  │   │   ├── <font color="#12488B"><b>server</b></font>  │   │   │   ├── ca-cert.pem  │   │   │   ├── docker-compose.yaml  │   │   │   ├── fabric-ca-server-config.yaml  │   │   │   ├── fabric-ca-server.db  │   │   │   ├── IssuerPublicKey  │   │   │   ├── IssuerRevocationPublicKey  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── <font color="#12488B"><b>cacerts</b></font>  │   │   │   │   ├── <font color="#12488B"><b>keystore</b></font>  │   │   │   │   │   ├── 7c54036e4b78ca3fb367969e477f4790ab326166b04919081f94156aff36a9c4_sk  │   │   │   │   │   ├── bc7c57a5815b04184f0c94e626e713a61d7d45889af58c11cec185d4d489e33c_sk  │   │   │   │   │   ├── IssuerRevocationPrivateKey  │   │   │   │   │   └── IssuerSecretKey  │   │   │   │   ├── <font color="#12488B"><b>signcerts</b></font>  │   │   │   │   └── <font color="#12488B"><b>user</b></font>  │   │   │   └── tls-cert.pem  │   │   ├── start.sh  │   │   └── stop.sh  │   ├── connection-profile.json  │   ├── <font color="#12488B"><b>ordererAdmin.ordererOrg.example.com</b></font>  │   │   ├── bin.sh  │   │   ├── <font color="#12488B"><b>certs</b></font>  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   └── config.yaml  │   │   │   └── <font color="#12488B"><b>tls</b></font>  │   │   └── <font color="#12488B"><b>channels</b></font>  │   └── <font color="#12488B"><b>orderer.ordererOrg.example.com</b></font>  │       ├── <font color="#12488B"><b>certs</b></font>  │       │   ├── <font color="#12488B"><b>msp</b></font>  │       │   │   ├── config.yaml  │       │   │   └── <font color="#12488B"><b>keystore</b></font>  │       │   └── <font color="#12488B"><b>tls</b></font>  │       ├── <font color="#12488B"><b>docker</b></font>  │       │   ├── docker-compose.yaml  │       │   ├── <font color="#12488B"><b>genesis</b></font>  │       │   │   └── <font color="#12488B"><b>genesis.block</b></font>  │       │   └── <font color="#12488B"><b>tmp</b></font>  │       ├── start.sh  │       └── stop.sh  ├── <font color="#12488B"><b>org1.example.com</b></font>  │   ├── <font color="#12488B"><b>ca.org1.example.com</b></font>  │   │   ├── <font color="#12488B"><b>client</b></font>  │   │   │   ├── <font color="#12488B"><b>ca</b></font>  │   │   │   ├── fabric-ca-client-config.yaml  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── config.yaml  │   │   │   │   └── <font color="#12488B"><b>tlscacerts</b></font>  │   │   │   └── <font color="#12488B"><b>tlsca</b></font>  │   │   ├── <font color="#12488B"><b>server</b></font>  │   │   │   ├── ca-cert.pem  │   │   │   ├── docker-compose.yaml  │   │   │   ├── fabric-ca-server-config.yaml  │   │   │   ├── fabric-ca-server.db  │   │   │   ├── IssuerPublicKey  │   │   │   ├── IssuerRevocationPublicKey  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── <font color="#12488B"><b>cacerts</b></font>  │   │   │   │   ├── <font color="#12488B"><b>keystore</b></font>  │   │   │   │   │   ├── 119d8c415a59cff634582a3ab916fc47ea6babb46e9a63c290570b8367160b1b_sk  │   │   │   │   │   ├── 8a1a85dea87fafe0fa20f2b300481662e56057972213114cbd17cddc52403b0a_sk  │   │   │   │   │   ├── IssuerRevocationPrivateKey  │   │   │   │   │   └── IssuerSecretKey  │   │   │   │   ├── <font color="#12488B"><b>signcerts</b></font>  │   │   │   │   └── <font color="#12488B"><b>user</b></font>  │   │   │   └── tls-cert.pem  │   │   ├── start.sh  │   │   └── stop.sh  │   ├── connection-profile.json  │   ├── <font color="#12488B"><b>org1admin.org1.example.com</b></font>  │   │   ├── bin.sh  │   │   ├── <font color="#12488B"><b>certs</b></font>  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── config.yaml  │   │   │   │   ├── <font color="#12488B"><b>keystore</b></font>  │   │   │   │   └── <font color="#12488B"><b>signcerts</b></font>  │   │   │   └── <font color="#12488B"><b>tls</b></font>  │   │   └── <font color="#12488B"><b>channels</b></font>  │   │       └── <font color="#12488B"><b>mychannel</b></font>  │   │           ├── core.yaml  │   │           ├── create.sh  │   │           ├── join.sh  │   │           └── <font color="#12488B"><b>tx</b></font>  │   ├── <font color="#12488B"><b>peer0.org1.example.com</b></font>  │   │   ├── <font color="#12488B"><b>certs</b></font>  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── config.yaml  │   │   │   │   └── <font color="#12488B"><b>keystore</b></font>  │   │   │   └── <font color="#12488B"><b>tls</b></font>  │   │   ├── <font color="#12488B"><b>docker</b></font>  │   │   │   ├── docker-compose.yaml  │   │   │   └── <font color="#12488B"><b>tmp</b></font>  │   │   ├── start.sh  │   │   └── stop.sh  │   └── <font color="#12488B"><b>user1.org1.example.com</b></font>  │       └── <font color="#12488B"><b>certs</b></font>  │           ├── <font color="#12488B"><b>msp</b></font>  │           │   └── config.yaml  │           └── <font color="#12488B"><b>tls</b></font>  ├── <font color="#12488B"><b>org2.example.com</b></font>  │   ├── <font color="#12488B"><b>ca.org2.example.com</b></font>  │   │   ├── <font color="#12488B"><b>client</b></font>  │   │   │   ├── <font color="#12488B"><b>ca</b></font>  │   │   │   ├── fabric-ca-client-config.yaml  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── config.yaml  │   │   │   │   └── <font color="#12488B"><b>tlscacerts</b></font>  │   │   │   └── <font color="#12488B"><b>tlsca</b></font>  │   │   ├── <font color="#12488B"><b>server</b></font>  │   │   │   ├── ca-cert.pem  │   │   │   ├── docker-compose.yaml  │   │   │   ├── fabric-ca-server-config.yaml  │   │   │   ├── fabric-ca-server.db  │   │   │   ├── IssuerPublicKey  │   │   │   ├── IssuerRevocationPublicKey  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── <font color="#12488B"><b>cacerts</b></font>  │   │   │   │   ├── <font color="#12488B"><b>keystore</b></font>  │   │   │   │   │   ├── 2b1147e705aa9f1b0ad0aa549efd4f89f7f0f6a7e5b5e8bcfda488e265d1eecd_sk  │   │   │   │   │   ├── a19c047c35474e4d8d51216cc7c3029b50f1465017a3ce9f7de869e526c33cf2_sk  │   │   │   │   │   ├── IssuerRevocationPrivateKey  │   │   │   │   │   └── IssuerSecretKey  │   │   │   │   ├── <font color="#12488B"><b>signcerts</b></font>  │   │   │   │   └── <font color="#12488B"><b>user</b></font>  │   │   │   └── tls-cert.pem  │   │   ├── start.sh  │   │   └── stop.sh  │   ├── connection-profile.json  │   ├── <font color="#12488B"><b>org2admin.org2.example.com</b></font>  │   │   ├── bin.sh  │   │   ├── <font color="#12488B"><b>certs</b></font>  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── config.yaml  │   │   │   │   ├── <font color="#12488B"><b>keystore</b></font>  │   │   │   │   └── <font color="#12488B"><b>signcerts</b></font>  │   │   │   └── <font color="#12488B"><b>tls</b></font>  │   │   └── <font color="#12488B"><b>channels</b></font>  │   │       └── <font color="#12488B"><b>mychannel</b></font>  │   │           ├── core.yaml  │   │           ├── create.sh  │   │           ├── join.sh  │   │           └── <font color="#12488B"><b>tx</b></font>  │   ├── <font color="#12488B"><b>peer0.org2.example.com</b></font>  │   │   ├── <font color="#12488B"><b>certs</b></font>  │   │   │   ├── <font color="#12488B"><b>msp</b></font>  │   │   │   │   ├── config.yaml  │   │   │   │   └── <font color="#12488B"><b>keystore</b></font>  │   │   │   └── <font color="#12488B"><b>tls</b></font>  │   │   ├── <font color="#12488B"><b>docker</b></font>  │   │   │   ├── docker-compose.yaml  │   │   │   └── <font color="#12488B"><b>tmp</b></font>  │   │   ├── start.sh  │   │   └── stop.sh  │   └── <font color="#12488B"><b>user1.org2.example.com</b></font>  │       └── <font color="#12488B"><b>certs</b></font>  │           ├── <font color="#12488B"><b>msp</b></font>  │           │   └── config.yaml  │           └── <font color="#12488B"><b>tls</b></font>  ├── README  ├── <font color="#26A269"><b>start_network.sh</b></font>  └── <font color="#26A269"><b>stop_network.sh</b></font>  </pre>  

Removing 0s from dataframe without removing NAs

Posted: 23 Dec 2021 03:24 AM PST

I try to create a subset, where I remove all answers == 0 for variable B, given another variable A == 1. However, I want to keep the NAs in Variable B (just remove the 0s).

I tried it with this df2 <- subset(df, B[df$A == 1] > 0) but the result makes no sense. Can someone help?

i <- c(1:10)  A <- c(0,1,1,1,0,0,1,1,0,1)  B <- c(0, 10, 13, NA, NA, 9, 0, 0, 3, NA)  df <- data.frame(i, A, B)    

How do you put two images side by side with captions

Posted: 23 Dec 2021 03:25 AM PST

I am trying to put two images side by side in Jupyter's markdown. We can use html but I am unable to put two images side by side with caption. I tried every option in here but did not work.

<figure>  <img src='aaa.png' width="350" height="350" align="center"/>      <figcaption align = "center"><b>Fig 2.5; Courtesy of Linear Algebra: Theory, Intuition, Code by Mike X Cohen</b></figcaption>  <img src='bbb.png' width="350" height="350" align="center"/>      <figcaption align = "center"><b>Fig 2.3; Courtesy of Linear Algebra: Theory, Intuition, Code by Mike X Cohen</b></figcaption>  </figure>  

What is the most accurate way of getting a computer's real world location in python

Posted: 23 Dec 2021 03:26 AM PST

What is the most accurate way of a getting a computer's real world location in python. I want to get the most precise location of the pc the script is running on(like my pc for eg) :

what I tried and possible solutions(most are not so accurate) :

  1. Location of ip address using geocoder module https://geocoder.readthedocs.io/providers/IPInfo.html (not so accurate and inconsistent results)
  2. Scraping data from https://mycurrentlocation.net/ (More accurate but still wrong district it is pointing to)
  3. This is a theoretical one, take image from webcam using python scan it for exif data hopefully get GPS data but python opencv(https://pypi.org/project/opencv-python/) is the most used module to take image using webcam but it doesn't write exif data I would like to hear answers regarding this as I would like to use this one for my project
  4. Using systeminfo command in cmd https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/systeminfo and get time zone (least accurate as it shows many locations)
  5. Searching my current location on google and scraping that data(wild results)
  6. This is the most I am unsure about if the person is using wifi and get the location of cell phone towers nearby and triangulate the location I don't know if it's possible so
  7. This is also wifi related if somebody is using wifi on their phone in the same network , somehow get the location of the phone (so it should be near 30 meters) I am also unsure about this one

How do I go on about this I want the most accurate result possible like down to the street if possible and what ways can I achieve this and how can I achieve this in python I think 3rd one has the most potential so how do I do that my python version is 3.8.8 and os windows 7 Thanks and have a great day

Rolling averages in SQL for assets which are added progressively to the population

Posted: 23 Dec 2021 03:25 AM PST

My data-table has various assets along with the groups they belong to and the date of entry into that group/population/data-table.

Now I can calculate the average age of the assets but how would I actually go about calculating an average age over a period of time so for example for Group A, I can calculate it for Assets SN 001 and SN 004 but how do I go about getting a running average since Date of Entry and in a Year-on-Year format.

I apologise if I am unclear, I would be happy to elaborate.

Asset Group Date of Entry
SN 001 A 2011-01-01
SN 002 B 2014-06-01
SN 003 C 2015-01-01
SN 004 A 2018-06-01
SN 005 B 2019-01-01
SN 006 C 2021-06-01

Desired Result: Where # is the average age and changes based on the addition of Assets to each group and adjusts accordingly.

Date of Entry (Y) AVG_Group A AVG_Group B AVG_Group C
2011 # # #
2012 # # #
2013 # # #
2014 # # #
2015 # # #
2016 # # #
2017 # # #
2018 # # #
2019 # # #
2020 # # #
2021 # # #

React state not giving correct value on useEffect()

Posted: 23 Dec 2021 03:26 AM PST

I'm trying to build a factorization algorithm using react. I'm struggling to add results to LocalStorage based on results from factorization: LocalStorage sets previous results not current ones... I think this is happening because useEffect runs on every new [number] (=user input) and not based on [results]. However, I need useEffect to run on new user input submition because that's when all the things have to run.

Here is the code:

const [results, setResults] = useState({    default: [],    detailed: [],    isPrime: '',  });    useEffect(() => {    if (!localStorage.getItem(number)) {      handleWorker(number);    } else {      setAboutExecution('Retrieved from localStorage');      setResults(JSON.parse(localStorage.getItem(number));    }    //accessing results here will give previous results  }, [number]); //number is user input from another component     const handleWorker = number => {    try {      const worker = new Worker(new URL('facto.js', import.meta.url));      worker.postMessage({ number, algorithm });      worker.onmessage = ({ data: { facto, about } }) => {        setResults({ ...facto });        setAboutExecution(about);        if (about !== 'operating...') worker.terminate()      };    } catch(error) {      setAboutExecution('Sorry, an error happened')    } finally {      localStorage.setItem(number, results)      //here, results is not current state but previous one    }  };  

Please not that everything else works fine

thanks

How can the DB instance know that it should be placed in the private address range specified inside a VPC?

Posted: 23 Dec 2021 03:25 AM PST

I was looking at Terraform's documentation on how to configure a private IP for a SQL database. There, they configure a private address inside a VPC.

resource "google_compute_global_address" "private_ip_address" {    provider = google-beta      name          = "private-ip-address"    purpose       = "VPC_PEERING"    address_type  = "INTERNAL"    prefix_length = 16    network       = google_compute_network.private_network.id  }    resource "google_service_networking_connection" "private_vpc_connection" {    provider = google-beta      network                 = google_compute_network.private_network.id    service                 = "servicenetworking.googleapis.com"    reserved_peering_ranges = [google_compute_global_address.private_ip_address.name]  }  

Afterwards, they configure the DB and specify the network (not the private address):

resource "google_sql_database_instance" "instance" {    provider = google-beta      name             = "private-instance-${random_id.db_name_suffix.hex}"    region           = "us-central1"    database_version = "MYSQL_5_7"      depends_on = [google_service_networking_connection.private_vpc_connection]      settings {      tier = "db-f1-micro"      ip_configuration {        ipv4_enabled    = false        # Why is the network and not the address referenced?        private_network = google_compute_network.private_network.id      }    }  }  

How can the DB instance know that it should be placed in the private address range specified? Is everything going to be placed in that range? are existing resources moved to those IPs? What happens if more than one google_service_networking_connection is defined? How the DB instance 'decides' where to go?

Also, what happens if I define a range of 1 address (10.0.0.1/32)? Is it going to be enough for 1 db instance?

Why does creating a branch and pushing it to the remote result in conflicts on pulling?

Posted: 23 Dec 2021 03:25 AM PST

For some reason I am experiencing a problem with pulling a new branch from the remote after pushing it. I just have created a branch test from master and added some simple changes to both test and master without any kind of merging and that results in a problem:

git on  master   ❯ git branch test    git on  master   ❯ git st    git on  master   ❯ echo "4" >> content     git on  master [!] took 7s   ❯ git add content     git on  master [+]   ❯ git ci -m "added 4"  [master eff5df4] added 4   1 file changed, 1 insertion(+)    git on  master [⇡]   ❯ git co test  Switched to branch 'test'    git on  test   ❯ echo "5" >> content     git on  test [!] took 6s   ❯ git add content ; git ci -m "added 5"  [test 86ec659] added 5   1 file changed, 1 insertion(+)    git on  master [⇡]   ❯ git log --oneline --all  86ec659 (test) added 5  eff5df4 (HEAD -> master) added 4  a5d72eb (tag: 0.3) added 3  84eded8 (tag: 0.2) added 3  a449cf1 (tag: 0.1, origin/master) added 3  9bf71a6 (tag: 0.0) added 3    git on  master [⇡?]   ❯ git push origin test  Enumerating objects: 5, done.  Counting objects: 100% (5/5), done.  Delta compression using up to 8 threads  Compressing objects: 100% (2/2), done.  Writing objects: 100% (3/3), 272 bytes | 272.00 KiB/s, done.  Total 3 (delta 1), reused 0 (delta 0), pack-reused 0  remote: Resolving deltas: 100% (1/1), completed with 1 local object.  remote:   remote: Create a pull request for 'test' on GitHub by visiting:  remote:      https://github.com/[my-repo]/pull/new/test  remote:   To https://github.com/[my-repo].git   * [new branch]      test -> test    git on  master    ❯ cd ../my-repo    my-repo on  master [⇡]   ❯ git pull  remote: Enumerating objects: 8, done.  remote: Counting objects: 100% (8/8), done.  remote: Compressing objects: 100% (2/2), done.  remote: Total 6 (delta 3), reused 5 (delta 2), pack-reused 0  Unpacking objects: 100% (6/6), 421 bytes | 421.00 KiB/s, done.  From https://github.com/[my-repo]     a449cf1..eff5df4  master     -> origin/master   * [new branch]      test       -> origin/test  hint: You have divergent branches and need to specify how to reconcile them.  hint: You can do so by running one of the following commands sometime before  hint: your next pull:  hint:   hint:   git config pull.rebase false  # merge (the default strategy)  hint:   git config pull.rebase true   # rebase  hint:   git config pull.ff only       # fast-forward only  hint:   hint: You can replace "git config" with "git config --global" to set a default  hint: preference for all repositories. You can also pass --rebase, --no-rebase,  hint: or --ff-only on the command line to override the configured default per  hint: invocation.  fatal: Need to specify how to reconcile divergent branches.    my-repo on  master [⇕]   ❯ git pull --rebase  Auto-merging content  CONFLICT (content): Merge conflict in content  error: could not apply 84eded8... added 3  hint: Resolve all conflicts manually, mark them as resolved with  hint: "git add/rm <conflicted_files>", then run "git rebase --continue".  hint: You can instead skip this commit: run "git rebase --skip".  hint: To abort and get back to the state before "git rebase", run "git rebase --abort".  Could not apply 84eded8... added 3    my-repo on  HEAD (eff5df4) (REBASING 1/2) [=]   ❯ git rebase --skip  Auto-merging content  CONFLICT (content): Merge conflict in content  error: could not apply a5d72eb... added 3  hint: Resolve all conflicts manually, mark them as resolved with  hint: "git add/rm <conflicted_files>", then run "git rebase --continue".  hint: You can instead skip this commit: run "git rebase --skip".  hint: To abort and get back to the state before "git rebase", run "git rebase --abort".  Could not apply a5d72eb... added 3    my-repo on  HEAD (eff5df4) (REBASING 2/2) [=]   ❯ git rebase --skip  Successfully rebased and updated refs/heads/master.  

Moreover, If I try to find the branch, to which recent commits belong, it shows nothing in the cases of commits that showed up during conflict resolution:

my-repo on  master   ❯ git branch --contains 86ec659    test    my-repo on  master   ❯ git branch --contains eff5df4  * master    my-repo on  master   ❯ git branch --contains a5d72eb    my-repo on  master   ❯ git branch --contains 84eded8    my-repo on  master   ❯ git branch --contains a449cf1  * master    test    my-repo on  master   ❯ git branch --contains 9bf71a6  * master    test  

Why does pull result in a conflict? I just created a standalone branch without merging, my perception is that it should not happen. How could I achieve seamless working flow with the remote? Is this a bug in git? My git --version is 2.34.1. Thanks for the help in advance.

Converting QMap<QString, QString> to Json string results empty

Posted: 23 Dec 2021 03:25 AM PST

I have a function defined and used as this:

// usage:  QMap<QString, QString> map = ...;  foo(map);    // defination:  QString stringMapToJson(const QMap<QString, QString>& arg) {      QVariant v = QVariant::fromValue(arg);      JsonDocument doc = QJsonDocument::fromVariant(v);      ...  }  

Then I realized v is empty.

  1. Is there a method to convert QMap<String, QString> to QMap<String, QVariant>, so above v could be valid?
  2. Why above v is empty? I read people were saying QVariant and qMetaData, I don't understand given the following valid, why QString have a qMetaData problem:
QString s = "";  QVariant v = s;  

(A Java programmer starts her pleasant C++ journey.)

Thanks.

how to read a large image by lines with python

Posted: 23 Dec 2021 03:26 AM PST

I am trying to process some satellite photo with the size over 1G. I code in python, and I have tried in these ways.

image = np.array(io.imread(each_dir))  image = np.array(TiffImagePlugin.open(each_dir))  image = np.array(Image.open(each_dir))  

Only io.read works with photos with size of 200Mb, when the size is larger than 1G, there's an error MemoryError: Unable to allocate 17.1 GiB for an array with shape (156105, 39136, 3) and data type uint8

I have changed my RAM from 16g to 32g, but this doesn't work. So I 'd like to ask is there a way to read the imgae by lines but not read the whole image in a time ? Thank you very much.

Getting "TypeError: 'numpy.ndarray' object is not callable" from shuffle call for Fashion-MNIST

Posted: 23 Dec 2021 03:26 AM PST

I have been trying to implement Mini-Batch optimisation on a CNN with SGD. But in trying the randomised sample selection using shuffle() I am getting the error in the Title. The code is as below. Could there be a header problem or there is something about the mismatch in data types that could lead to such an error? I have tried multiple solutions on this site but they do not seem to work. Or I'm overlooking something

import numpy as np  from tensorflow.keras.utils import to_categorical  import matplotlib.pyplot as plt  %matplotlib inline  from keras.datasets import fashion_mnist  from sklearn.metrics import classification_report  from sklearn.model_selection import train_test_split  import tensorflow as tf   import keras  from keras.models import Sequential,Input,Model  from keras.layers import Dense, Dropout, Flatten  from keras.layers import Conv2D, MaxPooling2D  from tensorflow.keras.layers import BatchNormalization  from keras.layers.advanced_activations import LeakyReLU  import random  from random import shuffle    (x_train,y_train), (x_test, y_test) = fashion_mnist.load_data()    n_feature = 2  n_class = 2  n_iter = 10      def make_network(n_hidden=100):      # Initialize weights with Standard Normal random variables      model = dict(          W1=np.random.randn(n_feature, n_hidden),          W2=np.random.randn(n_hidden, n_class)      )        return model      def softmax(x):      return np.exp(x) / np.exp(x).sum()      def forward(x, model):      # Input to hidden      h = x @ model['W1']      # ReLU non-linearity      h[h < 0] = 0        # Hidden to output      prob = softmax(h @ model['W2'])        return h, prob    def backward(model, xs, hs, errs):      """xs, hs, errs contain all informations (input, hidden state, error) of all data in the minibatch"""      # errs is the gradients of output layer for the minibatch      dW2 = hs.T @ errs        # Get gradient of hidden layer      dh = errs @ model['W2'].T      dh[hs <= 0] = 0        dW1 = xs.T @ dh        return dict(W1=dW1, W2=dW2)    def sgd(model, X_train, y_train, minibatch_size):      for iter in range(n_iter):          print('Iteration {}'.format(iter))            # Randomize data point          X_train, y_train = shuffle(X_train, y_train)            for i in range(0, X_train.shape[0], minibatch_size):              # Get pair of (X, y) of the current minibatch/chunk              X_train_mini = X_train[i:i + minibatch_size]              y_train_mini = y_train[i:i + minibatch_size]                model = sgd_step(model, X_train_mini, y_train_mini)        return model    def sgd_step(model, X_train, y_train):      grad = get_minibatch_grad(model, X_train, y_train)      model = model.copy()        # Update every parameters in our networks (W1 and W2) using their gradients      for layer in grad:          # Learning rate: 1e-4          model[layer] += 1e-4 * grad[layer]        return model    def get_minibatch_grad(model, X_train, y_train):      xs, hs, errs = [], [], []        for x, cls_idx in zip(X_train, y_train):          h, y_pred = forward(x, model)            # Create probability distribution of true label          y_true = np.zeros(n_class)          y_true[int(cls_idx)] = 1.            # Compute the gradient of output layer          err = y_true - y_pred            # Accumulate the informations of minibatch          # x: input          # h: hidden state          # err: gradient of output layer          xs.append(x)          hs.append(h)          errs.append(err)        # Backprop using the informations we get from the current minibatch      return backward(model, np.array(xs), np.array(hs), np.array(errs))    minibatch_size = 50  n_experiment = 100    # Create placeholder to accumulate prediction accuracy  accs = np.zeros(n_experiment)    for k in range(n_experiment):      # Reset model      model = make_network()        # Train the model      model = sgd(model, X_train, y_train, minibatch_size)        y_pred = np.zeros_like(y_test)        for i, x in enumerate(X_test):          # Predict the distribution of label          _, prob = forward(x, model)          # Get label by picking the most probable one          y = np.argmax(prob)          y_pred[i] = y        # Compare the predictions with the true labels and take the percentage      accs[k] = (y_pred == y_test).sum() / y_test.size    print('Mean accuracy: {}, std: {}'.format(accs.mean(), accs.std()))  

Gerrit fails to start the service

Posted: 23 Dec 2021 03:26 AM PST

Environment:

OS - Ubuntu 18.04.6 LTS  Openjdk - 1.8.0_292  Gerrit - 2.16.17  MYSQL - 5.7.36  

Gerrit service was running fine. Today restarted the server and tried to start the gerrit service, But it failed to start.

$ ./gerrit.sh start  Starting Gerrit Code Review: FAILED    GERRIT_SITE\logs\error_log - file doesn't have information about failure.  
GERRIT_SITE\bin\gerrit.sh    Updated #!/bin/sh -x  
$ ./gerrit.sh start  

Last few lines of service start command.

+ running /opt/gerrit/logs/gerrit.pid  + test -f /opt/gerrit/logs/gerrit.pid  + cat /opt/gerrit/logs/gerrit.pid  + PID=8890  + ps ax -o pid  + grep -w 8890  + return 1  + echo FAILED  FAILED  + exit 1  

Further executed

$ java -jar /opt/gerrit/gerrit-2.16.17.war daemon -d /opt/gerrit/    Thu Dec 16 10:59:46 IST 2021 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.  Thu Dec 16 10:59:46 IST 2021 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.  Thu Dec 16 10:59:46 IST 2021 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.  [2021-12-16 10:59:46,648] [main] ERROR com.google.gerrit.pgm.Daemon : Unable to start daemon  com.google.gerrit.common.Die: Unable to determine SqlDialect    caused by com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure    The last packet successfully received from the server was 161 milliseconds ago.  The last packet sent successfully to the server was 151 milliseconds ago.    caused by javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)          at com.google.gerrit.pgm.util.AbstractProgram.die(AbstractProgram.java:84)          at com.google.gerrit.pgm.util.SiteProgram.createDbInjector(SiteProgram.java:226)          at com.google.gerrit.pgm.Daemon.start(Daemon.java:348)          at com.google.gerrit.pgm.Daemon.run(Daemon.java:274)          at com.google.gerrit.pgm.util.AbstractProgram.main(AbstractProgram.java:61)          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)          at java.lang.reflect.Method.invoke(Method.java:498)          at com.google.gerrit.launcher.GerritLauncher.invokeProgram(GerritLauncher.java:225)          at com.google.gerrit.launcher.GerritLauncher.mainImpl(GerritLauncher.java:121)          at com.google.gerrit.launcher.GerritLauncher.main(GerritLauncher.java:65)          at Main.main(Main.java:28)  Caused by: java.lang.RuntimeException: DbInjector failed          ... 12 more  Caused by: com.google.inject.CreationException: Unable to create injector, see the following errors:    1) Cannot create ReviewDb    while locating com.google.gerrit.server.schema.ReviewDbDatabaseProvider    while locating com.google.gwtorm.jdbc.Database<com.google.gerrit.reviewdb.server.ReviewDb>    at com.google.gerrit.server.schema.DatabaseModule.configure(DatabaseModule.java:37)    while locating com.google.gwtorm.server.SchemaFactory<com.google.gerrit.reviewdb.server.ReviewDb> annotated with @com.google.gerrit.server.schema.ReviewDbFactory()      for the 1st parameter of com.google.gerrit.server.schema.NotesMigrationSchemaFactory.<init>(NotesMigrationSchemaFactory.java:32)    at com.google.gerrit.server.schema.NotesMigrationSchemaFactory.class(NotesMigrationSchemaFactory.java:25)    while locating com.google.gerrit.server.schema.NotesMigrationSchemaFactory    while locating com.google.gwtorm.server.SchemaFactory<com.google.gerrit.reviewdb.server.ReviewDb>  Caused by: com.google.gwtorm.server.OrmException: Unable to determine SqlDialect          at com.google.gwtorm.jdbc.Database.<init>(Database.java:81)          at com.google.gerrit.server.schema.ReviewDbDatabaseProvider.get(ReviewDbDatabaseProvider.java:38)          at com.google.gerrit.server.schema.ReviewDbDatabaseProvider.get(ReviewDbDatabaseProvider.java:27)          at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:85)          at com.google.inject.internal.BoundProviderFactory.provision(BoundProviderFactory.java:77)          at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:59)          at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:61)          at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:62)          at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)          at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:168)          at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:39)          at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:42)          at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:65)          at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:113)          at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:91)          at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:306)          at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)          at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:168)          at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:39)          at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:62)          at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:211)          at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:182)          at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:109)          at com.google.inject.Guice.createInjector(Guice.java:87)          at com.google.gerrit.pgm.util.SiteProgram.createDbInjector(SiteProgram.java:196)          at com.google.gerrit.pgm.Daemon.start(Daemon.java:348)          at com.google.gerrit.pgm.Daemon.run(Daemon.java:274)          at com.google.gerrit.pgm.util.AbstractProgram.main(AbstractProgram.java:61)          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)          at java.lang.reflect.Method.invoke(Method.java:498)          at com.google.gerrit.launcher.GerritLauncher.invokeProgram(GerritLauncher.java:225)          at com.google.gerrit.launcher.GerritLauncher.mainImpl(GerritLauncher.java:121)          at com.google.gerrit.launcher.GerritLauncher.main(GerritLauncher.java:65)          at Main.main(Main.java:28)  Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure  

Mysql service running fine, With Gerrit DB user able to login to DB on terminal.

Further how do i troubleshoot? I do not have any clue to find this problem.

npm ignores git+https setting and uses git+ssh in package-lock.json

Posted: 23 Dec 2021 03:25 AM PST

We have multiple developers and an npm package that is installed form a public repository on github. while all developers usually have a github account, the CI server obviously doesn't (and usually doesn't need to).

The package from the public repository is installed using git+https://github.com/<author>/<repo>#<branch> however whenever a developer (with ssh installed) is installing another package the depencency in the package-lock.json is changed to git+ssh... which of course fails on the CI server.

is there any way to fix this behaviour?

Write to text file from multiple threads? [duplicate]

Posted: 23 Dec 2021 03:24 AM PST

i have 20 threads that write with the println() function on a file called results.txt. How can i synchronize them all?

I note every time my program run i have different number of lines of text in results.txt.

Thank you.

Making Javascript and HTML5 games

Posted: 23 Dec 2021 03:26 AM PST

A long time ago (Netscape 4-era), I wrote Javascript-based games: Pong, Minesweeper, and John Conway's Life among them. I'm getting back into it, and want to get my hands even dirtier.

I have a few games in mind:

  • Axis & Allies clone, with rugged maps and complex rules.
  • Tetris clone, possibly with real-time player-vs-player or player-vs-computer mode
  • Breakout clone, with a couple weapons and particle velocities

In all of these, I have only a few objectives:

  • Use JavaScript and HTML 5 - it should run on Chrome, Safari, or maybe an iPad.
  • Start small and simple, then build-up features.
  • Learn something new about game design and implementation.

So my questions are:

  1. How would you implement these games?
  2. Do you have any technology recommendations?
  3. If you've written these games, what was the hardest part?

N.B. I also want to start from first-principles - if you recommend a framework/library, I would appreciate some theory or implementation details behind it. These games are different enough that I should learn something new from each one.

No comments:

Post a Comment