text:
Q: Error for clone() Method import java.util.*;

public class F1 {
   public static void man(String[] args) {

      ArrayList<Integer> a1 = new ArrayList<Integer>(4);

      a1.add(15);
      a1.add(30);
      a1.add(20);
      a1.add(18);

      ArrayList<Integer> a2 = a1.clone();

      for (Integer number : a2) {
         System.out.println("Number = " + number);
      }
   }
}

A: ArrayList implements Cloneable, so you can clone that way.
But clone returns an Object, not an ArrayList, so you need the cast.
However, if you simply need to copy your ArrayList in a new instance, consider to do:
ArrayList<Integer> a2 = new ArrayList<Integer>(a1);

a2 will have the same elements of a1, but it is a different object.

A: The clone() method does not return the same type.  It does, however, return a copy of the ArrayList; however, it is returned as a java.lang.Object.
In order to make the code function as expected, cast the clone() call return as an ArrayList<Integer> ie:
ArrayList<Integer> a2 = (ArrayList<Integer>) a1.clone();

Edit : "a1.clone()" instead of "a1.close()"


text:
Q: Intermittent '401: Unauthorized' exceptions from server I have a web service that is hosted in a clustered environment.  The web application that is calling this service is also hosted in a clustered environment, but on a different set of IIS6 servers.  Hence, the application servers are appserv1 and appserv2 and the service servers are svcserv1 and svcserv2.  We don't control which servers are accessed since we typically just refer to them as either appserv or svcserv, respectively.
The service is a WCF Service but has been created to be compatible with the .Net 2.0 Web Service framework.  The application runs fine, when it runs, but probably > 35% of the time the service responds with an Exception: The request failed with HTTP status 401: Unauthorized. error.
I've seen others that recommend setting the credentials directly and my application is doing this as follows.
Dim cc As New CredentialCache()
Dim service As WCFServiceRef.Reports

service = New WCFServiceRef.Reports

service.Url = serviceURL
cc.Add(New Uri(service.Url), "Negotiate", New NetworkCredential("username", "password"))
service.Credentials = cc

reportData = service.GenerateReport(reportid, True, parameters, "PDF", Environment)

I have also tried to directly access the individual servers by changing the reference URLs to bypass the load manager and go directly to the domain name for the server but this hasn't made any difference.
I have also seen this MSDN KB article but since I don't directly have access to the server configuration (and it's difficult to get anything changed) I wanted to be sure there isn't something I can do from the application side.  Note that the server has been configured for Windows Authentication and does not allow anonymous access.
Thanks!

A: A lot of this depends on whether your authentication attempts are using Kerberos or falling back to NTLM.  I would suggest using a tool like Fiddler to capture packets being sent from your app server to validate what authentication protocol is being used.
If you find you're using Kerberos, here's a few things to try:

*

*Get your admins to enable Kerberos error logging on both servers, then reattempt the authentication and check for any Kerberos errors in the event logs.  See http://support.microsoft.com/kb/262177.

*Check the SPNs registered for your service - assuming the FQDN of your service is myservice.prd.ad you would want two SPNs - they should be registered to the servers hosting your service if your IIS6 app pool is not running as a service account, and should be registered to the service account otherwise:

*

*HTTP/MYSERVICE.PRD.AD

*HTTP/MYSERVICE

*Also ensure that any DNS entries registered for your service are A (hostname) records rather than CNAME (alias) records.  I've encountered some issues in environments I've worked in where XP/2003 machines attempted to get a Kerberos ticket for the wrong SPN when CNAME records were used for DNS (whereas Windows 7/2008 machines did not).

*You could also try installing DelegConfig on your service servers, it's very good at sorting out the most common issues people have with Kerberos authentication.  See http://www.iis.net/community/default.aspx?tabid=34&g=6&i=1887
Hopefully that helps a bit.  If you're using NTLM then I unfortunately don't have many ideas as I'm used to working in Kerberos-only environments.

A: First thing is to check the IIS logs on each machine and see if the 401 errors are coming from a single machine.
The next thing to check is if the 401's are related to specific urls.

A: Another thing to consider:
Do you need sticky sessions?
Are there servers that are recycling too often?
There's a whole bunch of reasons why you may be getting 401s, so you'll just have to dig around and find out what's going on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift synchronous function waiting for asynchronous functions to finish In view controller, user can select images, then app will upload to server.
User can select multiples images at one, and can select multiple times.
Each image uploaded will returns an URL to download later.
There is a Submit button to save other info and URLs of uploaded images to server.
I want when user press Submit button, app will wait for all images uploaded (returns URL or throws an error).
I'm using await Taskgroup to upload images in parallel each time user select images.
Is there any way to wait for uploading tasks finish other than using sleep()?
Update:
My code to upload images:
let urls = try await upload(images: images, urls: urls)

func upload(images: [UIImage], urls: [String]) async throws -> [String] {
    try await withThrowingTaskGroup(of: String.self, returning: [String].self) { group in
        for (index, image) in images.enumerated() {
            group.addTask { [self] in
                guard let url = try? await upload(image: image, to: urls[index]) else {
                    return ""
                }
                return url
            }
        }

        var downloadURLs = [String]()

        for try await result in group {
            if result != "" {
                downloadURLs.append(result)
            }
        }

        return downloadURLs
    }
}

Uploading images and submitting data is 2 difference actions:

*

*User select images, after that app will upload them automatically.

*User can tap Submit button whenever they like, even when images being uploaded, app has to wait for uploading task finish before submit other data.

A: What about creating a dictionary [URL: UIImage] in your class to keep the state of the uploads (so add/remove when starting/finishing each) and enable your submit button only when that is empty? Do mind wrapping it into a class with a thread-safe implementation though.
EDIT: If the button can't be disabled, you could do something like below:
import SwiftUI
import Combine

struct ContentView: View {
    let viewModel = ViewModel()

    var body: some View {
        VStack {
            Button {
                self.viewModel.upload(url: URL(string: "https://google.com?id=\(UUID().uuidString)")!, image: UIImage())
                self.viewModel.upload(url: URL(string: "https://google.com?id=\(UUID().uuidString)")!, image: UIImage())
            }
            label: {
                Rectangle()
                    .fill(Color.red)
            }

            Button {
                self.viewModel.submit()
            }
            label: {
                Rectangle()
                    .fill(Color.blue)
            }
        }
        .padding()
    }
}

class ViewModel: ObservableObject {
    var uploadRequests = [URL: UIImage]()
    var submitting = false

    let requestPublisher = PassthroughSubject<Bool, Never>()
    var cancellable: AnyCancellable?

    init() {
        self.cancellable = requestPublisher.filter { [weak self] _ in
            self?.submitting ?? false
        }.sink { [weak self] _ in
            self?.uploadToServer()
        }
    }

    func upload(url: URL, image: UIImage) {
        Task {
            print("Uploading image")

            self.uploadRequests[url] = image

            try await Task.sleep(nanoseconds: 1_000_000_000)

            self.uploadRequests[url] = nil

            print("Image uploaded")

            // If submit button was pressed meanwhile...
            if self.uploadRequests.count == 0 {
                self.requestPublisher.send(true)
            }
        }
    }

    func submit() {
        self.submitting = true

        guard self.uploadRequests.count == 0 else {
            print("Still ongoing requests")
            return
        }

        self.uploadToServer()
    }

    func uploadToServer() {
        Task { [weak self] in
            guard let self = self else { return }

            print("Uploading to server")

            self.submitting = false
        }
    }
}

A: I assuming your upload image function look like thís
func uploadImage(image: UIImage) async -> URL {
   // some logic
}

And you want to make many upload image task running in parallel and wait to all upload task to be done. So i think you can do something like
Task {
    submitButton.isEnable = false
    async let firstImage = uploadImage(image: image1)
    async let secondImage = uploadImage(image: image2)
    async let thirdImage = uploadImage(image: image3)
    let images = await [firstImage, secondImage, thirdImage]
    submitButton.isEnable = true
}


text:
Q: Serverless Framework 3.8.0 with Webpack: next is not a function I've recently updated my project to Serverless Framework 3.8.0, but I've noticed that on the webpack plugin, it says the plugin only works with Serverless v1 & v2.
Those of us using Serverless 3.8.0, how do we go about integrating with webpack?
In my serverless.yml I have:
custom:
  webpack:
    webpackConfig: "webpack.config.js"
    serializedCompile: true
    excludeFiles: src/**/*.test.ts
    includeModules: true
    packager: yarn

And in the webpack.config.js I have:
const path = require("path");
const nodeExternals = require("webpack-node-externals");
const slsw = require("serverless-webpack");
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");

module.exports = {
  context: __dirname,
  mode: slsw.lib.webpack.isLocal ? "development" : "production",
  entry: slsw.lib.entries,
  devtool: slsw.lib.webpack.isLocal
    ? "eval-cheap-module-source-map"
    : "source-map",
  resolve: {
    extensions: [".mjs", ".json", ".ts"],
    symlinks: false,
    cacheWithContext: false,
    plugins: [new TsconfigPathsPlugin()]
  },
  output: {
    libraryTarget: "commonjs",
    path: path.join(__dirname, ".webpack"),
    filename: "[name].js"
  },
  target: "node",
  node: {
    __dirname: false
  },
  externals: [nodeExternals()],
  module: {
    noParse: [/dtrace-provider.js$/],
    rules: [
      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
      {
        test: /\.(tsx?)$/,
        loader: "ts-loader",
        exclude: [
          [
            path.resolve(__dirname, "node_modules"),
            path.resolve(__dirname, ".serverless"),
            path.resolve(__dirname, ".webpack")
          ]
        ],
        options: {
          transpileOnly: true,
          experimentalWatchApi: true
        }
      },
      {
        test: /\.(png)$/i,
        use: [
          {
            loader: "url-loader"
          }
        ]
      }
    ]
  }
};

Right now, when I try to run things with Serverless offline, I get the following error:
ANY /local/api/app-config (λ: compass)
× next is not a function
× TypeError: next is not a function
      at before (webpack-internal:///./src/middleware/parameterMiddleware.ts:12:16)
      at runMiddlewares (/app/node_modules/@middy/core/index.js:120:88)
      at runRequest (/app/node_modules/@middy/core/index.js:80:11)
      at instance (/app/node_modules/@middy/core/index.js:22:12)
      at InProcessRunner.run (/app/node_modules/serverless-offline/dist/lambda/handler-runner/in-process-runner/InProcessRunner.js:198:16)
      at processTicksAndRejections (internal/process/task_queues.js:95:5)
      at LambdaFunction.runHandler (/app/node_modules/serverless-offline/dist/lambda/LambdaFunction.js:368:20)
      at hapiHandler (/app/node_modules/serverless-offline/dist/events/http/HttpServer.js:740:18)
      at exports.Manager.execute (/app/node_modules/@hapi/hapi/lib/toolkit.js:60:28)
      at Object.internals.handler (/app/node_modules/@hapi/hapi/lib/handler.js:46:20)
      at exports.execute (/app/node_modules/@hapi/hapi/lib/handler.js:31:20)
      at Request._lifecycle (/app/node_modules/@hapi/hapi/lib/request.js:371:32)
      at Request._execute (/app/node_modules/@hapi/hapi/lib/request.js:281:9)

Any pointers would be greatly appreciated.


text:
Q: Idea + Scala-Play: Editor compiler cannot resolve Twirl templates e.g. views.html.index For some reason IntelliJ Idea version 2016.2.5 editor compiler is not able to recognize or find the compiled twirl templates e.g.
def index = Action {
    Ok(views.html.index()) // <<<<<<<<<<<<<<<<< cannot resolve symbol index
}

Is there a setting that can fix this?
UPDATE I installed Idea Community 2017.1 and also have the issue. I use it with its corresponding SBT and Scala plugins.

A: I would suggest using a proper build tool that compiles the Twirl files. I've used IntelliJ with Gradle and the Play framework before without any issues.
https://github.com/67726e/gradle-twirl
But the authors of the framework also show an example with SBT:
https://github.com/playframework/twirl


text:
Q: frisby.js post body content syntax I have a UI and server data exchange that works well but I wanted to start testing new development with Frisby.js. The UI has a JavaScript form manager that uses jQuery.  My request body is a JavaScript object that is first serialized with JSON.stringify.
var msg = {form:"login",data{username:"elmer",password:"wabbit"}};
var json_msg = JSON.stringify(msg);

Then it is sent by jQuery:
$.ajax(
    url: baseUrl+"forms/"+call,
    data: { req: json_msg },
    type: "POST",
    success: function(msg){...

The raw body content received at the server looks like this:
req=%7B%22form%22%3A%22login%22%2C%22data%22%3A%7B%22username%22%3A%22elmer%22%2C%22password%22%3A%wabbit%22%7D%7D

Since this raw body content is what my server expects and uses successfully, I have tried several combinations of content-type headers and content formats but Frisby.js chokes on them or sends the wrong body.
NOTE:
1. First the message (a JavaScript object) must be serialized.
2. Then req=[serialized_message] must be URIencoded.
These two steps are performed easily with jQuery.ajax() but seemingly are
impossible on Frisby.js
I tried:
  using unserialized JavaScript object,
  using serialized JavaScript object and
  serialized and URIencoded text (shown here)
msg = "%7B%22form%22%3A%22login%22%2C%22data%22%3A%7B%22username%22%3A%22elmer%22%2C%22password%22%3A%wabbit%22%7D%7D";

frisby.create('Login on HHHLEG web site.')
  .addHeader('X-Requested-With', 'XMLHttpRequest')
  .post('http://hhhleg/forms/login', req=msg )

The above code ends up with nothing in the body when it gets to the server.  I suspect there is some simple syntax issue or a content-type issue or Frisby.js cannot perform the combination of serialization and URI encoding because it chokes on the characters involved.

A: Frisby probably expects a JSON encoded request body, rather than jQuery's default application/x-www-form-urlencoded.
Try setting the contentType:
$.ajax({
    url: baseUrl+"forms/"+call,
    data: { req: json_msg },
    type: "POST",
    contentType: "application/json",
    // other properties...
});

A: In similar issue for me helps following:
 1. Create variable with needed name (in your case is "req") and send it with msg content
 2. Use not ordinary frisby js post constructor, but following:
...
    frisby.create('Send valid data in post')
        .post(YourPath,
            req, //before it we need to assign to it value by
                 //"var req = msg" or any byte array
            {
                json: false,
                headers: {
                    "content-type": "application/octet-stream",
                    "Authorization": your.authToken //if needed
                }
            })
        .expectStatus(200)
...

In my case I've tried to send image byte array, but met similar issue with URLencoded message and JSON-form sending request.
If it's doesn't help or seems like not your case - you can visit https://github.com/vlucas/frisby/tree/legacy-0.x/examples page for more examples of POST request with data sending.


text:
Q: How do I recover data after a Windows format with Ubuntu 10.10? I had a system running Windows 7 Home premium and Ubuntu 10.04, side by side dual boot.
I got an Ubuntu 10.10 image, so I decided to update. But during the installation I made a mistake by specifying the whole partition, and after the installation of Ubuntu 10.10, I saw that my Windows and all the other data was gone.
There were around 250GB of data. Is there any way I can recover it? I had a lot of irreplaceable photos and collections on the drive. I do have a recovery CD for my Windows, but it does not detect any Windows OS.

A: There are some programs you can use for data recovery (not complete a recovery) but most of what I've heard are on Windows.

*

*Free Data Recovery software

*Wikipedia - List of Data Recovery Software
But I recommend you to go check out a computer repair centre and see if they have any data recovery services available.
If you try to do it yourself, make sure to install the recovery software to some other computer. Do not use the system on the hard drive with lost files for anything else; mount it read-only if you have to, because the more you write there, the more of the old data will get over-written.

A: I am afraid that most of your data will be lost forever, but you might get lucky with some of the pictures.
Boot from a Ubuntu CD and create a bit by bit image the disk to a USB disk. Then head over to http://plan99.net/~mike/#work and look for the jpeg extract program. run that on the image on the USB disk. It might be able to recover some of the images, since it scans the raw contents of the disk image and looks for the jpeg headers.
Good Luck!

A: Hiren's Boot CD has many programs for data recovery (some for Windows some for DOS).
Here is some more information on the different programs for hard disk recovery.


text:
Q: How to implement a brush snaps in a multi-series line chart? so I'm trying to implement in my chart a brusher like in this exemple:
http://bl.ocks.org/DStruths/9c042e3a6b66048b5bd4
But I get some trouble to set the contextArea
I think that in the exemple the version is d3.v3 and I'm in d3.v4
There might be an issue on this side.
Could you help me on this one ?  I defined slider's part in my code.
I want to notice that my program work without slider's part.
<svg width="960" height="500"></svg>
<script>

    var svg = d3.select("svg"),
        margin = {top: 20, right: 200, bottom: 100, left: 50},
        margin2 = { top: 430, right: 10, bottom: 20, left: 40 },
        width = svg.attr("width") - margin.left - margin.right,
        height = svg.attr("height") - margin.top - margin.bottom,
        height2 = svg.attr("height") - margin2.top - margin2.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%m/%d/%Y %H:%M:%S %p");

    var x = d3.scaleTime().range([0, width]),
        x2 = d3.scaleTime().range([0, width]), // Duplicate xScale for brushing ref later
        y = d3.scaleLinear().range([height, 0]),
        z = d3.scaleOrdinal(d3.schemeCategory10);

    var maxY; // Defined later to update yAxis

    var line = d3.line()
        .curve(d3.curveBasis)
        .x(function(d) { return x(parseTime(d.date)); })
        .y(function(d) { return y(d.temperature); });

    //for slider part-----------------------------------------------------------------------------------

    var context = svg.append("g") // Brushing context box container
        .attr("transform", "translate(" + 0 + "," + 410 + ")")
        .attr("class", "context");

    //append clip path for lines plotted, hiding those part out of bounds
    g.append("defs")
      .append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

    //end slider part-----------------------------------------------------------------------------------

    d3.json("testSerialisation_v5.ujson", function(error, data) {
          if (error) throw error;

        var data = data["Session_test"][0]["datas_lines"];

        let responses = [];

        data.forEach(obj => {
            if (obj.log_time !== "No data") {
                let iterator = 0;
                let final = {};
                obj.datas_line.forEach(d => {
                final[iterator.toString()] = d;
                iterator++;
                });
                final.log_time = obj.log_time;
                responses.push(final);
            }
        });

        var dateKey = d3.keys(responses[0]);
        var i = dateKey.indexOf('log_time')
            if(i != -1) {
                dateKey.splice(i, 1);
            }

        var temp_list = dateKey.map(function(d) {
            return {
                id:d,
                values: responses.map( function(e) {
                    return {
                        date: e.log_time,
                        temperature: e[d]
                    };
                })
            }
        });
        console.log(responses);

        x.domain(d3.extent(responses, function(d) { return parseTime(d.log_time); }));

        x2.domain(x.domain()); // Setting a duplicate xdomain for brushing reference later

        y.domain([
            d3.min(temp_list, function(c) { return d3.min(c.values, function(d) { return d.temperature; }); }),
            d3.max(temp_list, function(c) { return d3.max(c.values, function(d) { return d.temperature; }); })
        ]);

        z.domain(temp_list.map(function(c) { return c.id; }));

        //for slider part-----------------------------------------------------------------------------------

        var brush = d3.brushX() //for slider bar at the bottom
            .extent(responses, function(d) { return parseTime(d.log_time); })
            .on("brush", brushed);

          context.append("g") // Create brushing xAxis
              .attr("class", "x axis1")
              .attr("transform", "translate(0," + height2 + ")")
              .call(x2);

          // HOW TO SET CONTEXTE AREA ???
          var contextArea = d3.area() // Set attributes for area chart in brushing context graph
            .interpolate("monotone")
            .x(function(d) { return xScale2(d.log_time); }) // x is scaled to xScale2
            .y0(height2) // Bottom line begins at height2 (area chart not inverted)
            .y1(0); // Top line of area, 0 (area chart not inverted)

          //plot the rect as the bar at the bottom
          context.append("path") // Path is created using svg.area details
            .attr("class", "area")
            .attr("d", contextArea(responses[0].values)) // pass first categories data .values to area path generator
            .attr("fill", "#F1F1F2");

          //append the brush for the selection of subsection
          context.append("g")
            .attr("class", "x brush")
            .call(brush)
            .selectAll("rect")
            .attr("height", height2) // Make brush rects same height
              .attr("fill", "#E6E7E8");

        //end slider part-------------------------------------------------------------------------------

        g.append("g")
            .attr("class", "axis axis--x")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x));

        g.append("g")
              .attr("class", "axis axis--y")
              .call(d3.axisLeft(y))
            .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", "0.71em")
              .attr("fill", "#000")
              .text("Temperature, ยบC");

        var temp = g.selectAll(".temp")
            .data(temp_list)
            .enter().append("g")
            .attr("class", "temp");

        temp.append("path")
            .attr("class", "line")
            .attr("d", function(d) { return line(d.values); })
            .style("stroke", function(d) { return z(d.id); });

        temp.append("text")
            .datum(function(d) { return {id: d.id, value: d.values[d.values.length - 1]}; })
            .attr("transform", function(d) { return "translate(" + x(parseTime(d.value.date)) + "," + y(d.value.temperature) + ")"; })
            .attr("x", 3)
            .attr("dy", "0.35em")
            .style("font", "10px sans-serif")
            .text(function(d) { return d.id; });

        //for brusher of the slider bar at the bottom
        function brushed() {

            x.domain(brush.empty() ? x2.domain() : brush.extent()); // If brush is empty then reset the Xscale domain to default, if not then make it the brush extent

            svg.select(".x.axis") // replot xAxis with transition when brush used
                  .transition()
                  .call(xAxis);

            maxY = findMaxY(responses); // Find max Y rating value categories data with "visible"; true
            y.domain([0,maxY]); // Redefine yAxis domain based on highest y value of categories data with "visible"; true

            svg.select(".y.axis") // Redraw yAxis
              .transition()
              .call(y);

            issue.select("path") // Redraw lines based on brush xAxis scale and domain
              .transition()
              .attr("d", function(d){
                  return d.visible ? line(d.values) : null; // If d.visible is true then draw line for this d selection
              });

        };

    });
</script>

Data is use to test :
{
    "Session_test": [{
        "datas_lines": [{
                "datas_line": [],
                "log_time": "No data"
            },
            {
                "datas_line": [],
                "log_time": "No data"
            },
            {
                "datas_line": [],
                "log_time": "No data"
            },
            {
                "datas_line": [
                    "157",
                    "158",
                    "157",
                    "157",
                    "157",
                    "158",
                    "159",
                    "161",
                    "160",
                    "160",
                    "159",
                    "158",
                    "159",
                    "160",
                    "160",
                    "160",
                    "160",
                    "161",
                    "160",
                    "161",
                    "159",
                    "161",
                    "161",
                    "158",
                    "161",
                    "159",
                    "160",
                    "157"
                ],
                "log_time": "5/18/2017 4:32:14 PM"
            },
            {
                "datas_line": [
                    "154",
                    "156",
                    "155",
                    "155",
                    "155",
                    "156",
                    "158",
                    "159",
                    "158",
                    "157",
                    "157",
                    "156",
                    "157",
                    "158",
                    "159",
                    "158",
                    "158",
                    "159",
                    "159",
                    "159",
                    "158",
                    "159",
                    "159",
                    "156",
                    "159",
                    "157",
                    "158",
                    "156"
                ],
                "log_time": "5/18/2017 4:34:14 PM"
            },
            {
                "datas_line": [
                    "154",
                    "156",
                    "155",
                    "155",
                    "155",
                    "156",
                    "158",
                    "159",
                    "158",
                    "157",
                    "157",
                    "156",
                    "157",
                    "158",
                    "159",
                    "158",
                    "158",
                    "159",
                    "159",
                    "159",
                    "158",
                    "159",
                    "159",
                    "156",
                    "159",
                    "157",
                    "158",
                    "156"
                ],
                "log_time": "5/18/2017 4:34:14 PM"
            }
        ]
    }]
}

Oh I've also noticed that my x axis doesn't display correctly.
If someone have the answer to this also I'm take it ^^'


text:
Q: Spring Cloud Services - Eureka I am trying to learn microservices using Spring and Spring Boot, and learning to deploy into cloud platform. I am planning to create an Angular 2 frontend application which communicates with my deployed microservice. Now I just going through Spring cloud services Eureka, Zuul, circuit breakers, etc.

*

*When I reading I found that Eureka is using for service registry for finding services each other. Here my doubt is that when I am communicating from my Angular 2 http request, I need to use these service registering?

*What cloud configuration I need to follow to make a REST API to microservice? I am getting confused how I need to push my sample microservice to cloud, since I am a beginner.

A: No...your frontend app should talk to Zuul which is already registered to Eureka and can query it to find the right backend server you need.
I wrote about it, hope it helps


text:
Q: draw icon with transparency in xlib and cairo Now that I've got the icons I want to draw them correctly.
At the moment I'm using Cairo to draw these images on a window.
I have a mask and the icon as pixmap.
cairo_surface_t *image;
cairo_surface_t *imask;
cairo_surface_t *surface;
cairo_t *csurface;

surface = cairo_xlib_surface_create(display, d, DefaultVisual(display, screen), 400, 400);
csurface = cairo_create(surface);

Pixmap icon;
Pixmap mask;

//XWM Stuff ...
if(icon != 0)
{
   get_pixmap_geometry(display, icon, &width, &height, &depth);
   image = cairo_xlib_surface_create(display, icon, DefaultVisual(display, screen), width, height);
   cairo_set_source_surface(csurface, image, 0, 0);
   //How do I apply the mask?
   //I tried cairo_set_operator(csurface, CAIRO_OPERATOR_SOURCE);
   cairo_paint(csurface);
}

But the icons do not have any transparencies. I've found no example to solve this with cairo on the internet. There is only a complicated way but it's so badly documented that it doesn't help me at all.
Does someone have a link or an example for how to restore the original icon with its transparencies?
Thank you in advance.

A: Here is an example from awesome where it "turns" the icon into a cairo surface: https://github.com/awesomeWM/awesome/blob/430f4fab15bb101b4af9fadbebb9a9bfa47ba9de/objects/client.c#L1501
This uses xcb instead of Xlib, but you should manage to still understand this. The part that handles a mask begins in line 1538. Basically, a new cairo surface is created and a cairo context is set up for it. The source surface is the icon and the mask is applied via cairo_mask_surface ("use the alpha channel of some cairo surface as the mask of a drawing operation"). You can just copy this part to your code so that you don't have to draw the icons to a temporary surface.
TL;DR: The answer to your //How do I apply the mask? is: Use cairo_mask_surface() instead of cairo_paint().


text:
Q: Python: Using the xlrd module to get a cell's row,column I am using the xlrd module for handling data in excel (if there is any better module please advise!). Is there any way to extract a cell's row and column information? Are there any members or methods besides introducing a counter? This question was asked a year ago but didn't receive much attention.
Also did anyone find any good API detailing this module? All I found was this: http://www.lexicon.net/sjmachin/xlrd.html#xlrd.Rowinfo-class
Thanks!


text:
Q: Using a script for slurm I'm a beginner user on Ubuntu 20.04 LST. Down there where it is a script on python for slurm that I have been trying to work however it doesn't.
There is something wrong at three variables.
#! /bin/bash

ROOT_UID=0

#Run as root, of course. (this might not be necessary, because we have to run the script somehow with root anyway)
if [ "$UID" -ne "$ROOT_UID" ]
then
     echo "Must be root to run this script"
     exit "$E_NOTROOT"
fi

#test, arguments are down there for slurm.
if [ $# -eq 3 ]; then
slurmname=$1
accountname=$2
maxjobsnumbers=$3

       # to create just a slurm user on the default account
       sacctmgr create user -s "$slurmname"  "$accountname"

       # to setup job limit for a slurm user
       sacctmgr -i modify user "$slurmname" set "$maxjobsnumbers"

       # to show job limit
       sacctmgr show ass

       echo ""
       echo "The user has been setuped on Slurm"
       sacctmgr show user "$slurmname"
else
       echo  " this program needs 3 arguments you have given $# "
       echo  " you have to call the script $0 slurmname, accountname and maxjobsnumbers "
fi
exit 0

When i run the .sh file with the command, output is;
tonny (slurmname)
music (accountname)
1 (maxjobsnumbers)
 root@hn:/home/sysadmin1/Desktop# ./adduser_slurm.sh tonny music 1

 Need name of account to add user to.
 Nothing new added.
 Bad format on 1: End your option with an '=' sign
 Cluster    Account       User  Partition     Share   Priority
 GrpJobs       GrpTRES GrpSubmit     GrpWall   GrpTRESMins
 MaxJobs       MaxTRES MaxTRESPerNode MaxSubmit     MaxWall
 MaxTRESMins                  QOS   Def QOS GrpTRESRunMin
 ---------- ---------- ---------- ---------- --------- ---------
 - ------- ------------- --------- ----------- ------------- ----
 --- ------------- -------------- --------- ----------- ---------
 ---- -------------------- --------- -------------
 cluster       root                               1
 normal
 cluster       root       root                    1
 normal
 cluster      music                               1
 normal
 cluster      music       cta1                    1
 3
 normal
 cluster      music       cta2                    1
 2
 normal

  The user has been setuped on Slurm
  User   Def Acct     Admin
  ---------- ---------- ---------

No new user who has been added.
I mean, how I can create a new user, how I can add the new user on slurm account, and how I can setup maxjob limits for the new user with this script on slurm?


text:
Q: Set valued map and equality of sets Let $K$ a compact of $\mathbb{R}^p$ and $t\mapsto F(t)$ a set-valued function such that $F(t)$ is a closed set of $\mathbb{R}^p$ for all $t\in \mathbb{R}$.
Is it true that
$$
\{t: F(t)\cap K\neq \emptyset\} = \bigcup_{n\ge 1} \{t:F(t)\cap V_n\neq \emptyset\} \qquad (*)
$$
where $V_n=\{x,d(x,K)<1/n\}$ ?
Because what I find is that :
$$
\{t: F(t)\cap K\neq \emptyset\} = \bigcap_{n\ge 1} \{t:F(t)\cap V_n\neq \emptyset\}
$$
and I don't understand the argument to show $(*)$ use in page 72 of Georges, Exercices in Integration, 1984 available here.
proof:
$\subset$
If $t\in \{t: F(t)\cap K\neq \emptyset\}$ then let $x\in F(t)\cap K$ this means that $x\in V_n$ for all $n$ so $x\in F(t)\cap V_n$ for all $n$.
$\supset$ If $t\in \bigcap_{n\ge 1} \{t:F(t)\cap V_n\neq \emptyset\}$ then for all $n$ there is $x_n\in V_n\cap F(t)$.
Since $V_n\cap F(t)$ is bounded we can extract a converging subsequence $y_n \to y$. We have $d(y_n,K)<1/n$ for all $n$ so $y\in K$. Also $y\in F(t)$ so $y\in F(t)\cap K$ and $t\in  \{t: F(t)\cap K\neq \emptyset\}$.
Example for $(*)$.
Take $F(t)$ be the unit ball centered at $(t,0,\dots,0)$ and consider $K$ be the unit ball centered at $0$.
Then $\{t: F(t)\cap K\neq \emptyset\}=[-2,2]$.
$V_n$ are the ball centered at $0$ of radius $1+1/n$ and we have
$F(t)\cap V_n \neq \emptyset$ for $t\in [-2-1/n,2+1/n]$ so
$\bigcup_{n\ge 1} \{t:F(t)\cap V_n\neq \emptyset\}
=\bigcup_{n\ge 1} [-2-1/n,2+1/n]$ which is not $[-2,2]$... so there must be a typo in the book.

A: Just a little nitpick; you should say $V_1\cap F(t)$ is compact and $V_n\cap F(t)\subseteq V_1\cap F(t)$, i.e. $x_n\in V_1\cap F(t)$ for every $n$, so $(x_n)$ admits a convergent subsequence. You wrote: $x_n$ is in a bounded set for every $n$, and that is not enough to say $(x_n)$ has a convergent subsequence.
Other than that, I agree with you that: $\{t:F(t)\cap K\neq\emptyset\}=\bigcap_{n\ge1}\{t:F(t)\cap V_n\neq\emptyset\}$. The author definitely made a typo. My confidence in this comes from the following:

"If for all $n$, there exists $x_n\in...$" means the author is treating the union as an intersection. It is a typo: their text is correct, but their maths-formatting must have gone awry somehow.


text:
Q: BinaryContent Stream wrapper in Grails I am trying to write a simple wrapper in grails that will read a binary file from a non-public back-end web-server and makes it available as a stream to a public server.
The first question is what is the best method to handle such a solution considering that the Grails will attempt to render views by default.
I am attempting a solution which leads to an "Attempted read from closed stream." which apparently looks to avoid the view rendering by invoking response but I am not sure if this is a good solution anyway.
I am reading the back-end file through the following code:
def http = new HTTPBuilder(baseUrl)
http.request(method, ContentType.BINARY) {
                uri.path = path
                uri.query = query
                response.success = { resp, inputstream ->
                    log.info "response status: ${resp.statusLine}"
                    resp.headers.each { h -> log.info " ${h.name} : ${h.value}" }
                    return inputstream
                }

and later attempt to push it to the client through the following method in a controller:
def binary(){
      response.outputStream << getBinaryContent("http://aaa" );
      response.flush()
    }

Error: "Attempted read from closed stream."

A: If I'm not mistaken << will close the response so response.flush() is invalid.
Here's the snippet that I use for CSV, just replace with your content type:
byte[] bytes = fileGenerated.getBytes() //fileGenerated is a File
response.setContentType("text/csv")
response.setContentLength(bytes.length)
response.setHeader("Content-Disposition", "attachment; filename=" + fileGenerated.getName())
response.outputStream << bytes


text:
Q: Current User Location return Zero values I use a global variable (declared as below )for latitude and longitude because i need to use them in other classes
in .h class :
extern NSNumber *MYGlobalVariableLat;
extern NSNumber *MYGlobalVariableLong;

Then in .m class:
NSNumber *MYGlobalVariableLat;
NSNumber *MYGlobalVariableLong;

MYGlobalVariableLat = [NSNumber numberWithDouble:[(id)self.mapView.userLocation coordinate].latitude];

MYGlobalVariableLong = [NSNumber numberWithDouble:[mapView.userLocation coordinate].longitude];

NSLog(@"Lat %@",MYGlobalVariableLat);
NSLog(@"Long %@",MYGlobalVariableLong);

that's always print Zero , Any help please ..


text:
Q: website.php#footer?variable="value" is this possible? When I was using this href link website.php#footer?variable="value" the variable value doesn't show up? or this is not possible?
the "#footer" is an anchor id so when you click an  tag it will scrolldown to the selected div with an id of "footer". I want to pass a variable from one page to another by using "?variable="value"".
But when I combined those two it doesn't work. Thank you in advance.


text:
Q: Linking to Framework I've a number of frameworks that I'm linking to my main project but for some reason, whenever I run the whole thing outside Xcode the executable cannot find the frameworks at all.
The frameworks have the dynamic installation path set to @loader_path/../Frameworks. I've tried simply put @rpath but it didn't work either. Runpath Search Paths is empty on the main executable.
Is there an easy way to debug this? I think I've been through every website and blog post that talks about framework linking and nothing's been of help.

A: If, for example, you have a Build Phase where you copy the Frameworks into your app bundle…

In your app Build Settings..
Runpath Search paths @executable_path/../Frameworks
In your framework Build Settings..
Dynamic Library Install Name @rpath/$(EXECUTABLE_PATH)
(where the macro $(EXECUTABLE_PATH) should be expanded to something like AFramework.framework/Versions/A/AFramework)
If you get it wrong your app should crash on startup. The crash report should say something like
Dyld Error Message:
  Library not loaded: @rpath/TestyFramework.framework/Versions/A/TestyFramework
  Referenced from: /path/to/TestyApp.app/Contents/MacOS/TestyApp
  Reason: image not found

which should help you work out what the values should be and where the framework should be
ie in my case the full runpath search path is..
/path/to/TestyApp.app/Contents/MacOS/TestyApp/../Frameworks

therefor the library should be found at..
/path/to/TestyApp.app/Contents/MacOS/TestyApp/../Frameworks/TestyFramework.framework


text:
Q: React-hook-form isValid not working in stepper when going back I posted this question on react-hook-form issues but thought of posting here too in case anyone found a solution for it.
I'm having this problem with isValid state when using react-hook-form on a stepper. The state of isValid seems a bit messed up when we use a back button. For example, if first step is valid and you go on to the next, trigger an error and go back, isValid will be false even though the first step is still valid.
This is a problem because I would like to use isValid as the state for the 'next' button to be disabled or not.
Is there any suggestions how to get this working or is it a bug?
Or is there another suggestion for what variable to use to disable the button?
Steps to reproduce

*

*Go to this CSB https://codesandbox.io/s/heuristic-lehmann-df6hmw

*Enter first name

*Enter last name

*Click Next

*Don't fill in address, click Next to trigger error

*Click Back

*See that Next button is greyed out on first step, even though the step is still valid.

Expected behaviour
isValid should match the valid state of current step
React hook form version: 6.14.0 but also seen on 7.33.0

A: EDIT:
For anyone having the same problem.. someone answered my question on react-hook -form's discussion page.

*

*Add to each step a dummy hidden input with shouldUnregister: true and unique name

      <input
        type="hidden"
        {...register("step1", {
          shouldUnregister: true
        })}
      />

This makes the isValid state somehow refresh when going backwards and forwards in the stepper.
CSB with this solution, see different step components: https://codesandbox.io/s/jovial-swartz-t31nu3?file=/src/steps/Step1.js:299-419
Github discussion: https://github.com/react-hook-form/react-hook-form/discussions/8787


text:
Q: Use a variable table name for Entity Framework SqlQuery to fetch data into entity Class I want to convert string var to entity framework class but I don't now how.
I have searched a lot but can not found anything
public JsonResult GetReports(string tbl)
{
    using (Context db = new Context())
    {
        // *** Problem is that tbl is string and I want to Cast tbl
        //     to Users Class OR eny of  my other Class
        var result= db.Database.SqlQuery<tbl>("SELECT * FROM Users");
        return Json(new { data = result});
    }
}

public partial class Users
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public Nullable<bool> Gender { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }
    public bool Deleted { get; set; }
}

The reason of way I want to do something like that is I want to crete some dynamic method and tbl can be any of my table names (As a string)

A: Generic Approach
Given that you have strongly named classes (like Users), there should be no reason to resort to weak or dynamic approaches.
For example, if the requirement is to build a generic repository Query capability, which DRY's up the data access code and possibly introduces common cross cutting concerns like logging, instrumentation, possibly retries, and exception handling, then you can use a generic wrapper around SqlQuery<T>:
public async Task<IEnumerable<T>> TypedQuery<T>(string myQuery)
{
    try
    {
        using (var db = new DbContext(ConnString))
        {
            return await db.Database
                .SqlQuery<T>(myQuery)
                .ToListAsync()
                .ConfigureAwait(false);
        }
    }
    catch (Exception ex)
    {
        // Log error here
        // Consider if the query can be retried
        // Consider whether the exception should be propogated or swallowed
        // Should the return type extended to indicate success / failure
        return Enumerable.Empty<T>();
    }
}

Which you can invoke like so, using the generic type parameter to indicate the type of the target POCO (Users in this case):
var repo = new MyRepo();
var myUsers = await repo.TypedQuery<Users>("SELECT Id, Name FROM Users");

The benefit is that myUsers is a strongly typed collection.
Dynamic Approach
In theory it is possible to use the Type overload of SqlQuery to answer your original question. You can either pass in a System.Type directly, or I guess you could map some other key abstraction to the type, such as this:
private static readonly IReadOnlyDictionary<string, Type> MyTypeMap
= new Dictionary<string, Type>
{
    { "users", typeof(Users)},
    { "foo", typeof(Foo)},
    ... other type maps here
};

public async Task<IEnumerable<object>> WeakQuery(string someType, string someQuery)
{
    Type typeOfMyClass;
    if (MyTypeMap.TryGetValue(someType, out typeOfMyClass))
    {
        using (var db = new DbContext(ConnString))
        {
            return await db.Database.SqlQuery(typeOfMyClass, someQuery)
                .ToListAsync()
                .ConfigureAwait(false);
            // The problem now is that you get an untyped DbRawSqlQuery
        }
    }
    return Enumerable.Empty<object>();
}

The problem is though is because of the weak typing that you would need to either re-cast the result, or work with dynamic, which will make for very fragile code when used, such as :
var repo = new MyRepo();
dynamic x = await repo.WeakQuery("users", "SELECT Id, Name, Gender FROM Users");
Assert.IsNotNull(x);
Assert.IsTrue(Enumerable.First(x).Name == "Foo");

*

*Try to avoid SELECT * - instead, select all of the columns explicitly to map into the Users class.


text:
Q: Adding a 2012 R2 server to a 2008 R2 SharePoint 2010 farm Having an issue where configuration is looking for SharePoint 2010 updates/patches that it sees on other servers in the farm. What is the best way to get all the updates/patches that are missing when the automatic update won't pull them?
Ultimate goal will be to have the following configuration:
WFE1-Server2008
WFE2-Server2008
WFE3-Server2012 (this is the new server i'm trying to add to the farm)
APP1-Server2008
UPDATE W/MISSING PATCHES:
Microsoft SharePoint Server 2010 Installed Across Server Farm
 Microsoft Word Server
Security Update for Microsoft SharePoint Server 2010 (KB3127950) 64-Bit Edition (14.0.7176.5000)
 Missing on WFE1
Missing on WAPPS1
Missing on WFE2
 Security Update for Microsoft SharePoint Server 2010 (KB3118377) 64-Bit Edition (14.0.7174.5001)
 Missing Locally
 Microsoft Excel Services Components
Security Update for Microsoft SharePoint Server 2010 (KB3118381) 64-Bit Edition (14.0.7176.5000)
 Missing on WFE1
Missing on WAPPS1
Missing on WFE2
 Security Update for Microsoft SharePoint Server 2010 (KB3115119) 64-Bit Edition (14.0.7173.5000)
 Missing Locally
 Microsoft Office Server Proof (English) 2010
Update for Microsoft SharePoint Server 2010 (KB3055040) 64-Bit Edition (14.0.7151.5000)
 Missing Locally
 Microsoft SharePoint Portal
Update for Microsoft SharePoint Server 2010 (KB3055040) 64-Bit Edition (14.0.7155.5000)
 Missing Locally
 Microsoft SharePoint Portal English Language Pack
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7113.5000)
 Missing Locally
 Microsoft Slide Library
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7109.5000)
 Missing Locally
 PerformancePoint Services for SharePoint
Update for 2010 Microsoft Business Productivity Servers (KB2880521) 64-Bit Edition (14.0.7160.5000)
 Missing Locally
 PerformancePoint Services in SharePoint 1033 Language Pack
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7109.5000)
 Missing Locally
 Microsoft Visio Services Web Front End Components
Update for Microsoft SharePoint Server 2010 (KB3055040) 64-Bit Edition (14.0.7149.5000)
 Missing Locally
 Microsoft Excel Services English Language Pack
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7109.5000)
 Missing Locally
 Microsoft Access Services Server
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7113.5000)
 Missing Locally
 Microsoft Access Services English Language Pack
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7109.5000)
 Missing Locally
 Microsoft Web Analytics Web Front End Components
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7124.5000)
 Missing Locally
 Microsoft Web Analytics English Language Pack
Hotfix for Microsoft SharePoint Server 2010 (KB2883103) 64-Bit Edition (14.0.7109.5000)
 Missing Locally
UPDATE: (after applying august cu as mentioned below)
Looks like that took care of most of them. Thanks to you both for that idea. I'm still seeing the following and when I try to manually download and install the patches listed as missing I get the message that they're already installed.
Microsoft SharePoint Server 2010 Installed Across Server Farm
 Microsoft Word Server
Security Update for Microsoft SharePoint Server 2010 (KB3127950) 64-Bit Edition (14.0.7176.5000)
 Missing on WFE1
Missing on WAPPS1
Missing on WFE2
 Security Update for Microsoft SharePoint Server 2010 (KB3118377) 64-Bit Edition (14.0.7174.5001)
 Missing Locally
 Microsoft Excel Services Components
Security Update for Microsoft SharePoint Server 2010 (KB3118381) 64-Bit Edition (14.0.7176.5000)
 Missing on WFE1
Missing on WAPPS1
Missing on WFE2
 Security Update for Microsoft SharePoint Server 2010 (KB3115119) 64-Bit Edition (14.0.7173.5000)
 Missing Locally

A: By looking at the latest build numbers on your list, it looks like you are missing the August 2015 CU package.  You can find the list of Build Numbers at SharePoint Server build numbers.
You'll have to install that package to your new server to add the server to the farm.  You must have SP2 installed to install the package, so if your installation of SharePoint on the new server did not include SP2, make sure to install it first.


text:
Q: Windows time keeps changing to a certain (incorrect) local time My laptop (ThinkPad) was purchased in Germany, then I move to a different time zone. The time of Windows 10 keeps changing back to German time. It can be fixed by clicking "Sync now" but how can I avoid doing so every time after (re)booting?
Regarding the setting:

*

*"Set time automatically" is ON

*Time zone and region are correct and has never been changed even when the time is wrong

It might have something to do with the dual boot, by the other OS (Ubuntu) works perfectly regarding system time


text:
Q: Return nothing or Error 500 when posting JSON by Python requests? I have a crawl-data task, after inspecting the URL with Firefox F12 (DevTools), I find that the site needs a JSON array input looks like:

phyIDs: Array
  0: "FDER047ERDF"

and returns some data also in JSON format:

trueIDs: Array
  0: "802.112.1"

What I need is just the 'trueIDs', so I use Python 3.6.1 and Requests to do the job, here is parts of the code:
import json
import requests

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0',
           'Cookie': 'JSFDKF.......',
           'Content-Type': 'application/json;charset=UTF-8'}

data = {'phyIDs': json.dumps([{0: 'FDER047ERDF'}])}

resp = requests.post(url, headers=headers, verify=False,
                     data=data)
print(resp.text)

But the printed response text is a html like message saying that some error occurs, and the status_code is 500, however, if I comment the 'Content-Type' part in headers, and use normal dict instead of JSON as the input data, then nothing returns and the status_code changes to 415, now I don't know what to do and hope someone could help me, thanks very much!
...........
Thanks guys, I have solved this. The problem is that I shouldn't add '0' in the JSON array!


text:
Q: Attempt to invoke virtual method null object reference Main Activty:
    TextView tvDescription;
    ArrayList<String> descriptions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvDescription = (TextView)findViewById(R.id.tvDescription);

        descriptions = new ArrayList<>();
        descriptions.add("Description for item 1");
        descriptions.add("Description for item 2");
        descriptions.add("Description for item 3");
    }

    @Override
    public void onItemSelected(int index) {

        tvDescription.setText(descriptions.get(index));
    }
}

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/listFrag"
        android:name="com.example.fragmentsvideo2018.ListFrag"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@layout/fragment_list" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/detailFrag"
        android:name="com.example.fragmentsvideo2018.DetailFrag"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        tools:layout="@layout/fragment_detail" />
</LinearLayout>

ListFrag:
ItemSelected activity;

public interface ItemSelected
{
    void onItemSelected (int index);
}

public ListFrag() {
    // Required empty public constructor
}

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);

    activity = (ItemSelected) context;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ArrayList<String> data = new ArrayList<String>();
    data.add("1.This is item 1");
    data.add("2.This is item 2");
    data.add("3.This is item 3");

    setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data));
    activity.onItemSelected(0);
}

@Override
public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {

    activity.onItemSelected(position);
}

}
fragment_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ListFrag">

    <ListView
        android:id="@+id/lvLIst"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Detail Frag:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_detail, container, false);
    }
}

fragment_deal.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/design_default_color_primary"
    android:orientation="vertical"
    tools:context=".DetailFrag">

    <TextView
        android:id="@+id/tvDescription"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:layout_marginRight="20dp"
        android:text="@string/textview"
        android:textColor="#FFFFFF"
        android:textSize="18sp" />
</LinearLayout>

Error:
2021-09-11 16:27:03.357 29251-29251/com.example.fragmentsvideo2018 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fragmentsvideo2018, PID: 29251
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.fragmentsvideo2018.MainActivity.onItemSelected(MainActivity.java:30)
at com.example.fragmentsvideo2018.ListFrag.onActivityCreated(ListFrag.java:52)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2996)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:580)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:285)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I tried to search in this site and other but I didn't find the solution.
Maybe I'm doing something wrong because I'm only a beginner.
Please help me!!

A: As far as i can tell from the code you provided, the issue lies in the xml files. You try to get the TextView via findViewById() from within ActivityMain.java, but the TextView is declared in fragment_deal.xlm. As far as i know findViewById only finds components declared in the xml file associated with the java file calling.


text:
Q: Mockito: mock async method I need to test this method with JUnit and Mockito
 function uploadData() {
    myObject.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    upload(arguments, callbackContext);
                }
            });
        }

How to mock myObject to call upload(arguments, callbackContext) not in background thread ?

A: You'll need to do a few things here. First, replace the ThreadPool with a mock, so you have access to mock execute at all. Then use an ArgumentCaptor in a verify call to get access to the Runnable. Finally, trigger the Runnable and test the state afterwards.
@Test public void shouldUploadInBackground() {
  // declare local variables
  MyObject mockMyObject = Mockito.mock(MyObject.class);
  ThreadPool mockThreadPool = Mockito.mock(ThreadPool.class);
  ArgumentCaptor<Runnable> runnableCaptor =
      ArgumentCaptor.forClass(Runnable.class);

  // create the system under test
  when(mockMyObject.getThreadPool()).thenReturn(mockThreadPool);
  SystemUnderTest yourSystemUnderTest = createSystem(mockThreadPool);

  // run the method under test
  yourSystemUnderTest.uploadData();

  // set the runnableCaptor to hold your callback
  verify(mockThreadPool).execute(runnableCaptor.capture());

  // here you can test state BEFORE the callback executes
  assertFalse(yourSystemUnderTest.isDataUploaded());

  // call run on the callback
  runnableCaptor.getValue().run();

  // here you can test state AFTER the callback executes
  assertTrue(yourSystemUnderTest.isDataUploaded());
}

A: I think the following would work:
Mockito.doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        upload(arguments, callbackContext);
    }).when(myObjectSpy.getThreadPool()).execute(Mockito.any(Runnable.class));

but i am not realy sure.


text:
Q: modify array in loop Here is the code:
$arraya = array('a','b','c');
foreach($arraya as $key=>$value)
{
    if($value == 'b')
    {
        $arraya[] = 'd';
        //print_r($arraya);    //$arraya now becomes array('a','b','c','d')
    }
    echo $key.' is '.$value."\n";
}

and it will get:
0 is a
1 is b
2 is c

And I wonder why 3 is d doesn't show up??

A: From the PHP manual:

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

A:

$arraya = array(a,b,c);
foreach($arraya as $key=>$value)
{
    if($value == b)
    {
        $d = 'd';
        array_push($arraya, $d);
        //print_r($arraya);    //$arraya now becomes array(a,b,c,d)
    }
    print_r($arraya);
    echo $key.' is '.$value."\n";
}

you will need to print the whole array not the individual elements one by one.
you will get your result only when you print $arraya

if $arraya had 'd' already in it then it would have printed easily.

A: it's the same reason that the else in the following statement will not be executed...
int a = 1;
if(a == 1){
   a = 0;
}
else{
   //print something;
}

your foreach deals with an array as it is when it is evaluated by the foreach clause.


text:
Q: What is the graph of partial derivative, or how do I understand it intuitively? Consider the graph of $f(x,y) = \sqrt{xy}$. Each coloured line depicts the curve $f(x,y) = k$ for different values of $k \in \mathbb{R}$.

The derivative is thought as the tangent. How do I think of the partial derivatives $\frac{\delta f}{\delta x}$ and $\frac{\delta f}{\delta y}$ in the graph?

A: The partial derivatives tell us how the function changes when only one variable is changed. For example, $\frac{\partial f}{\partial x}$ says how the value of $f$ will change if we increase $x$.
We can make sense of that in your graph. We fix a $y$ value and look at what happens as we move to the right along the $x$ axis. We can see that at $y=4$, $\frac{\partial f}{\partial x}$ is greater than at $y=2$ because the $k$ lines are closer together,


text:
Q: Files system become suddently read only; how to debug this? My ext-4 root and home filesystem became suddently read-only. How can I find out what was the reason for this?
The system is ubuntu 16.04 with systemd (installed on an ssd), where root and home partition are encrypted with dm-crypt and formatted with an ext-4 fs.
Edit Just after I wrote this post the system crashed again (two times) with a slightly blinking black/colored screen. Now it seems to work again.
The /etc/fstab contains for the root partition the mount option errors=remount-ro
The smartctl -a /dev/sda gives
smartctl -a /dev/sda
smartctl 6.5 2016-01-24 r4214 [x86_64-linux-4.4.0-21-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Device Model:     SAMSUNG MZ7PC256HAFU-000L7
Serial Number:    S0Y5NSAC602442
Firmware Version: CXM72L1Q
User Capacity:    256,060,514,304 bytes [256 GB]
Sector Size:      512 bytes logical/physical
Rotation Rate:    Solid State Device
Device is:        Not in smartctl database [for details use: -P showall]
ATA Version is:   ATA8-ACS T13/1699-D revision 4c
SATA Version is:  SATA 3.0, 6.0 Gb/s (current: 6.0 Gb/s)
Local Time is:    Mon May 23 17:07:40 2016 UTC
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x02) Offline data collection activity
                    was completed without error.
                    Auto Offline Data Collection: Disabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        ( 1020) seconds.
Offline data collection
capabilities:            (0x5b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    No Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   2) minutes.
Extended self-test routine
recommended polling time:    (  17) minutes.

SMART Attributes Data Structure revision number: 1
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  9 Power_On_Hours          0x0032   098   098   000    Old_age   Always       -       6093
 12 Power_Cycle_Count       0x0032   097   097   000    Old_age   Always       -       2810
175 Program_Fail_Count_Chip 0x0032   100   100   010    Old_age   Always       -       0
176 Erase_Fail_Count_Chip   0x0032   100   100   010    Old_age   Always       -       0
177 Wear_Leveling_Count     0x0013   095   095   017    Pre-fail  Always       -       169
178 Used_Rsvd_Blk_Cnt_Chip  0x0013   094   094   010    Pre-fail  Always       -       230
179 Used_Rsvd_Blk_Cnt_Tot   0x0013   094   094   010    Pre-fail  Always       -       450
180 Unused_Rsvd_Blk_Cnt_Tot 0x0013   094   094   010    Pre-fail  Always       -       7614
181 Program_Fail_Cnt_Total  0x0032   100   100   010    Old_age   Always       -       0
182 Erase_Fail_Count_Total  0x0032   100   100   010    Old_age   Always       -       0
183 Runtime_Bad_Block       0x0013   100   100   010    Pre-fail  Always       -       0
184 End-to-End_Error        0x0033   100   100   097    Pre-fail  Always       -       0
187 Reported_Uncorrect      0x0032   100   100   000    Old_age   Always       -       0
190 Airflow_Temperature_Cel 0x0032   066   042   000    Old_age   Always       -       34
195 Hardware_ECC_Recovered  0x001a   200   200   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0030   100   100   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x003e   253   253   000    Old_age   Always       -       1
233 Media_Wearout_Indicator 0x003a   200   200   000    Old_age   Always       -       0
234 Unknown_Attribute       0x0012   100   100   000    Old_age   Always       -       0
235 Unknown_Attribute       0x0012   099   099   000    Old_age   Always       -       48
236 Unknown_Attribute       0x0012   099   099   000    Old_age   Always       -       48
237 Unknown_Attribute       0x0012   099   099   000    Old_age   Always       -       169
238 Unknown_Attribute       0x0012   099   099   000    Old_age   Always       -       450

SMART Error Log Version: 1
No Errors Logged

SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Extended offline    Completed without error       00%      6092         -

SMART Selective self-test log data structure revision number 1
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Not_testing
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.

A: Some Linux systems will mount partitions as read-only if they were not cleanly unmounted and the system thinks that the appropriate flavor of fsck should be run on it before normal usage.
Check your logs or dmesg to find out if this is the case

A: As suggested by an earlier comment, start your "debugging" with dmesg rather than digging through SMART data. It's very likely you will get clues there (SATA/SAS/SCSI/whatever you use bus errors or read/write errors). It will also tell you which device/partition is at fault.
As suggested earlier, the issue may be a "soft" issue, such as an uncleanly unmounted filesystem (e.g. due to a power failure), or it could be a hardware issue, like a dying or malfunctioning hard drive/SSD. dmesg will show clues in both cases.


text:
Q: Is there a way to find out if a script's output is being passed to eval? I'm trying to find out if a program/script's output is being passed to eval, especially in bash scripts.
For example, can I distinguish:
$ ./program.sh

from
$ eval "$(./program.sh)"

within the program.sh? The latter would print the environment variables to be evaluated whereas the first one would not.
This would save me from developing a ./program.sh print-env for passing to eval.
On the other hand, I can see that having this possible potentially makes it possible to write malicious software that runs differently when it's output is passed to eval. Thoughts?

A: In:
eval "$(./program.sh)"

The shell would run ./program.sh with its stdout redirected to a pipe, and at the other end of the pipe would read that output in memory. And then, once ./program/sh is gone (causing eof to be seen on that pipe and the subsequent wait() done by most shell on the process to return), that saved content, minus the trailing newline character would be passed to eval.
So for ./program.sh to detect that situation, it would need to:

*

*detect that its stdout is a pipe. That's easy. On Linux, that could be with [ -p /dev/stdout ].

*that it's a shell process that is reading at the other end of that pipe. That becomes more complicated. On Linux with a recent lsof, you could look in the output of lsof +E -Fca -ap "$$" -d 1 for a process whose name ends with sh that has the pipe open for reading on a fd above 10.

*Then you would need to determine that that shell process is currently interpreting a eval something command line. For that, you'd probably need to attach a debugger to that shell and understand the internal data structures of that specific shell to see what command it is actually running.

In short you can't. But maybe you can be content with giving a different output when the output goes to a tty and when not, which should just be a matter of:
if [ -t 1 ]; then
  echo output for tty
else
  echo output for something else
fi


text:
Q: ASP.NET Ajax Control Toolkit: Custom toolbar button There is HtmlEditorExtender Control in Ajax Control Toolkit and there is some problem with it :)
What if I want to add my own button in Toolbar? How it can be done?
For example, I want to add the button which will insert a code snippet (and hightlight it) or add the button which will call a dialog window in browser then make async image upload and then insert this image?

A: you don't have much option I guess in HtmlEditorExtender.
Alternatively, try using these:

*

*FreetextBox

*obout ASP.NET HTML Editor


text:
Q: Not able to load static file CSS and JS thru pyBottle? Always getting 404 while trying to load static file using Bottle. I have referred stack overflow question and Google group chat but nothing is helping me to correct my problem. Please help me.. spent lot of time in this...
Tuts
   main.py
   static/
     bootstarp.css
   views/
     index.tpl

main.py code
import bottle
from bottle import Bottle
from os.path import basename,abspath, dirname, join

app = bottle.default_app()

appPath = dirname(abspath(''))
print appPath

@bottle.route('/')
def index():
    return bottle.template('index', dict(title=appPath,get_url=app.get_url))

@bottle.route('/static/:filename#.*#', name='css')
def server_static(filename):
    return bottle.static_file(filename, root=join(appPath,'static'))

bottle.debug(True)
bottle.run(host='localhost', port=8082,reloader=True)

**Template:**

<link href="{{ get_url('css', filename='bootstrap.css') }}" rel="stylesheet" media="screen">

A: Add
from bottle import static_file

at top. Then just use static_file(..., ...) is fine:
@bottle.route('/static/:filename#.*#', name='css')
def server_static(filename):
    return static_file(filename, root=join(appPath,'static'))


text:
Q: How to handle JavaScript dialog popup in WebView I'm trying to figure out how i can handle Javascript pop's in a webview, I have a WebView that is viewing a admin screen of a device on my network. Similar to a router, It has a administration section that then prompts a dialog box with a Username and Pswd field, However in my WebView i get no popup and instead get a 401 Error.
Great example of handling the dialog popup box is in Dolphin browser, they have provided a custom dialog with the two username and password fields.
I believe the below code is what i need to handle the Javascript for the pop up, however i need to create ad username and password dialog that will input the string's that are needed by the webpage.
Any idea's, recommendations, source code, is really appreciated. Thanks,
  public boolean onJsAlert(WebView view, String url, String message, final JsResult result)
        {
            new AlertDialog.Builder(Mosembro.this)
                .setTitle("javaScript dialog")
                .setMessage(message)
                .setPositiveButton(android.R.string.ok,
                        new AlertDialog.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int which)
                            {
                                result.confirm();
                            }
                        })
                .setCancelable(false)
                .create()
                .show();

            return true;
        };

A: Take a look at this SO post.
Apparently WebView can't get the HTTP response.  By creating your own custom WebViewClient class, you can 'intercept' the HTTP header and pull the response code.


text:
Q: Databinding working, but output window states databinding error I have a ComboBox which is bound to an ObservableCollection on my viewmodel. The type of objects in this collection are LanguageItem objects. I have a DataTemplate inside the ComboBox's ItemTemplate to customize the UI.
In here, I have a StackPanel that has a couple of controls. These controls bind to some properties within the LanguageItem object. Everything is working correctly.
This is where the error starts. I have two styles, one on the StackPanel and one on a TextBlock. These only contain some triggers to change some colours based on the value of ComboBoxItem.IsHighlighted. Two DataTriggers on each, one for true, and one for false.
Now, since the DataContext for each ComboBoxItem will be one of my LanguageItem objects, to get to the IsHighlighted property I use a RelativeSource for the binding in my data triggers. Here's an example:
<DataTrigger Value="True"
             Binding="{Binding Path=IsHighlighted,
                               RelativeSource={RelativeSource FindAncestor,
                                               AncestorType={x:Type ComboBoxItem}}}">

When I run my application, this does work and the colours are set correctly when I mouse-over different items in the ComboBox. But in the output window on Visual Studio, I can see the databinding errors logged. Here's an example:
System.Windows.Data Error: 4 :
Cannot find source for binding with reference 'RelativeSource FindAncestor,
AncestorType='System.Windows.Controls.ComboBoxItem', AncestorLevel='1''.
BindingExpression:Path=IsHighlighted; DataItem=null;
target element is 'TextBlock' (Name='');
target property is 'NoTarget' (type 'Object')

I don't understand why this error is being logged if the bindings are working. At first I was sceptial that these error messages were refering to these bindings. I commented out the two styles, and the errors disappeared. But so did the changing of colours on mouse over, as expected.
Am I lacking understanding of something, or is this a bug in VS? For reference, here's a complete style. I'm targetting .NET 3.0 using VS 2012 with Update 4.
<DataTemplate DataType="{x:Type model:LanguageItem}">

    ...

    <StackPanel.Style>
        <Style TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                <DataTrigger Value="True"
                             Binding="{Binding Path=IsHighlighted,
                                               RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBoxItem}}}">
                    <Setter Property="Background" Value="{StaticResource TitleBrush}"/>
                </DataTrigger>
                <DataTrigger Value="False"
                    Binding="{Binding Path=IsHighlighted,
                                      RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBoxItem}}}">
                    <Setter Property="Background" Value="{StaticResource BackgroundBrush}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>

    ...

</DataTemplate>

A: I'm guessing the DataContext becomes out of scope at some point. If the DataBinding works, this shouldn't be an issue.
Though, to get rid of the error, you can set a FallbackValue when it can't find it:
<StackPanel.Style>
    <Style TargetType="{x:Type StackPanel}">
        <Setter Property="Background" Value="{StaticResource BackgroundBrush}"/>
        <Style.Triggers>
            <DataTrigger Value="True"
                         Binding="{Binding Path=IsHighlighted, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBoxItem}}, FallbackValue=False}">
                <Setter Property="Background" Value="{StaticResource TitleBrush}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</StackPanel.Style>

Also, I would like to note that you do not need to satisfy both True/False conditions for a 2-state DataTrigger. Only having one condition, while setting the 'default' condition is good enough.


text:
Q: Laser beam max distance at 30000 ft would the max  the distance covered by a green pointer at 30000 feet above ground level be much greater than same laser pointed on earth surface? for example if the manufacturer claims max distance of one KM on ground level would the same laser reach 10 KM at 30000 feet above ground (because of thinner air lower impurities etc)?

A: The range might be greater because there may be less absorption by the air and the particles in the air but the spreading out of the laser beam because it is not parallel would probably have a large effect so reducing your estimated distance by a considerable amount.
If you increase the distance by a factor of ten then the light will be spread over an area $10^2=100$ times as large.
Shine a laser pointer over a distance of 10 m and then 100 m to observe how the width of the beam increases with distance.
This article on lunar laser ranging might be of interest in that it shows that even with the laser used to make these measurements there is beam spreading.


text:
Q: Accessing com.google.mms.pdu and com.android.mms So I am trying to access various class files in these package names, I have downloaded the following library
http://grepcode.com/snapshot/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/
If you look on the page and browse through the various files you will clearly see com.google.mms.pdu and the many classes inside.  However, after downloading the jar file and adding it to my project there is no com.google and it is driving me insane, I have downloaded all the older packages on this page and have found that older releases like 1.5_r5 do have this package inside them but the newer releases don't! Has anyone had any problem with this?
I am trying to follow this tutorial
http://forum.xda-developers.com/showthread.php?t=2222703
with the older library I can add most of the required packages but I am still missing com.android.mms.transaction.HttpUtils.java none of these libraries have any package beginning with com.android.mms
UPDATE
I have found that com.android.mms.transaction is in the 4.4.2 package even though the webpage does not list it.  However when I try to use HttpUtils.httpConection intellisense does not recognize the method even though the library shows it.
The Ideal solution would be to find a library that has the proper packages I am looking for without giving me these messed up errors


text:
Q: defaultValue is pulling the last value in React If i click on a particular ToDos edit button, its value should be defaulted inside the textarea but everytime the last ToDo  is defaulting, can somebody please help, whether using ref is a right choice or something else, then where i m wrong what i'm suppose to do ?
 handleEdit() {
  e.preventDefault();
  .....

}

renderDisplay() {
    return(

       {
        this.props.listArr.map((list,i) => {
           return(

{list}

                 <button className="btn btn-primary btn-xs glyphicon glyphicon-pencil"
                         onClick={this.handleEdit.bind(this)}
                 />

           )})
       }

    );
  }

  renderForm() {
   return(

        <textarea className="form-control" defaultValue={this.refs.newText.innerText} rows="1" cols="100" style={{width: 500}}/>

    )
  }

  render() {
      if(this.state.editing) {
        return this.renderForm();
      }else {
        return this.renderDisplay();
      }
    }
}

A: First of all you are using an old ref API. You should use this one, where you set the ref to the instance of the class using this with a callback.
<input ref={ref => {this.myInput = ref}} />

And then you can access its value by just referring to this.myInput .
As for your "bug", keep in mind that you are looping over and overriding the ref. so the last ref assignment would be the last item in the array.
 this.props.listArr.map((list,i) => {
           return(

{list}

There will always be 1 newText ref and it will always be the last item in the array.
You should render different ref names according to the item id and then pass the id of the item to the renderForm so it can access the relevant ref.
With that said, i really recommend to extract the todo to a different component as well as the form. I don't see a valid reason to use refs in this case.
Edit
As a follow-up to your comment, here is a small example of how you would use components instead of refs in order to get information from the child like values etc..

class Todo extends React.Component {
  onClick = () => {
    const { todoId, onClick } = this.props;
    onClick(todoId);
  }

  render() {
    const { value, complete } = this.props;
    return (

        {value}

    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: [
        { id: '1', value: 'to do this', complete: false },
        { id: '2', value: 'todo that', complete: true },
        { id: '3', value: 'will do it later', complete: false }]
    }
  }

  toggleTodo = (todoId) => {
    const { todos } = this.state;
    const nextState = todos.map(todo => {
      if (todo.id !== todoId) return todo;
      return {
        ...todo,
        complete: !todo.complete
      }
    });
    this.setState({ todos: nextState });
  }

  render() {
    const { todos } = this.state;
    return (

        {
          todos.map((todo) => {
            return (
              <Todo
                complete={todo.complete}
                key={todo.id}
                todoId={todo.id}
                value={todo.value}
                onClick={this.toggleTodo}
              />
            )
          })
        }

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));


text:
Q: Google Map Error message in IE I have a Tab containing google map and other informations about the location.
If I switch between the Tabs then in IE i have always a Javascript Error message

"Invalid Argument at line 30"

If i remove the Map from the Tab then I don't get this error message.
I have tried some solutions like
setting style for the DIV contain googlemap like
"visibility:hidden;height:0px"

or
"position:absolute;left:-5000px"

but i patch this error.
Any suggestion?


text:
Q: React state update error whenever i open someone's image, and image not redering too. How can I fix this error I was creating a snapchat like web app and this is the chats page where all different snaps were commoing from different users, but when I open their snap their image is not rendering and I'm always ending with this error -
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at Chats
import "./Chats.css";
import { Avatar } from "@material-ui/core";
import SearchIcon from "@material-ui/icons/Search";
import ChatBubbleIcon from "@material-ui/icons/ChatBubble";
import { auth, db } from "./firebase";
import Chat from "./Chat";
import { useDispatch, useSelector } from "react-redux";
import { selectUser } from "./features/appSlice";
import RadioButtonUncheckedIcon from "@material-ui/icons/RadioButtonUnchecked";
import { useHistory } from "react-router";
import { resetCameraImage } from "./features/cameraSlice";

const Chats = () => {
  const [posts, setPosts] = useState([]);
  const user = useSelector(selectUser);
  const dispatch = useDispatch();
  const history = useHistory();

  useEffect(() => {
    db.collection("posts")
      .orderBy("timestamp", "desc")
      .onSnapshot((snapshot) =>
        setPosts(
          snapshot?.docs.map((doc) => ({
            id: doc.id,
            data: doc.data(),
          }))
        )
      );
  }, []);

  const takeSnap = () => {
    dispatch(resetCameraImage());
    history.pushState("/");
  };

  return (

        <Avatar
          className="chats__avatar"
          src={user.propilePic}
          onClick={() => auth.signOut()}
        />

          <SearchIcon className="chats__searchIcon" />
          <input placeholder="Friends" type="text" />

        <ChatBubbleIcon className="chats__chatIcon" />

        {posts.map(
          ({
            id,
            data: { profilePic, username, timestamp, imageUrl, read },
          }) => (
            <Chat
              key={id}
              id={id}
              profilePic={profilePic}
              username={username}
              timestamp={timestamp}
              imageUrl={imageUrl}
              read={read}
            />
          )
        )}

      <RadioButtonUncheckedIcon
        className="chats_takePicIcon"
        onClick={takeSnap}
        fontSize="large"
      />

  );
};

export default Chats;```

A: The issue is related to the fact that onSnapshot function subscribes the component to real-time Firebase updates, even if the component is unmounted, so you have to return a unsubscription function on your useEffect like this:
useEffect(() => {
  const unsubscribe = db.collection("posts")
    .orderBy("timestamp", "desc")
    .onSnapshot((snapshot) =>
      setPosts(
        snapshot?.docs.map((doc) => ({
          id: doc.id,
          data: doc.data(),
        }))
      )
    );

  return () => unsubscribe();
}, []);


text:
Q: Unclosed socket due to spawn child processes using multiprocessing I don't really understand what's going on with http requests.
When I started child processes and uvicorn timeout_keep_alive
timed out, I tried hitting "stop" in the browser and got infinite loading and no HTTP connection log. But if I try to click other buttons or refresh the page, it works and I get two responses.
Netstat shows that socket bind on port 60862 is opened, but uvicorn log:
TRACE:    127.0.0.1:60862 - HTTP connection lost.
import multiprocessing
import os
import time

import uvicorn
from fastapi import FastAPI

app = FastAPI()
processes = []

def keep_alive_process():
    while True:
        print(f"process {os.getpid()} is alive")
        time.sleep(1)

@app.post("/start")
async def start_processes():

    for i in range(4):
        process = multiprocessing.Process(target=keep_alive_process,
                                          args=())
        processes.append(process)
        process.start()

    return {'status': 'started'}

@app.post("/stop")
async def stop_processes():

    for process in processes:
        process.kill()
    processes.clear()

    return {'status': 'stopped'}

if __name__ == '__main__':
    uvicorn.run('main:app', timeout_keep_alive=10, log_level='trace')

TRACE:    127.0.0.1:60862 - HTTP connection made
TRACE:    127.0.0.1:60862 - ASGI [2] Started scope={'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'server': ('127.0.0.1', 8010), 'client': ('127.0.0.1', 60862), 'scheme': 'http', 'root_path': '', 'headers': '<...>', 'method': 'POST', 'path': '/start', 'raw_path': b'/start', 'query_string': b''}
TRACE:    127.0.0.1:60862 - ASGI [2] Send {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}
TRACE:    127.0.0.1:60862 - ASGI [2] Send {'type': 'http.response.body', 'body': '<20 bytes>'}
TRACE:    127.0.0.1:60862 - ASGI [2] Completed
process 63912 is alive
process 63913 is alive
process 63914 is alive
process 63915 is alive
INFO:     127.0.0.1:60862 - "POST /start HTTP/1.1" 200 OK
process 63912 is alive
process 63913 is alive
TRACE:    127.0.0.1:60862 - HTTP connection lost

....

process 63912 is alive
INFO:     127.0.0.1:59092 - "POST /stop HTTP/1.1" 200 OK
INFO:     127.0.0.1:59092 - "POST /stop HTTP/1.1" 200 OK
TRACE:    127.0.0.1:59092 - HTTP connection made
TRACE:    127.0.0.1:59092 - ASGI [3] Started scope={'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'server': ('127.0.0.1', 8010), 'client': ('127.0.0.1', 59092), 'scheme': 'http', 'root_path': '', 'headers': '<...>', 'method': 'POST', 'path': '/stop', 'raw_path': b'/stop', 'query_string': b''}
TRACE:    127.0.0.1:59092 - ASGI [3] Send {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}
TRACE:    127.0.0.1:59092 - ASGI [3] Send {'type': 'http.response.body', 'body': '<20 bytes>'}
TRACE:    127.0.0.1:59092 - ASGI [3] Completed
TRACE:    127.0.0.1:59092 - ASGI [4] Started scope={'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'server': ('127.0.0.1', 8010), 'client': ('127.0.0.1', 59092), 'scheme': 'http', 'root_path': '', 'headers': '<...>', 'method': 'POST', 'path': '/stop', 'raw_path': b'/stop', 'query_string': b''}
TRACE:    127.0.0.1:59092 - ASGI [4] Send {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}
TRACE:    127.0.0.1:59092 - ASGI [4] Send {'type': 'http.response.body', 'body': '<20 bytes>'}
TRACE:    127.0.0.1:59092 - ASGI [4] Completed
TRACE:    127.0.0.1:59092 - HTTP connection lost

Swagger image

A:
The multiprocessing module uses the process forking technique, in which file and socket descriptors are inherited by child processes as usual. Therefore, the child process will use the same connected socket as the parent process.

See https://mvblog.ru/zavershenie-dochernix-processov.html

A: So my only decision (WORKAROUND) is to set timeout_keep_alive uvicorn param onto zero and using BackgroundTask from Fastapi.
The socket closes immediately after sending the response, but processes spawns after sending response.


text:
Q: Adding element to MySQL database from php code what's wrong here?:) I want to put data to database (I'm pretty sure that connection to db works).
$host="localhost";
$username="root";
$password="root";
$db_name="db";
$tbl_name="changes";

mysql_connect("$host","$username","$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$when=$_POST['when'];
$bad_teacher=$_POST['bad_teacher'];
$teacher=$_POST['teacher'];
$hour=$_POST['hour'];
$class=$_POST['class'];

$sql="INSERT INTO $tbl_name (when, bad_teacher, teacher, hour, class) VALUES (`$when`,`$bad_teacher`,`$teacher`,`$hour`,`$class`)";
mysql_query($sql);

?>

A: WHEN is mysql reserved keyword  you need to use bactiks arround your column names matched with
Rererved Keywords,and why you have used bacticks arround the values.
$sql="INSERT INTO
$tbl_name (`when`, `bad_teacher`, `teacher`, `hour`, `class`)
VALUES
('".$when."','".$bad_teacher."','".$teacher."','".$hour."','".$class."')";

Also mysql* family is depreiciated you need to move on with pdo or aleast with mysqli* family.
Pdo demo
$dbhost     = "localhost";
$dbname     = "dbname";
$dbuser     = "user";
$dbpass     = "pass";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// query
$sql = "INSERT INTO books (`when`, `bad_teacher`, `teacher`, `hour`, `class`)
 VALUES (:when,:bad_teacher,:teacher,:hour,:class)";
$q = $conn->prepare($sql);
$q-> bindParam(':when', $when);
$q-> bindParam(':bad_teacher',$bad_teacher);
$q-> bindParam(':teacher', $teacher);
$q-> bindParam(':hour', $hour);
$q-> bindParam(':class', $class);
$q->execute();

Pdo Reference

A: //connection.php

$dsn  = 'mysql:host=localhost;dbname=db';
$user = 'root';
$pass = 'root';
$option = array(
    PDO::MYSQL_ATTR_INIT_COMMAND =>'SET NAMES utf8',
);

try {
    $con = new PDO($dsn, $user, $pass,$option);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e) {
    echo 'Failed To Connect'.$e->getMessage();
}

//INSERT

$sqli="INSERT INTO
$tbl_name (`when`, `bad_teacher`, `teacher`, `hour`, `class`)
VALUES
('".$when."','".$bad_teacher."','".$teacher."','".$hour."','".$class."')";


text:
Q: How to force Word to do a SaveAs on generated document We have a system where we are generating a report as a Word document (using RDLC).
The report is created in a temporary directory, and then Word is launched to display it to the user.
Word is launched, and the report loaded by:
_wordApplication = (Word.Application)Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"));
object tempFileNameObj = documentPath;
_wordDocument = _wordApplication.Documents.Open(ref tempFileNameObj);

What I want is to convince Word that this is really a newly created, unsaved file, so it will give the user a SaveAs dialog when they save it (rather than save back to the temporary location).
Ideally, I would like to be able to specify the target directory, and offer a default name.
While the Word is being launched, I can do what I like using Automation, but after Word has been launched, my application will be disconnected from Word, and I would prefer not to leave any macros floating around in the document.

A: You can rename your .doc file to .dot (Word Template) and if you launch it afterwards, it will create a new File looking exactely like your .doc

A: If you're not using a macro I believe that the only way to archieve this would be to save the file that they will download be a read-only or user defined template file this way if they wan't to make changes to it they wil have to save it with another name in their computer to save the changes made. If you can use a macro you can archieve more options and even force a save as dialog when the document is opened or when it's closed. I hope this helps as I couldn't find any more information without using a macro.


text:
Q: Checking for Old RSS Items? I'm writing my own RSS app in Csharp, and I'm wondering what would be a good method for seeing previously fetched RSS items (so it only fetches the new ones)? Currently, my app just refetches all the RSS Items and transfers them to Email one by one (individual emails for each Item).  Do an MD5 hash of the title and compare it to all the other MD5 hashes (stored in a file)? I'm short on a good idea.
Edit: It can't be related to the Date field in the RSS item, as a lot of RSS feeds don't have a pubDate field.

A: I haven't explored RSS that much (and know that different sites do various strange things), but I'd try something like: Use the "guid" if it's there, and if not, use the "link".  You could hash it to either save space, or add some privacy - but I'd probably start out not hashing them to make debugging easier, and hasing later when I saw that the algorithm was working, and if there were a need for it.
P.S.  The "link" alone may be good enough for most sites (and probably easier to implement), since if this were repeated, it would effectively be different articals pointing to the same link, which I suspect is not done too much.  But again, I don't speak here from experience.