Friday, March 19, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Exchange and office 365 calender with php and mysql

Posted: 19 Mar 2021 08:10 AM PDT

So guys, I am a JS and react frontend developer, but a I got a job to solve an app using php and mysql, there is a problem with the manage events, they are not shown or saved in the calender anymore, normally after booking an event it shows in the calender either exchange or office 365 and that is to be showns in the devide later. I don't know where to start and which file I can look for. the app is runing in a xampp local server,I checkedsome files like calender.php and calenderItem.php, but I also find under lib/Calendars 2 file Exchange.php and Outlook.php. If any will guide me I will be thankful.

I need to find an alternate for recursion to solve this problem

Posted: 19 Mar 2021 08:10 AM PDT

Suppose I have a 5x5 2D array.

00, 00, 01, 01, 00   01, 00, 01, 01, 00   01, 00, 00, 01, 01   01, 01, 00, 00, 00   01, 00, 00, 01, 01  

Criteria for grouping :- All the 1s (01s) in the array that are connected to each other from up, down, left, right or diagonally belongs to the same group.

Now, I want to group all the 1s (01s) together without recursion in such a way that my array looks like:-

00, 00, 02, 02, 00   01, 00, 02, 02, 00   01, 00, 00, 02, 02   01, 01, 00, 00, 00   01, 00, 00, 03, 03  

At last I output how many groups there are. Here, I output 3.

Say I find the connection from one index position, suppose I am at i=1 and j=0. Now using nested loops I can find all connections from the position I am at.

for(int i=-1; i<2; i++){      for(int j=-1; j<2; j++){  }}  

But how do I find the connections from a connection? Say I find all connections from i=1, j=0. If I found a 1 at i=1,j=1 then how do I continue my search again? Here recursion seems easy but how should I do this without recursion?

How to row counts from each tables in a DB based on condition

Posted: 19 Mar 2021 08:10 AM PDT

i have multiple tables in database ( say x_db) and all the tables have a common column having date values( say column 'date'). I want to retrieve count of rows for each table in database x_db where value of column 'date' is greater than a specific value.

Provide potentional nil variable to function in GOLANG

Posted: 19 Mar 2021 08:10 AM PDT

I want to call a function with a int variable that can have a value or can be nil. In the main function i'm doing this call.

doDomething(10) // works  doDomething(nil) // does not work?    func doSomething(parent_id *int) {      fmt.Printf(parent_id)  }  

Potential memory leak when allocating memory space

Posted: 19 Mar 2021 08:10 AM PDT

I got a notification stating "Potential leak of memory pointed to by field '_Myval2'" in a code, that allocates memory and processes data with Boost lockfree spsc_queue. The data is constantly pushed by a callback function (when hardware is active) and I noticed, that indeed the memory usage quickly rises to an unacceptable value. I am having trouble figuring out how to get rid of this memory leak issue. I checked the data transfer and it passes through as expected. Is there a way to delete/deallocate the memory after I push it to the spsc queue?

boost::lockfree::spsc_queue<uchar*,boost::lockfree::capacity<10>> q{};    // Callback function  void MyClass::callback(SIGNALTYPE signalInfo)  {      ...      PVOID bufferAddress = getBufferAddress();      processData(bufferAddress);      break;      ...  }    // SPSC producer  void MyClass::processData(PVOID bufferAddress)  {      int size = getBufferSize();      auto bufferData = std::make_unique<uchar[]>(size); // This code causes a memory leak      memcpy(bufferData.get(), bufferAddress, size);      q.push(bufferData.release());  }    // SPSC consumer  std::unique_ptr<uchar[]> MyClass::popData()  {      std::unique_ptr<uchar[]> output(nullptr);      if(q.read_available())      {          output = std::unique_ptr<uchar[]>(q.front());          q.pop();      }      return output;  }  

ElasticSearch paginate over 10K result

Posted: 19 Mar 2021 08:10 AM PDT

Elasticsearch's search feature only support 10K result by default. I know I can specific the "size" parameter in the search query, but this only applies to number of result to get back in one call.

If I want to iterate over 20K results using size=100, making 200 calls total. How should I do it?

How to run Access query that works on SQL Server too

Posted: 19 Mar 2021 08:10 AM PDT

I know this is a common issue, but all on the thighs I've read are not clear enough for me to fix my issue.

I have an Access 2016 database with linked tables to SQL Server. When my vba code inside Access tries to run an update query that contains Date or DateTime fields, I can't get the update to work, I get an error message stating that I need an updatable query.

Is there a standard way to run this type of query?

UPDATE Table1 SET Table1.MyText = "Hello there!", Table1.MyInt = 33342, Table1.MyDate = #12/30/1899 2:28:0#/1960, Table1.MyBit = -1  

WHERE (((Table1.ID)=1));

Windows 10: Disappearing cursor on wake

Posted: 19 Mar 2021 08:10 AM PDT

When my computer wakes up from low power mode,

the cursor disappears.

When I turn it off, a cursor appears.

I am using additional acceleration applications.

How to fetch live bus schedules in firebase?

Posted: 19 Mar 2021 08:10 AM PDT

I'm new to firebase . I'm doing a project in android studio where I have to fetch live bus schedules from any transit services (ex. TTC ,Brampton transit) in firebase real-time. But I don't know how to fetch those data.

Can you please provide me the code !

How to return one row based upon date

Posted: 19 Mar 2021 08:10 AM PDT

I have an internal Department that will be switching account numbers in the future. I am trying to build a stored procedure to return only one of two rows based upon an effective date.

Here's the data makeup |ID | EffectiveDate | AccountNum | |-- | ------------- | ---------- | | 1 | 2021-01-01 | 350000 | | 2 | 2021-09-01 | 950000 |

I know this returns all the data SELECT Id, EffectiveDate, AccountNum FROM Account

This returns on the first row and never the 2nd: SELECT Id, EffectiveDate, DeptNum FROM Account WHERE EffectiveDate <= GETDATE() ORDER BY EffectiveDate DESC

How would I dynamically return only 1 row based upon today's date?

So if the Effective date is less than today's date get row one. If the Effective Date is = greater than todays date get row two.

Converting a column of MULTIPOLYGON data to lat and long in python

Posted: 19 Mar 2021 08:10 AM PDT

My dataset includes a column of MULTIPOLYGON like below. I am searching a lot to extract the lat and lot of data, but I am not able to do that. can anyone help me please?

    name                wkt  0   place_1 McDonald's  POLYGON ((13.4611920000000005 52.4709870000000009, 13.4610299999999992 52.4706600000000023, 13.4611959999999993 52.4706290000000024, 13.4612090000000002 52.4706550000000007, 13.4613589999999999 52.4709560000000010, 13.4611920000000005 52.4709870000000009))  1   place_2 McDonald's  POLYGON ((13.4683480000000007 52.5471599999999981, 13.4684080000000002 52.5471560000000011, 13.4684589999999993 52.5471360000000018, 13.4684910000000002 52.5471050000000020, 13.4684960000000000 52.5470729999999975, 13.4685500000000005 52.5470740000000021, 13.4685430000000004 52.5470449999999971, 13.4685269999999999 52.5470180000000013, 13.4684939999999997 52.5469920000000030, 13.4684449999999991 52.5469719999999967, 13.4684080000000002 52.5469629999999981, 13.4683630000000001 52.5469599999999986, 13.4683650000000004 52.5469960000000000, 13.4683159999999997 52.5469989999999996, 13.4682650000000006 52.5470189999999988, 13.4682329999999997 52.5470510000000033, 13.4682270000000006 52.5470880000000022, 13.4682469999999999 52.5471220000000017, 13.4682899999999997 52.5471480000000000, 13.4683480000000007 52.5471599999999981))        

xxxxx@21cn.com email login to Firebase project

Posted: 19 Mar 2021 08:10 AM PDT

I'm developing a mobile app using Firebase and its email authentication feature. I found that there are some unknown sign up with email with 21cn.com domain even though I'm not publishing the app yet. It seems like these email addresses are related to this website(https://mail.21cn.com/w2/).

Is there a way to prevent these unknown signup from outside or how can I improve the project safety?

Why do my two "exact same" string not match?

Posted: 19 Mar 2021 08:10 AM PDT

I have two strings and wonder why they do not match, although they seem to be the same. I even cannot macth them in my editor like atom with ctrl+find.

So I have

a = 'hello there'  b = 'hello there'    and a==b is False...  

which are really identicall (stripped etc.), but I think there are some isues with decoding etc.?

How can I find out out what is oing on there bhind the scences?

Map child refs into parent array

Posted: 19 Mar 2021 08:10 AM PDT

I attempting to map an array of children but to assign a ref to them as I do it so I can track their positions from in the parent.

However, I need to store each ref in an array.

I've attempted the below, but I get a ref containing an array. How could I modify it to get an array of refs?

export default function ({ children }) => {    const itemsRef = useRef([]);      console.log(itemsRef);    // returns a ref containing an array    // {current: Array(5)}        // How could I modify what I am doing     // to to instead return an array of refs?    // something like:    // [{current: HTMLDivElement}, {current: HTMLDivElement}, .....]        return (      <>        {React.Children.map(children, (child, index) =>          React.cloneElement(child, {            ref: (ref) => (              <Item ref={(itemsRef.current[index] = ref)} key={index}>                {child}              </Item>            )          })        )}      </>    );  };  

android opengl render a bitmap not showing

Posted: 19 Mar 2021 08:10 AM PDT

I'm trying to show a bitmap in android opengl-es3.1. The bitmap is created with Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8); and I filled the bitmap with pixels.

Here is the bitmap I created:

enter image description here

But the emulator show a strange thing: enter image description here

Here is the main render code:

    // generate bitmap from data      private void initMap(OccupancyGrid occupancyGrid) {          int height = occupancyGrid.info.height;          int width = occupancyGrid.info.width;            Bitmap newMap = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);            int[] pixels;          int bytePixel;            int curr = 0;          for (int y = 0; y < height; y++) {              pixels = new int[width];                for (int x = 0; x < width; x++) {                  // Pixels are ARGB packed ints.                  bytePixel = occupancyGrid.data[curr++];                    if (bytePixel == -1) {                      // black color                      pixels[x] = gradient[101];                  } else {                      // gray color                      pixels[x] = gradient[bytePixel];                  }              }                newMap.setPixels(pixels, 0, width, 0, y, width, 1);          }          bitmap = newMap;      }        @Override      public void onSurfaceChanged(GL10 gl, int width, int height) {          gl.glViewport(0, 0, width, height);      }        @Override      public void onDrawFrame(GL10 gl) {          // enable          GLES31.glEnable(GLES31.GL_TEXTURE_2D);          final int[] textureIds = new int[1];          //create          GLES31.glGenTextures(1, textureIds, 0);            // bind          GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textureIds[0]);            //set default param          GLES31.glTexParameterf(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_MIN_FILTER, GLES31.GL_NEAREST);          GLES31.glTexParameterf(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_MAG_FILTER, GLES31.GL_NEAREST);          GLES31.glTexParameteri(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_BASE_LEVEL, 0);          GLES31.glTexParameteri(GLES31.GL_TEXTURE_2D, GLES31.GL_TEXTURE_MAX_LEVEL, 0);          // load bitmap          GLUtils.texImage2D(GLES31.GL_TEXTURE_2D, 0, bitmap, 0);            // vertex          gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);          gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);          gl.glVertexPointer(3, GL10.GL_FLOAT, 0, surfaceVertices);          gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureVertices);              GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);      }  

View the full code in repository in repository link

Android finish() ends app instead of going to onAcitivityResult of previous activity

Posted: 19 Mar 2021 08:10 AM PDT

I am trying to get some data from a server. User clicks search and another acitivity starts by startActivityForResult().when user clicks the data the data should be put inside intent and setResult() is done with that intent and finish() is called. Now i have tried debugg but when finish() is called the activity does no go back to the one which called this activity. instead the app closes down.

Here is the code;

public class SearchContactActivity extends AppCompatActivity {        ProgressBar pb;      CircleImageView profile_image_search;      TextView name_search,user_name_search;      EditText edit_search_contact;      Button btn_search_contact;      ConstraintLayout cl;      String profile_image,firstName,lastName;      RequestQueue myQueue;      String url = "working url";      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_search_contact);            pb = findViewById(R.id.progressBar);          profile_image_search = findViewById(R.id.profile_image_search);          name_search = findViewById(R.id.name_search);          user_name_search = findViewById(R.id.user_name_search);          btn_search_contact = findViewById(R.id.btn_search_contact);          edit_search_contact = findViewById(R.id.edit_search_contact);          cl = findViewById(R.id.nested_layout);            cl.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  setResultForPreviousAcitvity();              }          });          btn_search_contact.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  try {                      search_contacts();                  } catch (JSONException e) {                      e.printStackTrace();                  }              }          });          hideVisibility();      }      public void setResultForPreviousAcitvity()      {          Intent data = new Intent();          data.putExtra("first_name",firstName);          data.putExtra("last_name",lastName);          data.putExtra("user_name",user_name_search.getText().toString());          data.putExtra("profile", profile_image);          setResult(RESULT_OK,data);          finish(); // app closes down here      }      private void search_contacts() throws JSONException {          pb.setVisibility(View.VISIBLE);            //send php data in json array format          //JSONObject jsonbody = new JSONObject("{\"search_key\":\"jhonsanders \"}");          HashMap<String, String> params = new HashMap<String, String>();          params.put("search_key", edit_search_contact.getText().toString().trim());          JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( url,new JSONObject(params), new Response.Listener<JSONObject>() {              @Override              public void onResponse(JSONObject response) {                  try {                      JSONArray jsonArray = response.getJSONArray("result");                      for(int i = 0; i < jsonArray.length(); i++)                      {                          JSONObject myobj = jsonArray.getJSONObject(i);                          firstName = myobj.getString("first_name");                          lastName = myobj.getString("last_name");                          String userName = myobj.getString("user_name");                          profile_image = myobj.getString("profile_image");                          Bitmap image = NameAndImage.stringToImage(profile_image);                          show_visibility();                          profile_image_search.setImageBitmap(image);                          user_name_search.setText(userName);                          name_search.setText(firstName+" "+lastName);                      }                  } catch (JSONException e) {                      e.printStackTrace();                  }                  }          }, new Response.ErrorListener() {              @Override              public void onErrorResponse(VolleyError error) {                  error.printStackTrace();              }          })/*{              @Override              protected Map<String, String> getParams() throws AuthFailureError {                  Map<String,String> param = new HashMap<>();                  param.put("search_key",edit_search_contact.getText().toString().trim());                  return param;              }          }*/;          myQueue = VolleySingleton.getInstance(SearchContactActivity.this).getRequestQueue();          myQueue.add(jsonObjectRequest);        }      private void hideVisibility()      {          pb.setVisibility(View.INVISIBLE);          profile_image_search.setVisibility(View.INVISIBLE);          name_search.setVisibility(View.INVISIBLE);          user_name_search.setVisibility(View.INVISIBLE);        }      private void show_visibility()      {          profile_image_search.setVisibility(View.VISIBLE);          name_search.setVisibility(View.VISIBLE);          user_name_search.setVisibility(View.VISIBLE);          pb.setVisibility(View.INVISIBLE);      }     /* private Bitmap stringToImage(String s)      {          byte[] image = Base64.decode(s,Base64.DEFAULT);          Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);          return decodedImage;      }*/    }  

The above activity is called by

Intent i = new Intent(ContactsActivity.this,SearchContactActivity.class);          startActivityForResult(i,REQUEST_CONTACT_SEARCH);  

This is the manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.example.privatechat">        <application          android:allowBackup="true"          android:icon="@mipmap/ic_launcher"          android:label="@string/app_name"          android:roundIcon="@mipmap/ic_launcher_round"          android:supportsRtl="true"          android:usesCleartextTraffic="true"          android:theme="@style/Theme.PrivateChat">          <activity android:name=".SearchContactActivity"></activity>          <activity android:name=".ContactsActivity" />          <activity android:name=".NameAndImage" />          <activity android:name=".MainActivity">              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                    <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>          </activity>            <uses-library              android:name="org.apache.http.legacy"              android:required="false" />      </application>        <uses-permission android:name="android.permission.INTERNET" />    </manifest>  

There is no logs that i can print.The log is cleared when onfinish() is called.

The app goes back to this other activity. This one also has onAcitivityResult but its not the one that called the other acitivity.

public class NameAndImage extends AppCompatActivity {        EditText editFirstName,editLastName;      ImageView profile_image;      Button uploadNameImage;      Bitmap image;      RequestQueue myQueue;      SaveSharedPreference sp = new SaveSharedPreference();        private String URL = "working url";      public static final int PICK_IMAGE_REQUEST = 1011;      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_name_and_image);          editFirstName = findViewById(R.id.edit_first_name);          editLastName = findViewById(R.id.edit_last_name);          profile_image = findViewById(R.id.profile_image_search);          uploadNameImage = findViewById(R.id.upload_name_image);          Log.i("SharedPreference",sp.getUserName(NameAndImage.this).trim());            profile_image.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  pickPhoto();              }          });            uploadNameImage.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  uploadData();              }          });      }      private void pickPhoto()      {          Intent intent = new Intent();          intent.setAction(Intent.ACTION_PICK);          intent.setType("image/*");          startActivityForResult(intent,PICK_IMAGE_REQUEST);      }      private  void uploadData()      {          StringRequest upload_data = new StringRequest(Request.Method.POST, URL,                  new Response.Listener<String>() {                      @Override                      public void onResponse(String response) {                          if(response.trim().equals("success_data_upload"))                          {                              Toast.makeText(NameAndImage.this, "upload success", Toast.LENGTH_SHORT).show();                              Intent i = new Intent(NameAndImage.this,ContactsActivity.class);                              startActivity(i);                          }                          if(response.trim().equals("Error"))                          {                              Toast.makeText(NameAndImage.this, "upload error", Toast.LENGTH_SHORT).show();                              Log.i("server",response.toString());                          }                          else                          {                              Toast.makeText(NameAndImage.this, "Response dont match", Toast.LENGTH_SHORT).show();                              Log.i("server",response);                          }                        }                  },                  new Response.ErrorListener() {                      @Override                      public void onErrorResponse(VolleyError error) {                          Toast.makeText(NameAndImage.this, error.toString(), Toast.LENGTH_SHORT).show();                          Log.i("server",error.toString());                      }                  }) {              @Override              protected Map<String, String> getParams() throws AuthFailureError {                  Map<String,String> param = new HashMap<>();                  param.put("image",imageToString(image));                  param.put("first_name",editFirstName.getText().toString());                  param.put("last_name",editLastName.getText().toString());                  param.put("user_name",sp.getUserName(NameAndImage.this).trim());                  return param;              }          };          upload_data.setRetryPolicy(new DefaultRetryPolicy(                  3000,                  DefaultRetryPolicy.DEFAULT_MAX_RETRIES,                  DefaultRetryPolicy.DEFAULT_BACKOFF_MULT          ));          myQueue = VolleySingleton.getInstance(NameAndImage.this).getRequestQueue();          myQueue.add(upload_data);      }      public static String imageToString(Bitmap pic)      {          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();          pic.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);          byte[] imageByte = byteArrayOutputStream.toByteArray();          return Base64.encodeToString(imageByte,Base64.DEFAULT);      }      public static Bitmap stringToImage(String s)      {          byte[] image = Base64.decode(s,Base64.DEFAULT);          Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);          return decodedImage;      }        @Override      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {          super.onActivityResult(requestCode, resultCode, data);            if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)          {              Uri uri = data.getData();                try {                  image = MediaStore.Images.Media.getBitmap(getContentResolver(),uri);                  profile_image.setImageBitmap(image);              } catch (IOException e) {                  e.printStackTrace();              }          }      }  }  

Edit: The app seems to close but after 2 sec the wrong activity is started.

Termcaps lines and columns are not changing when I resize the window

Posted: 19 Mar 2021 08:10 AM PDT

I'm trying to get the terminal window size, even when I resize the window, I'm using termcaps for this, the problem is when I resize the window, the values of lines and columns stays the same instead of updating, I also tried using ncurses's LINES and COLS globals, but the same thing happens. Here is a minimal reproductible example:

#include <ncurses.h>  #include <term.h>  #include <unistd.h>  #include <stdlib.h>  #include <stdio.h>    int main(void)  {      char * term_type = getenv("TERM");      int ret;      int li_cap;      int co_cap;        if (!term_type)      {          write(2, "TERM env must be set\n", 21);          return (-1);      }      if ((ret = tgetent(NULL, term_type)) == -1)      {          write(2, "Could not access to the termcap database\n", 41);          return (-1);      }      if (!ret)      {          write(2, "This terminal is not supported by termcaps\n", 43);          return (-1);      }      while (1)      {          sleep(1);          li_cap = tgetnum("li");          co_cap = tgetnum("co");          printf("%d %d\n", li_cap, co_cap);      }      return (0);  }  

So when I resize the window inside the loop, the values stay the same, I want to get the lines and colums in real time, how could I do this with termcaps?

Keycloak: Invalid token issuer when running from internal docker container

Posted: 19 Mar 2021 08:10 AM PDT

I'm having some issues with configuring keycloak to run on our server. Locally it works great but on on our test environment, after login, on any call using the received access token, we get "Invalid token issuer. Expected "http://keycloak:8080/auth/realms/{realmnName}" but was "http://{our-test-server-IP}/auth/realms/{realmName}"" So basically, our backend connects to the internal keycloak docker image but when the request comes it expects that the issuer is the configured external IP so even though the issuers are basically the same service keycloak sees them as being different and responds with a 401.

docker-compose.yml:

keycloak:      image: jboss/keycloak:12.0.4      restart: on-failure      environment:          PROXY_ADDRESS_FORWARDING: "true"          KEYCLOAK_USER: admin          KEYCLOAK_PASSWORD: password          KEYCLOAK_LOGLEVEL: DEBUG          KEYCLOAK_IMPORT: /etc/settings/realm.json -Dkeycloak.profile.feature.upload_scripts=enabled          TZ: Europe/Bucharest          DB_VENDOR: POSTGRES          DB_ADDR: db          DB_DATABASE: user          DB_SCHEMA: keycloak          DB_USER: user          DB_PASSWORD: user      ports:          - 8090:8080      volumes:          - ./settings:/etc/settings      depends_on:          - db  

Spring application.yml:

keycloak:    cors: true    realm: Realm-Name    resource: back-office    auth-server-url: http://keycloak:8080/auth/    public-client: false    credentials:      secret: 8401b642-0ae9-4dc8-87a6-2f494b388a49    keycloak-client:    id: bcc94ed5-0099-40e0-b460-572eba3f0214  

If we change the backend properties auth-server-url to connect to the exposed endpoint and no to the internal docker container we get a timeout, seems like it doesn't want to connect to it. I understand that the main issue is that we are running both the keycloak instance and our backend application on the same server but I don't see why it shouldn't work and why they can not connect to each other.

We tried setting up the FRONTEND_URL in the environment when running the container and in Keycloak admin console but nothing has changed. We've also tried to set forceBackendUrlToFrontendUrl to true in standalone.xml/standalone-ha.xml(./jboss-cli.sh --connect "/subsystem=keycloak-server/spi=hostname/provider=default:write-attribute(name=properties.forceBackendUrlToFrontendUrl, value=true)") files and reset the keycloak instance inside the docker container using ./jboss-cli.sh --connect command=:reload but nothing has changed.

I understand that basically by setting up the FRONTEND_URL all tokens should be signed by the keycloak instance and we would not have this issue but I've tried everything I've found so far on this issue regarding the keycloak configuration and nothing seems to change things. How can I make sure that the issuer that signs the access token and the one that the backend service expects are the same(hopefully the frontend)? And how can I configure this, is there some property I'm missing or was there something I did wrong while configuring it?

Encrypting a txt file using Caesar cipher

Posted: 19 Mar 2021 08:10 AM PDT

I am working on a project where it is required to encrypt a .txt file. I am pretty new to programming so my code is faulty. I don't know how to convert the text in the file to a char variable to add the left-shift of 4.

import java.io.*;  import java.util.*;  import java.io.FileNotFoundException;    public class CaesarCipher {            public static void main(String [] args) throws FileNotFoundException {                    File file = new File ("data_plain_alphabet.txt");          Scanner scan = new Scanner(file);                    while (scan.hasNextLine()) {              System.out.println(scan.nextLine());                    }                              scan.close();      }        public static String caesar(String line) {          for (int i = 0; i < line.length(); i++ ) {              String line = scan.nextLine();              char[] chars = line.toCharArray();                            System.out.print(line);          }      }  }  

What does CN stand for in a mobile app apk signature information?

Posted: 19 Mar 2021 08:10 AM PDT

In https://docs.microsoft.com/en-us/xamarin/android/deploy-test/signing/keystore-signature?tabs=windows, it gives an example of the signature information:

Alias name: androiddebugkey  Creation date: Aug 19, 2014  Entry type: PrivateKeyEntry  Certificate chain length: 1  Certificate[1]:  Owner: CN=Android Debug, O=Android, C=US  Issuer: CN=Android Debug, O=Android, C=US  Serial number: 53f3b126  Valid from: Tue Aug 19 13:18:46 PDT 2014 until: Sun Nov 15 12:18:46 PST 2043  Certificate fingerprints:           MD5:  27:78:7C:31:64:C2:79:C6:ED:E5:80:51:33:9C:03:57           SHA1: 00:E5:8B:DA:29:49:9D:FC:1D:DA:E7:EE:EE:1A:8A:C7:85:E7:31:23           SHA256: 21:0D:73:90:1D:D6:3D:AB:4C:80:4E:C4:A9:CB:97:FF:34:DD:B4:42:FC:  08:13:E0:49:51:65:A6:7C:7C:90:45           Signature algorithm name: SHA1withRSA           Version: 3  

Regarding "Owner: CN=Android Debug, O=Android, C=US", O may stand for organisation, and C may stand for country.

What does CN stand for?

Java Spliterator Continually Splits Parallel Stream

Posted: 19 Mar 2021 08:10 AM PDT

I found some surprising behavior with Java parallel streams. I made my own Spliterator, and the resulting parallel stream gets divided up until each stream has only one element in it. That seems way too small and I wonder what I'm doing wrong. I'm hoping there's some characteristics I can set to correct this.

Here's my test code. The Float here is just a dummy payload, my real stream class is somewhat more complicated.

   public static void main( String[] args ) {        TestingSpliterator splits = new TestingSpliterator( 10 );        Stream<Float> test = StreamSupport.stream( splits, true );        double total = test.mapToDouble( Float::doubleValue ).sum();        System.out.println( "Total: " + total );     }  

This code will continually split this stream until each Spliterator has only one element. That seems way too much to be efficient.

Output:

run:  Split on count: 10  Split on count: 5  Split on count: 3  Split on count: 5  Split on count: 2  Split on count: 2  Split on count: 3  Split on count: 2  Split on count: 2  Total: 5.164293184876442  BUILD SUCCESSFUL (total time: 0 seconds)  

Here's the code of the Spliterator. My main concern is what characteristics I should be using, but perhaps there's a problem somewhere else?

public class TestingSpliterator implements Spliterator<Float> {     int count;     int splits;       public TestingSpliterator( int count ) {        this.count = count;     }       @Override     public boolean tryAdvance( Consumer<? super Float> cnsmr ) {        if( count > 0 ) {           cnsmr.accept( (float)Math.random() );           count--;           return true;        } else           return false;     }       @Override     public Spliterator<Float> trySplit() {        System.err.println( "Split on count: " + count );        if( count > 1 ) {           splits++;           int half = count / 2;           TestingSpliterator newSplit = new TestingSpliterator( count - half );           count = half;           return newSplit;        } else           return null;     }       @Override     public long estimateSize() {        return count;     }       @Override     public int characteristics() {        return IMMUTABLE | SIZED;     }  }  

So how can I get the stream to be split in to much larger chunks? I was hoping in the neighborhood of 10,000 to 50,000 would be better.

I know I can return null from the trySplit() method, but that seems like a backwards way of doing it. It seems like the system should have some notion of number of cores, current load, and how complex the code is that uses the stream, and adjust itself accordingly. In other words, I want the stream chunk size to be externally configured, not internally fixed by the stream itself.

Can we directly write Python code under "run | " section in action.yml file

Posted: 19 Mar 2021 08:10 AM PDT

In GitHub Actions, can we directly write python code under run | -section in action.yml file? Can I write GitHub Actions scripts in Python?

Average response time on Grafana from Prometheus

Posted: 19 Mar 2021 08:10 AM PDT

I am trying to find the average response time of all the URLs in Grafana,

The below query not returning any data, what am I doing wrong here?

    avg by (uri) (rate(http_server_requests_seconds_sum{app_name="$app",                    namespace="$namespace", uri!~".*actuator.*|/health|root"}[1m])      /rate(http_server_requests_seconds_count{app_name="$app",                    namespace="$namespace", uri!~".*actuator.*|/health|root"}[1m]))  

The data is collected via a micrometer.

Asteroids Game, Object Oriented Orogramming, Python

Posted: 19 Mar 2021 08:10 AM PDT

I am making an asteroids game. I have got the ship moving and asteroids floating as they should. I want an explosion to occur when an asteroid collides with the ship, but I am lost on how to make it work. Thank you.

laserBlue01.png

meteorGrey_big1.png

meteorGrey_med1.png

meteorGrey_small1.png

playerShip1_orange.png

import arcade  import random  import math  from abc import ABC, abstractmethod    # These are Global constants to use throughout the game  SCREEN_WIDTH = 800  SCREEN_HEIGHT = 600    BULLET_RADIUS = 30  BULLET_SPEED = 10  BULLET_LIFE = 60    SHIP_TURN_AMOUNT = 3  SHIP_THRUST_AMOUNT = 0.25  SHIP_RADIUS = 30    INITIAL_ROCK_COUNT = 5    BIG_ROCK_SPIN = 1  BIG_ROCK_SPEED = 1.5  BIG_ROCK_RADIUS = 15    MEDIUM_ROCK_SPIN = -2  MEDIUM_ROCK_RADIUS = 5    SMALL_ROCK_SPIN = 5  SMALL_ROCK_RADIUS = 2    """      Flying Object          -Velocity          -Point          -Draw          -Advance          -Angle        Asteroid      Ship      Bullet        SmallRock      BigRock      LargeRock """      # This class determines a starting point.  class Point:      def __init__(self):          self.x = 0.00          self.y = 0.00      # This class determines speed.  class Velocity:      def __init__(self):          self.dx = 0.00          self.dy = 0.00      class FlyingObject(ABC):      def __init__(self, img):          self.center = Point()          self.velocity = Velocity()          self.alive = True          self.img = img          self.texture = arcade.load_texture(self.img)          self.width = self.texture.width          self.height = self.texture.height          self.radius = SHIP_RADIUS          self.angle = 0          self.speed = 0          self.direction = 1            """          Velocity to be looked at later.          """          self.velocity.dx = math.cos(math.radians(self.direction)) * self.speed          self.velocity.dy = math.sin(math.radians(self.direction)) * self.speed        def advance(self):          self.wrap()          self.center.y += self.velocity.dy          self.center.x += self.velocity.dx        def is_alive(self):          return self.alive        def draw(self):          arcade.draw_texture_rectangle(              self.center.x,              self.center.y,              self.width,              self.height,              self.texture,              self.angle,              255,          )        def hit(self):          self.alive = False          return self.hit_score        def wrap(self):          if self.center.x > SCREEN_WIDTH:              self.center.x -= SCREEN_WIDTH          if self.center.x < 0:              self.center.x += SCREEN_WIDTH          if self.center.y > SCREEN_HEIGHT:              self.center.y -= SCREEN_HEIGHT          if self.center.y < 0:              self.center.y += SCREEN_HEIGHT      class Ship(FlyingObject):      def __init__(self):          super().__init__("images/playerShip1_orange.png")          self.angle = 1          self.center.x = SCREEN_WIDTH / 2          self.center.y = SCREEN_HEIGHT / 2          self.radius = SHIP_RADIUS        def left(self):          self.angle += SHIP_TURN_AMOUNT        def right(self):          self.angle -= SHIP_TURN_AMOUNT        def thrust(self):          self.velocity.dx -= math.sin(math.radians(self.direction)) * SHIP_THRUST_AMOUNT          self.velocity.dy += math.cos(math.radians(self.direction)) * SHIP_THRUST_AMOUNT        def rev_Thrust(self):          self.velocity.dx += math.sin(math.radians(self.direction)) * SHIP_THRUST_AMOUNT          self.velocity.dy -= math.cos(math.radians(self.direction)) * SHIP_THRUST_AMOUNT      class Bullet(FlyingObject):      def __init__(self, ship_angle, ship_x, ship_y):          super().__init__("images/laserBlue01.png")          self.radius = BULLET_RADIUS          self.life = BULLET_LIFE          self.speed = BULLET_SPEED          self.angle = ship_angle - 90          self.center.x = ship_x          self.center.y = ship_y        def fire(self):          self.velocity.dx -= math.sin(math.radians(self.angle + 90)) * BULLET_SPEED          self.velocity.dy += math.cos(math.radians(self.angle + 90)) * BULLET_SPEED        def advance(self):          super().advance()          self.life -= 1          if self.life <= 0:              self.alive = False      class Asteroid(FlyingObject):      def __init__(self, img):          super().__init__(img)          self.radius = 0.00          self.hit_score = 1        def advance(self):          super().advance()          self.radius = 0.00        def hit(self):          self.alive = False          return self.hit_score      """  This class represent the small asteroid size.  """      class SmallRock(Asteroid):      def __init__(self):          super().__init__("images/meteorGrey_small1.png")          self.radius = SMALL_ROCK_RADIUS          self.speed = BIG_ROCK_SPEED          self.lives = 1        def advance(self):          super().advance()          self.angle += SMALL_ROCK_SPIN        def break_apart(self, asteroids):          self.alive = False        def hit(self):          """          Reduces object life as a bullet hits it.          """            self.lives -= 1          if self.lives == 2:              self.hit_score = 1          elif self.lives == 1:              self.hit_score = 1          elif self.lives == 0:              self.alive = False              self.hit_score = 5          return self.hit_score      """  This class represents the medium asteroid size.  """      class MediumRock(Asteroid):      def __init__(self):          super().__init__("images/meteorGrey_med1.png")          self.radius = MEDIUM_ROCK_RADIUS          self.speed = BIG_ROCK_SPEED          self.velocity.dx = math.cos(math.radians(self.direction)) * self.speed          self.velocity.dy = math.sin(math.radians(self.direction)) * self.speed          self.lives = 2        def advance(self):          super().advance()          self.angle += MEDIUM_ROCK_SPIN        def break_apart(self, asteroids):          small = SmallRock()          small.center.x = self.center.x          small.center.y = self.center.y          small.velocity.dy = self.velocity.dy + 1.5          small.velocity.dx = self.velocity.dx + 1.5            small2 = SmallRock()          small2.center.x = self.center.x          small2.center.y = self.center.y          small2.velocity.dy = self.velocity.dy - 2          small2.velocity.dx = self.velocity.dx + 1.5            asteroids.append(small)          asteroids.append(small2)          self.alive = False        def hit(self):          """          Reduces object life as a bullet hits it.          """            self.lives -= 1          if self.lives == 2:              self.hit_score = 1          elif self.lives == 1:              self.hit_score = 1          elif self.lives == 0:              self.alive = False              self.hit_score = 2          return self.hit_score      class LargeRock(Asteroid):      def __init__(self):          super().__init__("images/meteorGrey_big1.png")          self.radius = BIG_ROCK_RADIUS          self.center.x = random.randint(1, 50)          self.center.y = random.randint(1, 150)          self.direction = random.randint(1, 50)          self.speed = BIG_ROCK_SPEED          self.hit_score = 5          self.lives = 3          self.velocity.dx = math.cos(math.radians(self.direction)) * self.speed          self.velocity.dy = math.sin(math.radians(self.direction)) * self.speed        def advance(self):          super().advance()          self.angle += BIG_ROCK_SPIN        """      This breaks the rock into pieces when hit by a bullet.      """        def break_apart(self, asteroids):          med1 = MediumRock()          med1.center.x = self.center.x          med1.center.y = self.center.y          med1.velocity.dy = self.velocity.dy + 2            med2 = MediumRock()          med2.center.x = self.center.x          med2.center.y = self.center.y          med2.velocity.dy = self.velocity.dy - 2            small = SmallRock()          small.center.x = self.center.x          small.center.y = self.center.y          small.velocity.dy = self.velocity.dy + 5            asteroids.append(med1)          asteroids.append(med2)          asteroids.append(small)          self.alive = False        def hit(self):          """          Reduces object life as a bullet hits it.          """            self.lives -= 1          if self.lives == 2:              self.hit_score = 1          elif self.lives == 1:              self.hit_score = 1          elif self.lives == 0:              self.alive = False              self.hit_score = 10          return self.hit_score      class Game(arcade.Window):      """      This class handles all the game callbacks and interaction      This class will then call the appropriate functions of      each of the above classes.      You are welcome to modify anything in this class.      """        def __init__(self, width, height):          """          Sets up the initial conditions of the game          :param width: Screen width          :param height: Screen height          """          super().__init__(width, height)          arcade.set_background_color(arcade.color.SMOKY_BLACK)            self.held_keys = set()            self.asteroids = []            for i in range(INITIAL_ROCK_COUNT):              bigAst = LargeRock()              self.asteroids.append(bigAst)            # todo: declare anything here you need the game class to track          self.ship = Ship()          self.score = 0            self.bullets = []        def on_draw(self):          """          Called automatically by the arcade framework.          Handles the responsibility of drawing all elements.          """            # clear the screen to begin drawing          arcade.start_render()            for asteroid in self.asteroids:              asteroid.draw()            # todo: draw each object          for bullet in self.bullets:              bullet.draw()            self.ship.draw()            self.draw_score()            """'          This method removes dead objects from the game and makes the ship          inactive if it collides with an asteroid          """        def draw_score(self):          """          Puts the current score on the screen          """          score_text = "Score: {}".format(self.score)          start_x = 10          start_y = SCREEN_HEIGHT - 20          arcade.draw_text(              score_text,              start_x=start_x,              start_y=start_y,              font_size=12,              color=arcade.color.NAVY_BLUE,          )        def remove_DeadObjects(self):          for bullet in self.bullets:              if not bullet.alive:                  self.bullets.remove(bullet)            for asteroid in self.asteroids:              if not asteroid.alive:                  self.asteroids.remove(asteroid)              if not self.ship.alive:                    """                  Opens a Game Over Window when the ship collides with an asteroid                  """                  arcade.open_window(700, 400, "Game Over")                  arcade.start_render()                  arcade.draw_text(                      text="GAME OVER! TRY AGAIN",                      start_x=20,                      start_y=200,                      color=arcade.color.RED,                      font_size=50,                  )                  arcade.finish_render()                  arcade.run()        def check_collisions(self):          for bullet in self.bullets:              for asteroid in self.asteroids:                  if bullet.alive and asteroid.alive:                      distance_x = abs(asteroid.center.x - bullet.center.x)                      distance_y = abs(asteroid.center.y - bullet.center.y)                      max_dist = asteroid.radius + bullet.radius                      if (distance_x < max_dist) and (distance_y < max_dist):                          asteroid.break_apart(self.asteroids)                          bullet.alive = False                          asteroid.alive = False                          bullet.alive = False                            # collision to occur                          print("Collision of asteroid and bullet.")            for asteroid in self.asteroids:              if self.ship.alive and asteroid.alive:                  distance_x = abs(asteroid.center.x - self.ship.center.x)                  distance_y = abs(asteroid.center.y - self.ship.center.y)                  max_dist = asteroid.radius + self.ship.radius                  if (distance_x < max_dist) and (distance_y < max_dist):                      self.ship.alive = False                      asteroid.alive = False                      print("Asteroid collides with ship")        def update(self, delta_time):          """          Update each object in the game.          :param delta_time: tells us how much time has actually elapsed          """          self.check_keys()            for asteroid in self.asteroids:              asteroid.advance()            for bullet in self.bullets:              bullet.advance()            self.remove_DeadObjects()          self.check_collisions()            self.ship.advance()            # TODO: Tell everything to advance or move forward one step in time            # TODO: Check for collisions        def check_keys(self):          """          This function checks for keys that are being held down.          You will need to put your own method calls in here.          """          if arcade.key.LEFT in self.held_keys:              self.ship.left()            if arcade.key.RIGHT in self.held_keys:              self.ship.right()            if arcade.key.UP in self.held_keys:              self.ship.thrust()            if arcade.key.DOWN in self.held_keys:              self.ship.rev_Thrust()            # Machine gun mode...          # if arcade.key.SPACE in self.held_keys:          #    pass        def on_key_press(self, key: int, modifiers: int):          """          Puts the current key in the set of keys that are being held.          ,see;   You will need to add things here to handle firing the bullet.          """          if self.ship.alive:              self.held_keys.add(key)                if key == arcade.key.SPACE:                  bullet = Bullet(self.ship.angle, self.ship.center.x, self.ship.center.y)                  self.bullets.append(bullet)                  bullet.fire()                  # TODO: Fire the bullet here!        def on_key_release(self, key: int, modifiers: int):          """          Removes the current key from the set of held keys.          """          if key in self.held_keys:              self.held_keys.remove(key)      # Creates the game and starts it going window = Game(SCREEN_WIDTH, SCREEN_HEIGHT) arcade.run()  

Apparent lack of support for Tailwind CSS 2+ on webkit-based browsers

Posted: 19 Mar 2021 08:10 AM PDT

Note to viewer

I have solved this issue on my own. If you would like to see the solution, scroll down below, where I have provided a detailed explanation for the issue and ways to solve it.


I am working on a webapp that exclusively uses Tailwind for the frontend, and I have constructed a simple sidebar for it like so:

<!--SIDEBAR Element (Tailwind)-->  <div    class="flex flex-col w-full py-8 m-auto text-gray-300 shadow-md justify-around bg-palegray space-y-12 rounded-xl"  >    <!--PENCIL BUTTON-->    <button      class="px-3 mx-auto w-full space-y-4 border-solid border-gray-400 border-r-4"      id="pencil-button"    >      <div class="flex justify-around" id="icon">          <svg xmlns="http://www.w3.org/2000/svg" class="w-8"  viewBox="0 0 20 20" fill="currentColor">              <path                 d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />          </svg>      </div>      <p class="text-xs">Draw</p>    </button>      <!--SQUARE BUTTON-->    <button class="px-3 mx-auto ...">      <!--Basically the same markup as the button above-->    </button>      <!--CIRCLE BUTTON-->    <button class="px-3 mx-auto ...">      <!--Basically the same markup as the button above-->    </button>      <!--SPRAY BUTTON-->    <button class="px-3 mx-auto ...">      <!--Basically the same markup as the button above-->    </button>      <!--PATTERN BUTTON-->    <button class="px-3 mx-auto ...">      <!--Basically the same markup as the button above-->    </button>      <!--TEXTURE BUTTON-->    <button class="px-3 mx-auto ...">      <!--Basically the same markup as the button above-->    </button>  </div>    

Unfortunately, while it works on Firefox and Chromium-based browsers, it completely breaks on all webkit browsers (such as epiphany and safari). This is what it looks like there:

The problem apparently seems to be the space-y-4 class, which uses css variables and may not work on webkit-based browsers. However, removing this class did not solve the issue. Additionally, I re-ran tailwind to produce vendor prefixes for webkit, but that has not helped solve the issue.

Any advice would be greatly appreciated.

How do I check if hardware lock elision (HLE) is disabled in libpthread.so.0?

Posted: 19 Mar 2021 08:11 AM PDT

From this post, I learned that HLE can be enabled/disabled differently depending on the glibc version.

How do I check whether HLE is enabled in the libpthread library object for glibc prior to and after version 2.27?

I was thinking to use dlsym(void *handle, const char *symbol) where handle is the libpthread handle and symbol refers to HLE enabled. If the function returns NULL, then HLE is disabled. If this is the case, what would symbol be ?

Is there a better way to check if HLE is disabled in the libpthread?

Update: I used "nm" command on a SLES12 system running glibc 2.22 to display all the symbols from /lib64/noelision/libpthread.so.0 which should have HLE disabled. Does the output of "nm" tell me if HLE is disabled in libpthread ?

nm "/lib64/noelision/libpthread.so.0" | grep "elision"  0000000000218290 d __elision_aconf  000000000021c4a8 b __elision_available  0000000000013440 t elision_init  0000000000013470 t __lll_lock_elision  0000000000013570 t __lll_timedlock_elision  0000000000013640 t __lll_trylock_elision  0000000000013530 t __lll_unlock_elision  000000000021c4a4 b __pthread_force_elision  

Update: To answer my own question, you can indirectly check whether HLE path is disabled in pthreads by testing if there is undefined behaviour when double release a mutex from the pthreads library. A segmentation fault would indicate that the code is using HLE-enabled pthreads paths.

pthread_mutex_lock( &mutex ) ;  ...  pthread_mutex_unlock( &mutex ) ;  pthread_mutex_unlock( &mutex ) ;  

Understanding the $ATTRIBUTE_LIST in NTFS

Posted: 19 Mar 2021 08:11 AM PDT

I'm examining the NTFS (New Technology File System) and have been stuck in a loop trying to figure out the $ATTRIBUTE_LIST attribute. From this documentation, it is unusual to come across an $ATTRIBUTE_LIST and they're only used if the MFT table is running out of room. However, from looking at the following parsers, I've found they do parse it:

From looking at these, I've come up with the following flowchart:

Attribute List Flow Chart

(There should be a yes to the right of "Has $ATTRIBUTE_LIST")

I would like to refer to the 2 processes on the right side of the flow chart. Is it correct that:

  1. The attribute is only parsed if it's FRN is different than the file containing the attribute lists FRN?
  2. The attribute is added to the file with the FRN listed in the attribute and not the FRN containing the attribute list? Or, is the FRN listed in the attribute only used for attributes for this file record (and not really a file)?

Is it possible to restrict number to a certain range

Posted: 19 Mar 2021 08:10 AM PDT

Since typescript 2.0 RC (or even beta?) it is possible to use number literal types, as in type t = 1 | 2;. Is it possible to restrict a type to a number range, e.g. 0-255, without writing out 256 numbers in the type?

In my case, a library accepts color values for a palette from 0-255, and I'd prefer to only name a few but restrict it to 0-255:

const enum paletteColor {    someColor = 25,    someOtherColor = 133  }  declare function libraryFunc(color: paletteColor | 0-255); //would need to use 0|1|2|...  

C++ How to compile WxWidget programs using MinGW?

Posted: 19 Mar 2021 08:10 AM PDT

I'm using MinGW g++ and have installed and -mingw32-make'd the wxWidgets library files. But, when i try to compile a simple program:

// test.cpp  #include "wx/wx.h"    int main( int , char** )  {       return 0;  };  

The linking fails.

I use this command line

g++ test.cpp - o test.exe  

It appears I need extra linker parameters. What exactly do I need?

Also, I was searching around a little bit, and I found someone saying i should use -mingw32-make -n on a sample program in the wxWidgets folder, and use the same parameters for my own file, but that fails as well.

This is what I get as an error message:

g++ test.cpp -o test.exe -g -mthreads -L.....\lib\gcc_lib -Wl,-- subsystem,windows -mwindows -lwxmsw31ud_core -lwxbase31ud -lwxtiffd -lwxjpegd -lwxpngd -lwxzlibd -lwxregexud -lwxexpatd -lkernel32 -luser32 -lgdi32 -lcomdlg32 -lwinspool -lwinmm -lshell32 -lshlwapi -lcomctl32 -lole32 -loleaut32 -luuid -lrpcrt4 -ladvapi32 -lversion -lwsock32 -lwininet d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxmsw31ud_core d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxbase31ud d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxtiffd d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxjpegd d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxpngd d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxzlibd d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxregexud d:/programming/software/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -lwxexpatd collect2.exe: error: ld returned 1 exit status

Round in numpy to Nearest Step

Posted: 19 Mar 2021 08:10 AM PDT

I would like to know how I can round a number in numpy to an upper or lower threshold which is function of predefined step size. Hopefully stated in a clearer way, if I have the number 123 and a step size equal to 50, I need to round 123 to the closest of either 150 or 100, in this case 100. I came out with function below which does the work but I wonder if there is a better, more succint, way to do this.

Thanks in advance,

Paolo

def getRoundedThresholdv1(a, MinClip):      import numpy as np      import math      digits = int(math.log10(MinClip))+1      b = np.round(a, -digits)      if b > a:  # rounded-up          c = b - MinClip          UpLow = np.array((b,c))      else:  # rounded-down          c = b + MinClip          UpLow = np.array((c,b))      AbsDelta = np.abs(a - UpLow)      return UpLow[AbsDelta.argmin()]          getRoundedThresholdv1(143, 50)  

No comments:

Post a Comment