Wednesday, September 29, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to display button on screen tap

Posted: 29 Sep 2021 08:54 AM PDT

I am displaying a network image in the app and I need to display a button when the user taps on the screen. until then it should stay hidden. How can I do it?

return Scaffold(        body: GestureDetector(          onTap:  (){                      },          child: Container(            decoration: BoxDecoration(              image: DecorationImage(                image: NetworkImage(widget.img_url),                fit: BoxFit.contain              )            ),          ),        ),      );  

Issue when sideloading todo-list-with-Azure-backend sample code, I get the following error:

Posted: 29 Sep 2021 08:54 AM PDT

When I attempt to sideload the todo-list-with-Azure-Backend into my desktop teams client, I get the following error (The code compiles and deploys okay to my Azure tenant), Am I missing a permission somewhere? enter image description here

Django admin url decoding

Posted: 29 Sep 2021 08:54 AM PDT

I have a Django admin panel with simple products view. Each product has it's own ID like "bus", "avia", "bus_24" and "avia_26". Url to products page look like this: /products/<product_id>/.

For products with ids like "bus" and "avia" it works just fine. But for "bus_24" and "avia_26" I get HttpRedirect to main page with messages:

Product with ID "avia$" doesn't exist. Perhaps it was deleted?

Product with ID "bus&" doesn't exist. Perhaps it was deleted?

I guees there is smth with decoding/encoding url, so "_24" = $ and "_26" = &.

I tried to override get_object method of admin.ModelAdmin to decode object_id but it didn't worked out. Maybe someone had same problem?

Sorting a queue in O(n log n) using at most 2 queue

Posted: 29 Sep 2021 08:54 AM PDT

We were tasked to sort a queue in O(n log n) using basic functions such as enqueue, dequeue, peek, empty only. Additionally, we may use another queue to help us. No other data structures are allowed.

Having trouble coming up with a solution as I feel like this is possibly an modification of a divide-and-conquer problem but I am unable to come up with a solution using the 4 basic functions.

Is it possible to receive some hints to solve this problem?

Python compares two arrays and save to text file

Posted: 29 Sep 2021 08:53 AM PDT

My goal is to compare all lines in "all.txt" with "blacklist.txt". Any matches will be removed and saved to "all_cleaned.txt". However, my current code is EXTREMELY slow. I have to do this for millions of records, and sadly this is not fast enough. Any suggestions to speed it up will be appreciated

import os  input_file = "all.txt"  blacklist_file = "blacklist.txt"    i = 0    with open(input_file, "r") as fp:      lines = fp.readlines()      new_lines = []      for line in lines:          line = line.strip().lower()          print(str(i) + ": " + line)          i = i + 1          if line not in new_lines:              new_lines.append(line)    output_file = "all_cleaned.txt"  print("Writing data ...")  with open(output_file, "a+") as fp:      fp.write("\n".join(new_lines).lower())  

How to change default region in Google Cloud Console?

Posted: 29 Sep 2021 08:53 AM PDT

I'm trying to change default region for cloud functions. Client side I've changed like this:

const firebaseFunctions = require("firebase-functions");  const functions = firebaseFunctions.region("europe-west3");  

And now when I deploy I can see the correct region. But when I go to the logs in Google Cloud I see 2 hours less so the scheduler doesn't trigger my function.

In the documentation I read that you can get and change the default region from Google Cloud Console. This is my console:

****@cloudshell:~ (*****)$ gcloud config set functions/region europe-west3  Updated property [functions/region].  ****@cloudshell:~ (project)$ gcloud config get-value compute/region  Your active configuration is: [cloudshell-*****]  europe-west3   

Could be a propagation problem? Or am I missing something?

deconstruct return value of function into an array

Posted: 29 Sep 2021 08:53 AM PDT

Im studyig solidity and im trying to understand arrays and destructuring. is it possible to deconstruct returns of functions into arrays ? if so how can that be achieved ?

say i have a function named function someFunction(uint arg1, uint arg2) external returns (uint, uint, uint){// some logic // } I want to destructure the return values into an array. The only way im able to achieve this is by declaring an array, destructuring the return values of someInfo into their own values and then assining each slot in the array a destructured value.

uint[3] memory someArray;    (uint var1, uint var2, uint var3) = someFunction(//some inputs //);  someArray[0] = var1;  someArray[1] = var2;  someArray[2] = var3;  

Is there a better way of achieving this ? Thanks in advance.

Javascript short circuit assignment with default first value

Posted: 29 Sep 2021 08:53 AM PDT

What I want to is something like the following:

let x=32  let y=x===32 ?: 7;  

Basically short circuiting the ternary. I want y to equal x if, and only if, x === 32. In the case above the value assigned to y would be 32. However if I had assigned x to equal 50 or anything else, then y would equal 7.

Is there a safe and elegant way to do this?

Azure Devops Upload Image

Posted: 29 Sep 2021 08:53 AM PDT

I am importing a lot of data into Azure Devops using python. I have all the pieces working. I can upload images, my issue is when I download the image from the Devops website it is not a valid file. I will share my image upload code.

def convertAttachmentToJsonBinary(attachmentPath):      file = open(attachmentPath, 'rb')      file_data = file.read()      encoded_data = base64.b64encode(file_data)      decoded_data = encoded_data.decode()      data = "[" + decoded_data + "]"      return data      def patchWorkItemWithAttachment(case_id, att_id, att_url):      json_template = open("attachment.json", "r")      json_data = json.load(json_template)      json_data[0]['value']['url'] = att_url      json_data[0]['value']['attributes']['comment'] = "Adding attachment"        response = requests.patch(patch_workitem_url.replace("{id}", case_id), json=json_data, headers=headers)      print(response.json())  

While I am uploading a new case, I create the case, add attachments, then patch the newly created case with the new attachment. Again all of this work. I can see the attachment in my case online, however when I download it the file is invalid. Image on Devops enter image description here

deployed and running windows service does not log4net nor appears to pickup connection string to access database

Posted: 29 Sep 2021 08:53 AM PDT

I have the typical "it works on my machine" debacle. I have code that works in visual studio and when published as executable like so:

dotnet publish C:\xyz\BlaSolutions\Project1\Project1.csproj -o C:\Project1Publication -r win-x64 -c Release /p:PublishSingleFile=true   

The code logs nicely using log4net and picks up db windows authentication using this connection string in a appsettings.json:

"Server=BestServerEver;Database=AllDataEva;Integrated Security=true;Connection Timeout=0"

I want to run this as windows service and uses these commands:

sc.exe create Project1 binPath= "C:\Project1Publication\Project1.exe" DisplayName= "Amazing Windows Service" type= own obj= "xyz\un" password= "verysecret"  sc.exe start Project1  

The windows service is deployed and started and does not appear to throw any events in the windows log. However no expected output is generated nor are any log4net outputs created (not even a log4net log file is generated as specified in the log4net.config. Presumably the appsettings.json + log4net.config should be consumed/picked up transparently by the windows service from C:\Project1Publication. I also specify the user name for the windows service to use, which would be used for the windows authentication to access the database given the above connection string.

I know this is a bit of a long shot, but can someone see anything blatantly wrong with the above approach? Thanks.

Java 8 method using streams explanation

Posted: 29 Sep 2021 08:53 AM PDT

I am kinda new in Java 8 and i am trying to understand what the following code does

 @Override  public Optional<String> getMostFrequentLastName(final List<User> users) {      return users.stream().collect(Collectors.groupingBy(User::getLastName, Collectors.counting()))              .entrySet()              .stream()              .filter(entry -> entry.getValue() >= 2)              .reduce((e1, e2) -> e1.getValue() < e2.getValue() ? e2 :                      e1.getValue() > e2.getValue() ? e1 :                              new AbstractMap.SimpleEntry<>(null, e1.getValue()))              .map(Map.Entry::getKey);  }  

Can anyone explain in details what is going on here?

Hichcharts (Highstock) — Why isn't the plotLine being drawn on the chart?

Posted: 29 Sep 2021 08:53 AM PDT

Why isn't the plotLine being drawn on the chart? I've been trying to figure this out for at least 2 hours.

The goal is to add a plotLine in line with a candlestick at any given index (100 in the example). So candle at index 100 in the ohlcarray would be highlighted in the chart. To do this I set the value of the plotLine to 100. Am I doing it wrong?

I really appreciate your help.

// ASSUME WE HAVE 300 BARS    const symbol = 'APPL';    const volume = [ ... ];  const ohlc = [ ... ];      Highcharts.stockChart('chart', {        cropThreshold: 500,        xAxis: {          plotLines: [{              color: 'red',              dashStyle: 'longdashdot',              value: 100,              width: 1,              zIndex: 5          }],      },        series: [{          type: 'candlestick',          id: `${symbol}-ohlc`,          name: `${symbol} OHLC`,          data: ohlc,      }, {          type: 'column',          id: `${symbol}-volume`,          name: `${symbol} Volume`,          data: volume,          yAxis: 1,      }]  });    

Pivot Issue ORA-00918 column ambiguously defined

Posted: 29 Sep 2021 08:53 AM PDT

I am running the below query and need to output the rows as columns. When I am adding the second MAX statement, I am getting an error ORA-00918 column ambiguously defined. Not sure what I am doing wrong. Any help will be appreciated.

SELECT * from (   SELECT a.REF_NUM as "Number", a.SUMMARY, a.DESC_SEARCH as "Description", a.Status, e.Label, e.Value          FROM ca a,          cr_prp e      WHERE           a.PERSID = e.OWNING_CR          AND a.CATEGORY = '16996807'          ORDER by a.REF_NUM DESC)t      PIVOT      (      MAX(CASE WHEN LABEL = 'Plan/UnPlanned' THEN Value END),      MAX(CASE WHEN LABEL = 'Reason for' THEN Value END),      MAX(CASE WHEN LABEL = 'Name & "ID"' THEN Value END)      FOR LABEL      IN ('Plan/UnPlanned',          'Reason for',          'Name & "ID"')      )  

When I run the "ometpp.ini" file, the simulation prompts:

Posted: 29 Sep 2021 08:53 AM PDT

illegal character " " encountered in tag name while parsing display string "i=block/routing" -- at t=0s,envent #0 enter image description here

Part of the code is as follows:

simple nodeR { parameters: @display("i = block/routing"); @signalarrival; @statistic[hopCount](title="hop count"; source="arrival"; record=vector,stats; interpolationmode=none); gates: inout gate[]; }

How should I do it? Please help me.

Undefined index: selector in C:\wamp\www\Elearning\new_pass_stud.php on line 18

Posted: 29 Sep 2021 08:53 AM PDT

I cant get the selector and validator on

$url = "www.elearning.com/forgottenpassword/new_pass_stud.php?selector=" . $selector . "&validator=" . bin2hex($token);  

using this

                $selector = $_GET["selector"];                  $validator = $_GET["validator"];                                    if ( empty($selector) || empty($validator) ) {                    echo "Could not validate your request";                  } else {                    if (ctype_xdigit($selector) !== false && ctype_xdigit($validator) !== false){                  ?>`  

Python list comprehension: add values from a list into multiple separate lists

Posted: 29 Sep 2021 08:54 AM PDT

I want to add values into multiple lists from a single list with list comprehension. There are 4 values in the feature list, which should go into 4 separate lists. my code:

  features = features_time_domain(values, column_name)    feature_lists =[mean_list, std_list, max_list, min_list]    [x.append(y) for x,y in zip(feature_lists, features)]  

The expected output should be something like this:

'x-axis_mean': [[0.010896254499999957,-0.01702540899999986 ,0.24993333400000006 ,-0.2805791479999999, -0.7675066368], 'x-axis_std': [4.100886585107956,3.8269951001730607, 4.19064980513631, 3.7522815775487643, 3.5302154102620498], 'x-axis_max': [6.2789803,7.668256,  11.604536, 9.384419, 7.5865335], 'x-axis_min': [-8.430995,-8.662541, -7.8861814,7.6546354,-5.175732 ]  

but I get:

'x-axis_mean': [[0.010896254499999957, 4.100886585107956, 6.2789803, -8.430995], [-0.01702540899999986, 3.8269951001730607, 7.668256, -8.662541], [0.24993333400000006, 4.19064980513631, 11.604536, -7.8861814], [-0.7675066368, 3.7522815775487643, 9.384419, -7.6546354], [-0.2805791479999999, 3.5302154102620498, 7.5865335, -5.175732]], 'x-axis_std': [], 'x-axis_max': [], 'x-axis_min': []  

I have looked at other post and tried to do something similar as them but my answer is off. I could do something like this, but it looks very ugly:

mean_list.append[features[0]]  std_list.append[features[1]]  max_list.append[features[2]]  min_list.append[features[3]]  

Difference between io.quarkus and io.quarkus.platform

Posted: 29 Sep 2021 08:54 AM PDT

What's the difference between the quarkus group-id io.quarkus.platform and io.quarkus?

In older versions (<2.0.0) the latter (without platform) was used. However, in the new sample projects the group-id io.quarkus.platform is used.

Does method definition carry over separate unit tests?

Posted: 29 Sep 2021 08:54 AM PDT

Using Rails 5.0.7.2 and Minitest 5.1.

I was writing multiple unit tests and looked for possible ways to stub a method call (not the question here). I decided to redefine my instance method:

def Payment_method.usable? ; true ; end  

Then out of caution, we were wondering whether this method redefinition would carry over other distinct tests. This latter behaviour should not happen since unit tests are isolated, but we wanted to confirm this.

Spring Boot controller endpoint request with invalid characters must throw 400 instead 500?

Posted: 29 Sep 2021 08:53 AM PDT

I'm testing a Spring boot microservice and performing some security checking. When I try to send a request to the endpoint with invalid characters to the URL, e.g., https://server/api/dogs/%2500/puppies you noticed the "%2500" is invalid. The service throws 500 Internal Server error and returns a message that there is an invalid character in the request.

Is there a way to validate the URL in the request in my Springboot application so that it will throw 400 Bad Request, instead of 500 Internal Server error.

How can I make my selected outstanding in the form?

Posted: 29 Sep 2021 08:53 AM PDT

I have created two questions in the tag. I want to highlight the answer I chose by changing the background color. However, it is possible for me to do this because when I choose the answer in the first question, then I choose the next question, the highlight in the previous one disappears. So now, how I can do that, and how I can choose my answer by click anywhere in the answer box instead of clicking on the label or the radio box.

function openPresent(event) {        const answer = document.querySelectorAll('.option');      for (let i = 0; i < answer.length; i++) {          answer[i].style.backgroundColor = originalAnswerArray[i];      }        event.target.style.backgroundColor = 'blue';    }    const answer = document.querySelectorAll('.option');  let i;    let originalAnswerArray = [];  for (i = 0; i < answer.length; i++) {      originalAnswerArray.push(answer[i].getAttribute('value'));      answer[i].addEventListener('click', openPresent);  }
.option {      border-top: 1px solid white;      border-bottom: 1px solid white;      display: flex;      justify-content: flex-start;      align-items: center;      flex-direction: row;      width: auto;      padding: 15px;      background-color: #f1f1f1;  }    .option:hover {      background-color: #ddd;  }    label {      margin-left: 15px;  }
<form>            <div class='option'>              <input type='radio' id='option1' name="question1" value="option 1">              <label for='option1'>                option 1               </label><br>            </div>            <div class='option'>              <input type='radio' id='option2' name="question1" value="option 2">              <label for='option2'>option 2</label><br>            </div>            <div class='option'>              <input type='radio' id='option3' name="question1" value="option 3">              <label for='option3'>option 3</label><br>            </div>            <div class='option'>              <input type='radio' id='option4' name="question1" value="option 4">              <label for='option4'>option 4</label><br>            </div>          </form>                              <p><strong> Question 2 of 10</strong></p>                  <p>Question 2</p>                  <form>                      <div class='option'>                          <input type='radio' id='option1' name="question2" value="option 1">                          <label for='option1'>                <div>option 1 </div>              </label><br>                      </div>                      <div class='option'>                          <input type='radio' id='option2' name="question2" value="option 2">                          <label for='option2'>option 2</label><br>                      </div>                      <div class='option'>                          <input type='radio' id='option3' name="question2" value="option 3">                          <label for='option3'>option 3</label><br>                      </div>                      <div class='option'>                          <input type='radio' id='option4' name="question2" value="option 4">                          <label for='option4'>option 4</label><br>                      </div>                  </form>

Screen with multiple lists with background

Posted: 29 Sep 2021 08:53 AM PDT

I am trying to build a scrollable screen which contains multiple lists. To achieve that I am doing something like this:

LazyColumn{       item{       }       items(list of items){         ...       }       item{       }       items(list of items){         ...       }       ...  }  

My problems is that I would like to set a background to each list, but I can't set a modifier to the "items(list){}" object. How can I build this screen? Should I approach the whole screen build in a different way?

Exercism Clojure exercise

Posted: 29 Sep 2021 08:53 AM PDT

I am learning clojure with Exercism and I'm having a bit of trouble finishing the last section of the lasagna problem.

Heres the instruction - Define the total-time function that takes two arguments: the first argument is the number of layers you added to the lasagna, and the second argument is the number of minutes the lasagna has been in the oven. The function should return how many minutes in total you've worked on cooking the lasagna, which is the sum of the preparation time in minutes, and the time in minutes the lasagna has spent in the oven at the moment.

here's my code thats giving me trouble:

(defn prep-time [num-layers]    (* times-two num-layers))    (def sum (prep-time times-two))    (defn total-time [num-layers actual-time]    (def test1 (prep-time num-layers))    (+ test1 actual-time))    (def finished (total-time test1 prep-time))  

Im getting an error saying:

`(defn prep-time [num-layers]   11:   (* times-two num-layers))              ^--sci.impl.fns$fun$arity_1__1213 cannot be cast to java.lang.Number`  

why would I be getting this error?

why tooltip appears wrong in my chart JS?

Posted: 29 Sep 2021 08:54 AM PDT

I have a chart that I have developed using Chart JS and it works good. The problem here is that when I hover on a point, the x axes of that point appears wrong! So for example in the image below, I am hovering on that orange point which have '23000' x axes point. but it appears '18428.91'! it has right values only with the first purple line on the bottom. I think the problem with the tooltip option but I do understand what's the problem

enter image description here

html

 <div class="card-body">                                          <canvas id="lineChart_1"></canvas>                                      </div>  

JS

<script type="text/javascript">          (function($) {      /* "use strict" */              /* function draw() {                } */     var dzSparkLine = function(){      let draw = Chart.controllers.line.__super__.draw; //draw shadow            var screenWidth = $(window).width();                var lineChart1 = function(){                              if(jQuery('#lineChart_1').length > 0 ){              //basic line chart              const lineChart_1 = document.getElementById("lineChart_1").getContext('2d');                            lineChart_1.height = 100;                new Chart(lineChart_1, {                  type: 'line',                  data: {                      defaultFontFamily: 'Poppins',                                            datasets: [                                                             { label: '5390',      data: [         {x: 10000 , y: 58.81 },                                  {x: 11000 , y: 57.34 },                                  {x: 12000 , y: 55.99 },                                  {x: 13000 , y: 54.21 },                                  {x: 14000 , y: 52.09 },                                  {x: 15000 , y: 49.32 },                                  {x: 16000 , y: 45.53 },                                  {x: 17000 , y: 41.87 },                                  {x: 18000 , y: 36.87 },                                  {x: 18428.91 , y: 34.15 },                           ],                                borderColor: '#FF00FF',                              borderWidth: "2",                              backgroundColor: 'transparent',                                pointBackgroundColor: '#FF00FF'},    { label: '6160',      data: [         {x: 12000 , y: 76.66 },                                  {x: 13000 , y: 75.7 },                                  {x: 14000 , y: 74.15 },                                  {x: 15000 , y: 72.38 },                                  {x: 16000 , y: 70.14 },                                  {x: 17000 , y: 68.08 },                                  {x: 18000 , y: 64.76 },                                  {x: 19000 , y: 60.64 },                                  {x: 20000 , y: 55.75 },                                  {x: 21000 , y: 49.57 },                                  {x: 22000 , y: 42.18 },                           ],                                borderColor: '#4472C4',                              borderWidth: "2",                              backgroundColor: 'transparent',                                pointBackgroundColor: '#4472C4'},    { label: '6930',      data: [         {x: 14000 , y: 97.17 },                                  {x: 15000 , y: 96.06 },                                  {x: 16000 , y: 94.58 },                                  {x: 17000 , y: 93.3 },                                  {x: 18000 , y: 91.41 },                                  {x: 19000 , y: 89.35 },                                  {x: 20000 , y: 86.44 },                                  {x: 21000 , y: 82.95 },                                  {x: 22000 , y: 79.01 },                                  {x: 23000 , y: 73.08 },                                  {x: 24000 , y: 65.36 },                                  {x: 25000 , y: 55.55 },                                  {x: 25357.89 , y: 50.67 },                           ],                                borderColor: '#ED7D31',                              borderWidth: "2",                              backgroundColor: 'transparent',                                pointBackgroundColor: '#ED7D31'},    { label: '7700',      data: [         {x: 16000 , y: 119.81 },                                  {x: 17000 , y: 119.22 },                                  {x: 18000 , y: 117.988 },                                  {x: 19000 , y: 116.55 },                                  {x: 20000 , y: 115.05 },                                  {x: 21000 , y: 113.003 },                                  {x: 22000 , y: 110.186 },                                  {x: 23000 , y: 108.44 },                                  {x: 24000 , y: 104.15 },                                  {x: 25000 , y: 99.4 },                                  {x: 26000 , y: 93.33 },                                  {x: 27000 , y: 84.8 },                                  {x: 28000 , y: 68.7 },                                  {x: 28264.22 , y: 60.7 },                           ],                                borderColor: '#A5A5A5',                              borderWidth: "2",                              backgroundColor: 'transparent',                                pointBackgroundColor: '#A5A5A5'},    { label: '8085',      data: [         {x: 19000 , y: 130.56 },                                  {x: 20000 , y: 129.3 },                                  {x: 21000 , y: 127.6 },                                  {x: 22000 , y: 126.08 },                                  {x: 23000 , y: 123.7 },                                  {x: 24000 , y: 121.088 },                                  {x: 25000 , y: 117.9 },                                  {x: 26000 , y: 113.6 },                                  {x: 27000 , y: 108.2 },                                  {x: 28000 , y: 99.17 },                                  {x: 29000 , y: 84.9 },                                  {x: 29555.19 , y: 66.15 },                           ],                                borderColor: '#0070C0',                              borderWidth: "2",                              backgroundColor: 'transparent',                                pointBackgroundColor: '#0070C0'},  {        label: 'Efficiency',        data: [                   {x: 17000, y: 100}        ],        borderColor: 'black'      } ],                                     },              options: {        interaction: {              mode: 'y'          },scales: {    x: {      type: 'linear'    }  }      }              });                        }      }                           /* Function ============ */          return {              init:function(){              },                                          load:function(){                                lineChart1();                              },                            resize:function(){                                    lineChart1();                               }          }            }();        jQuery(document).ready(function(){      });                jQuery(window).on('load',function(){          dzSparkLine.load();      });        jQuery(window).on('resize',function(){          dzSparkLine.resize();                });         })(jQuery);      </script>        

After Editing:enter image description here

Socket.io + Node.js CORS ERROR Blocked my req

Posted: 29 Sep 2021 08:54 AM PDT

I'm using node and socket.io to write an application, which gives an error to enable the Cross-Origin Requests.

const io = require("./socket").init(server, {        cors: {          origin: "*",          methods: ["GET", "POST"],        },      });  

This is my soket.io code...

    let io;      module.exports = {        init: (httpServer) => {          io = require("socket.io")(httpServer);          return io;        },        getIO: () => {          if (!io) {            throw new Error("Socket.io not inittialized");          }      return io;    },  };  

Help me out from this thanks in advance...

Data Design for User-Achievements with attributes

Posted: 29 Sep 2021 08:53 AM PDT

I just started learning about databases and therefore i need a bit of help with the design of my database.

I am trying to design user-achievement system.

User and Achievement has some ability vectors like this.

User - (Ability 1(int) | Ability 2(int) | ... | Ability N(int))    Achievement - (Ability 1(int) | Ability 2(int) | ... | Ability N(int))  

User gains Achievement's ability once, when user achieve it first time.

N is now about 200, and it could be bigger after. Also, about half of user and achievement's ability vector elements are zero. (sparse)

System will use query like these frequently,

  • "User a has achieved Achievement b?",
  • "What is User a's current ability?",
  • "Add Achievement b's ability to User a's ability."

I'm not sure which design would be proper? Here's simple design I come up with.

enter image description here

But, it seems to be problematic when achievement's ability has changed, since all users' ability should change who has achieved the achievement.

Downgrade version of cargo

Posted: 29 Sep 2021 08:54 AM PDT

Have following version:

cargo 1.52.0 (69767412a 2021-04-21)  

And I want to downgrade to 1.51, how is that achieveable?

Is Sedgewick's Shell Sort the most optimal one?

Posted: 29 Sep 2021 08:53 AM PDT

The following is Sedgewigck's version of the Shell Sort. Is it the most optimal or are there more efficient ones?

import java.util.Arrays;  public class ShellSortSedgewick {    public static void main(String[] args) {      { // Sort a[] into increasing order.          int [] a={5,8,44,77,23,81,90,52,25,21,35};          int N = a.length;          int h = 1;          while (h < N / 3) {              h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...          }          while (h >= 1) { // h-sort the array.              for (int i = h; i < N; i++) { // Insert a[i] among a[i-h], a[i-2*h], a[i-3*h]... .                  for (int j = i; j >= h && a[j] < a[j - h]; j -= h) {                   int temp=a[j];                   a[j]=a[j-h];                   a[j-h]=temp;                  }              }              h = h / 3;              System.out.println(Arrays.toString(a));          }      }            // See page 245 for less(), exch(), isSorted(), and main().  }  

Sharing object between dialogs of the same activity

Posted: 29 Sep 2021 08:54 AM PDT

In my small project I have one activity: SomeActivity and three custom dialogs:DialogA,DialogB,DialogC.

Supposing DialogA has a Foo Object which needed to be sent to DialogB, and DialogC will receive this object after DialogB dismissed then send it to SomeActivity.

I tried using interface but ended with spaghetti code.
I want some directions to do it properly.

Span tag onclick loads blank page?

Posted: 29 Sep 2021 08:53 AM PDT

I've got a span tag:

<span id="myBtnfb"      class="demo" onclick="open()">      <span class="icon">&nbsp;</span>      <span class="">Testing</span>  </span>   

and some javascript

  function open() {        alert('Hello');    }  

Now, what I want to happen is when the span is clicked, it fires the function "open". What seems to happen though is it just reloads the page but brings back a blank page. Any ideas?

http://jsfiddle.net/qtf5s/

How can I replace a character with a newline in Emacs?

Posted: 29 Sep 2021 08:53 AM PDT

I am trying to replace a character - say ; - with a new line using replace-string and/or replace-regexp in Emacs.

I have tried the following commands:

  • M-x replace-string RET ; RET \n

    This will replace ; with two characters: \n.

  • M-x replace-regex RET ; RET \n

    This results in the following error (shown in the minibuffer):

    Invalid use of `' in replacement text.

What's wrong with using replace-string for this task? Is there another way to do it?

No comments:

Post a Comment