text:
Q: Getting parameter from user and using it in post method @RequestMapping(value="/thyroidReport",method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/JSON")
   public ArrayList<thyroidMedicalReport> getThyroidDetails(@RequestParam("id") String personId) throws IOException{
      return thyroidReportHandler.getDetails(personId);
   }

The above code is to POST the thyroid report details in JSON format. However, i need to pick up the user ID from my website (PHP code) for which is need a GET method too with the request for the ID.
The POST call should be made in the format :
    http://localhost:8090/thyroidReport?id=123
I am getting the following compilation error:
The method getDetails(String) in the type thyroidReportHandler is not applicable for the arguments

A: If your service thyroidReportHandler works, you could do it this way:
   @RequestMapping(value="/thyroidReport", method = RequestMethod.GET)
   public ArrayList<thyroidMedicalReport>getThyroidDetails(@RequestParam(value="id") String personId) throws IOException{
      return thyroidReportHandler.getDetails(personId);
   }

You don't need to perform two HTTP calls, you can provide all your information in the GET.
By the way, I would make your class thyroidMedicalReport start by a uppercase letter!


text:
Q: Can't access Port 9200 Remotely Have just started using elastic search 5.4.0, first i have  installed it on Mac(local) and then in server.
In Mac when i am running in browser as  'http://localhost:9200' it is showing me output :

{
  "name" : "Node_1",
  "cluster_name" : "bhujang_bipl",
  "cluster_uuid" : "N75mGOiSQCufpBl_2B7jSg",
  "version" : {
    "number" : "5.4.0",
    "build_hash" : "780f8c4",
    "build_date" : "2017-04-28T17:43:27.229Z",
    "build_snapshot" : false,
    "lucene_version" : "6.5.0"
  },
  "tagline" : "You Know, for Search"
}

which means i am connected to 9200 which is elasticsaerch.
But when i am running it on server by http://192.168.1.126:9200 , then it is not getting connected and shows me an output as :page not found !!
I disabled firewall on both the server and client as solutions I got from internet but couldn't get it working.
My elasticsaerch.yml file is

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#network.host:192.168.1.126
#
# Set a custom port for HTTP:
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
#The default list of hosts is ["127.0.0.1", "[::1]","103.240.195.45","103.240.195.45"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes: 3
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true

Can anyone help me with what can be the best possible mistake from my side ?

A: From the link
https://github.com/elastic/elasticsearch/issues/19987
add this two line in the yml file
transport.host: localhost
network.host: 192.168.1.126

A: It doesn't work for me remotely, it's hosted on Azure windows 2019 server. I have opened port ranges 9200-9300
transport.host: localhost
transport.tcp.port: 9300
http.port: 9200
#network.host: 0.0.0.0
network.host: 192.168.1.126
http.host: 0.0.0.0
http.cors.enabled: true
http.cors.allow-origin : "*"
http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers : X-Requested-With,X-Auth-Token,content-Type,content-Length

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I symbolicate without archive but have .dsym files? I have to symbolicate a crash report given to me, however I didn't create the initial archive that was sent to Apple. I do, however, have the .dsym files. Is there a way I can symbolicate the crash file?
Thanks.

A: This is assuming Xcode 8.2.1 is installed as Xcode.app
Create a new folder on your desktop and call it symbolication

Put the .dsym files into the symbolication folder
download the crash report
(I used CustomerID.crash as the format of these files)
In the terminal, type:
cp /Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash  ~/desktop/symbolication/symbolicgtecrash
cd ~/desktop/symbolication
export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"

Then for each file to symbolicate, type:
./symbolicatecrash CustomerID.crash > CustomerID_symbolicated.crash

(where CustomerID is the customer id used when saving the crash report)

A: Here is another way to get the crash logs:-
copy your app dSYM file path using atos command with crash address and execute on terminal:-
Here is the command:-
atos -arch arm64 -o ~/Documents/yourApp.app.dSYM/Contents/Resources/DWARF/yourApp yourExceptionAddress
eg:-
yourExceptionAddress = 0x100048000


text:
Q: Starting a new screen session to run a script that starts another one I'm trying to make a program using node.js that needs to be able to pull new updates and restart it self. For that purpose, I've made an auto.sh script that has this code in it:
screen -S GNode -X quit
screen -dmS GNode -L node server

Unfortunately, when I try to run that script from node, what appears to happen is that the first line is ran and my node application shuts down (as it's being run in that session) but then the second line doesn't get executed, which is a bummer.
What I've ended up doing is having ANOTHER screen session called ScriptRunner that I run with the command
screen -dmS ScriptRunner sh auto.sh

For some reason though, when I run that command and then check for open screen sessions, there are none. So the first line again gets executed but the second one doesn't. This doesn't appear to be a problem with my node program because when I run that last command directly in the terminal, the same thing happens.
Does anyone know what could possibly be wrong? I'm very new to Linux and terminal stuff.

A: Try to add a delay before running the next session:
screen -S GNode -X quit
sleep 10s  ## You can adjust this value.
screen -dmS GNode -L node server


text:
Q: Is there a better way to form this code example? I'm new to rxjs and using redux-observable.  The short of it is that I need to make a couple promise requests when i get a connection then output the results.  I'm wondering if there is a way to join this into a single map at the end and not have to call store.dispatch multiple times and have the retry work for each individual read.  Thanks ahead of time for your comments.
export const handleBleConnectionSuccess = (action$,store,{bleCommunicator}) =>
  action$.ofType(c.BLE_CONNECTION_SUCCESS)
    .do((a)=>{
      Observable.fromPromise(bleCommunicator.readCharacteristic(a.device.id,gattInfo.uuid,gattInfo.firmwareRevision.uuid))
        .do((value)=>store.dispatch({type:c.DEVICE_FIRMWARE_VERSION,device:{...a.device,firmwareVersion:value}}))
        .retry(3);

      Observable.fromPromise(bleCommunicator.readCharacteristic(a.device.id,gattInfo.uuid,gattInfo.modelNumber.uuid))
        .do(value=>store.dispatch({type:c.DEVICE_MODEL_NUMBER,device:{...a.device,modelNumber:value}}))
        .retry(3);
    })
    .mapTo({type:'DEVICE_INFORMATION_REQUESTED'});

A:
I'm wondering if there is a way to join this into a single map at the end and not have to call store.dispatch multiple times and have the retry work for each individual read

Yes, there is a better way, and it's possible to do what you want.
From the syntax, I'm guessing that you use ngrx (effects) (and not redux-observable).
So with ngrx/effects you could do it like that:
export const handleBleConnectionSuccess = (
  action$,
  store,
  { bleCommunicator }
) =>
  action$.ofType(c.BLE_CONNECTION_SUCCESS).switchMap(a => {
    const readCharacteristic = deviceOrFirmwareUuid =>
      bleCommunicator.readCharacteristic(a.device.id, gattInfo.uuid, deviceOrFirmwareUuid);

    return Observable.merge(
      readCharacteristic(gattInfo.firmwareRevision.uuid)
        .map(value => ({
          type: c.DEVICE_FIRMWARE_VERSION,
          device: { ...a.device, firmwareVersion: value },
        }))
        .retry(3),

      readCharacteristic(gattInfo.modelNumber.uuid)
        .map(value => ({
          type: c.DEVICE_MODEL_NUMBER,
          device: { ...a.device, modelNumber: value },
        }))
        .retry(3),

      { type: 'DEVICE_INFORMATION_REQUESTED' }
    );
  });


text:
Q: How to draw a shadow on a pic I have the following example and I'm wondering why this is not working:
\documentclass[tikz]{standalone}

\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\usetikzlibrary{quotes}
\usetikzlibrary{shadows}

\RequirePackage{luatex85}

\begin{document}
\newcommand\unit{1.2cm}
\begin{tikzpicture}[
  pics/limiter/.style={
    code={
      \draw[black!50,very thin] (-0.45*\unit,0) -- (0.45*\unit,0);
      \draw[black!50,very thin] (0,-0.45*\unit) -- (0,0.45*\unit);
      \draw (0.5*\unit,0.5*\unit) -- (0.5*\unit,-0.5*\unit) --
            (-0.5*\unit,-0.5*\unit) -- (-0.5*\unit,0.5*\unit) -- cycle;
      \draw (-0.4*\unit,-0.4*\unit) -- (-0.25*\unit,-0.4*\unit) --
            (0.25*\unit,0.4*\unit) -- (0.4*\unit,0.4*\unit);
      \coordinate (-north) at (0,0.5*\unit);
      \coordinate (-west) at (-0.5*\unit,0);
      \coordinate (-south) at (0,-0.5*\unit);
      \coordinate (-east) at (0.5*\unit,0);
    },
    drop shadow={shadow xshift=.3ex,shadow yshift=-.3ex}
  }
]
  \pic[fill=yellow!50] (lim) at(0,0) {limiter};
\end{tikzpicture}
\end{document}

It should look like this only with drop shadow

A: with standard node is simpler and more flexible (regarding node names, positioning etc) to draw a limiter. beside this, \pic seems not enable to use drop shadow options for paths.
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{shadows}

\begin{document}
\newcommand\unit{1.2cm}
    \begin{tikzpicture}[
limiter/.style = {shape=rectangle, draw,
                  fill=#1, drop shadow,
                  minimum size=\unit, outer sep=0mm,
    path picture={%
      \draw[black!50,very thin] (-0.45*\unit,0) -- (0.45*\unit,0);
      \draw[black!50,very thin] (0,-0.45*\unit) -- (0,0.45*\unit);
      \draw (-0.40*\unit,-0.4*\unit) -- (-0.25*\unit,-0.4*\unit) --
            ( 0.25*\unit, 0.4*\unit) -- ( 0.40*\unit, 0.4*\unit);
                },% end path picture
               },% end of limiter
limiter/.default = white
                ]
\node[limiter] (lim) at (0,0) {};
\node[limiter=yellow] (lim) at (2,0) {};
    \end{tikzpicture}
\end{document}


text:
Q: Multiple definition and header-only libraries I have a C program with several c and h files. I decided to make one part of the program 'header-only' so I moved the code from c to h. Now I'm getting multiples definition problems and I have no idea why. e.g.:
main.c includes utils.h
vector.c includes utils.h

I moved everything in utils.c to utils.h (and of course removed utils.c from the project). utils.h starts with
#ifndef UTILS_H_
#define UTILS_H_

// and end with:
#endif

To be sure my guard was unique I tried changing it (e.g.: UTILS718171_H_) but it doesn't work.
Still, the compiler complains:
/tmp/ccOE6i1l.o: In function `compare_int':
ivector.c:(.text+0x0): multiple definition of `compare_int'
/tmp/ccwjCVGi.o:main.c:(.text+0x660): first defined here
/tmp/ccOE6i1l.o: In function `compare_int2':
ivector.c:(.text+0x20): multiple definition of `compare_int2'
/tmp/ccwjCVGi.o:main.c:(.text+0x6e0): first defined here
/tmp/ccOE6i1l.o: In function `matrix_alloc':
ivector.c:(.text+0x40): multiple definition of `matrix_alloc'
/tmp/ccwjCVGi.o:main.c:(.text+0x0): first defined here
...

The problem might be something like: all c files are compiled and get their own version of the code and then at linkage it causes problem, but I have honestly no idea how to solve this problem.

A: You're violating the One-Definition-Rule. Each function must be defined precisely once, while you end up defining it in each translation unit.
You simply cannot do something like this:
// header.h
void foo() { }

// file1.c
#include "header.h"

// file2.c
#include "header.h"

The only real solution is to declare void foo(); in the header and define it once only (usually in a dedicated foo.c). The same goes for global variables, which should be declared as extern in the header and defined in the source file.
Include guards have nothing to do with this. They only serve to prevent recursive self-inclusion or redundant multiple inclusion within one translation unit.

A: If you indend for the utils.h functions to be "copied" into each place where it is used, just use static functions in the header. (static inline in C99)

A: If you define your variables inside your header file and include the header in several c files, you are bound to get multiple definitions error because you break the One definition rule(ODR), which states that there should be only one definition in one Translation Unit(header files + source file).
Solution is:
You should define the entities you get Multiple definition errors for only once.
For Functions:
Declare the function prototypes in header file(which you include in other source files) and define the function in one and only one source file.
For Global variables:
You declare the variable extern in header file(which you include in other source files) and then define the variable in one and only one source file.

A: You are missing the point of #ifndef _FOO_H / #define _FOO_H / #endif construct.  That only protects against multiple inclusions in ONE file. For example they protect against this:
foo.h:
  #ifndef _FOO_H
  #define _FOO_H

  /* some C stuff here */

  #endif /* _FOO_H */

foo.c:
   #include <foo.h>
   #include <bar.h>
   ...

bar.h:
   #include <foo.h>
   ...

note that foo.c and bar.h both include foo.h; here the #ifdef _FOO_H / #define _FOO_H / #endif protects against that double inclusion in foo.c ( the foo.h included in bar.h doesn't redefine stuff )
Now the next part.
Why would you move function implementation from utils.c to utils.h? Also why did you decide to make it "header-only" ?
You can, depending on whether your compiler supports static inline functions do this; but even then it's NOT recommended, as more than likely, it  will make your program unnecessarily bloated because chances are your util functions are quite complex and cannot be inlined anyways.
So change it back to utils.c and utils.h construct that you had before which, i presume, WAS working and enjoy the software.


text:
Q: netty4:How to listen on multiple ports on a java process I'm trying to listen for connections on two different ports
I start 2 Thread in a java main method,every Thread bind a port with netty4,but can't
  listener success!
this is my code,the port 3333 is ok,but 1234 is not ok,it looks like 3333 is blocking!
    public class ObjectServer
    {
private static final Logger logger = LoggerFactory.getLogger(ObjectServer.class);

private String ip;
private int port;

public ObjectServer(int port)
{
    this.port = port;
}

public void run(final ChannelInboundHandlerAdapter handler) throws Exception
{
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try
    {
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>()
        {
            @Override
            public void initChannel(SocketChannel ch) throws Exception
            {
                ch.pipeline().addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), handler);
            }
        });
        server.bind(port).sync().channel().closeFuture().sync();
    }
    catch (Exception e)
    {
        logger.error("开启监听失败!端口[" + port + "]", e);
        throw e;
    }
    finally
    {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

}
 public class SocketServer
{
private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);
private static final StringDecoder DECODER = new StringDecoder();
private static final StringEncoder ENCODER = new StringEncoder();
private int port;

public SocketServer(int port)
{
    this.port = port;
}

public void run(final ChannelInboundHandlerAdapter handler) throws Exception
{
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try
    {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>()
        {
            @Override
            public void initChannel(SocketChannel ch) throws Exception
            {
                ChannelPipeline pipeline = ch.pipeline();
                // Add the text line codec combination first,
                pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                // the encoder and decoder are static as these are
                // sharable
                pipeline.addLast("encoder", ENCODER);
                pipeline.addLast("decoder", DECODER);
                // and then business logic.
                pipeline.addLast("handler", handler);
            }
        });
        b.bind(port).sync().channel().closeFuture().sync();
    }
    catch (Exception e)
    {
        logger.error("开启监听失败!端口[" + port + "]", e);
        throw e;
    }
    finally
    {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

}
 public class Test
       {
    public static void main(String[] args) throws Exception
    {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread2.start();
        thread1.start();
        new SocketClient("192.168.16.52", 3333).run(new TestHandler4("test4"));
        new ObjectClient("192.168.16.52", 1234).run(new TestHandler3("test3"));
    }

    @Sharable
    static class TestHandler1 extends ChannelInboundHandlerAdapter
    {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
        {
            System.out.println("1234" + msg);
        }

    }

    static class Thread1 extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                new ObjectServer(1234).run(new TestHandler1());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    static class Thread2 extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                new SocketServer(3333).run(new TestHandler2());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    @Sharable
    static class TestHandler2 extends SimpleChannelInboundHandler<String>
    {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception
        {
            System.out.println("3333" + msg);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception
        {
            System.out.println("sssssssssssssssss");
        }
    }

    @Sharable
    static class TestHandler3 extends ChannelInboundHandlerAdapter
    {
        private String msg;

        public TestHandler3(String msg)
        {
            this.msg = msg;
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception
        {
            ctx.writeAndFlush(msg);
        }
    }

    @Sharable
    static class TestHandler4 extends SimpleChannelInboundHandler<String>
    {
        private String msg;

        public TestHandler4(String msg)
        {
            this.msg = msg;
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception
        {
            ctx.writeAndFlush(msg);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext arg0, String arg1)throws     Exception
        {

        }
    }
}

A: In your run() implementation, you do this:
server.bind(port).sync().channel().closeFuture().sync();

.. which will block until the server socket is closed.  Because you do not close the server socket, it will never return.  Therefore, only the first server socket will be bound.
What you probably want is just bind and return rather than waiting for the server sockets closed.


text:
Q: Save the current state of program and resume again from last saved point I have a script to download images from a link. Suppose the script gets terminated due to some reason then I want to save the point till which the images have been downloaded and resume again from the point last saved
I have made the download script and tried saving the state of the program using pickle till now
import pandas as pd
import requests as rq
import os,time,random,pickle
import csv
data=pd.read_csv("consensus_data.csv",usecols=["CaptureEventID","Species"])

z=data.loc[ data.Species.isin(['buffalo']), :]

df1=pd.DataFrame(z)

data_2=pd.read_csv("all_images.csv")

df2=pd.DataFrame(data_2)

df3=pd.merge(df1,df2,on='CaptureEventID')

p=df3.to_csv('animal_img_list.csv',index=False)

# you need to change the location below
data_final = pd.read_csv("animal_img_list.csv")
output=("/home/avnika/data_serengeti/url_op")

mylist = []

for i in range(0,100):
    x = random.randint(1,10)
    mylist.append(x)

print(mylist)

for y in range(len(mylist)):
    d=mylist[y]
    print(d)

file_name = data_final.URL_Info
print(len(file_name))
for file in file_name:
    image_url='https://snapshotserengeti.s3.msi.umn.edu/'+file
    f_name=os.path.split(image_url)[-1]
    print(f_name)
    r=rq.get(image_url)

    with open(output+"/"+f_name, 'wb') as f:
        f.write(r.content)
    time.sleep(d)

with open("/home/avnika/data_serengeti","wb") as fp:
    pickle.dump(r,fp)

with open("/home/avnika/data_serengeti","rb") as fp:
    pic_obj=pickle.load(fp)

Suppose i have to download 4000 images from a URL. I successfully downloaded 1000 images but due to some network issue my script crashed. So i want that when the script restarts then it should start downloading from image number 1001. Currently it starts fresh from image number 1 again if the script is restarted. How can i run my loop again after loading the pickle object?

A: There might be multiple solutions to this problem but this comes first in mind it will help you to solve this problem.
Approach :
It's very clear, the script starts to download from starting because it can't remember the index till where it has downloaded the last time.
To solve this issue we will create a text file which is having an integer 0 denoting to that up to this index file has been downloaded. And when the script runs it checks what is the integer value present in the text file. (It's like recalling the position). The value in the text file gets incremented with 1 if the file is downloaded successfully.
Code
An Example for understanding ::
Please See: I have manually created a text file with '0' in it earlier.
# Opening the text file
counter =  open('counter.txt',"r")

# Getting the position from where to start.Intially it's 0 later it will be updated
start = counter.read()
print("-->  ",start)
counter.close()

for x in range(int(start),1000):
    print("Processing Done upto : ",x)

    #For every iteration we are writing it in the file with the new position
    writer = open('counter.txt',"w")
    writer.write(str(x))
    writer.close()

Fixing your code :
Note: Create a text file manually with the name 'counter.txt' and write '0' in it.
import pandas as pd
import requests as rq
import os,time,random,pickle
import csv
data=pd.read_csv("consensus_data.csv",usecols=["CaptureEventID","Species"])

z=data.loc[ data.Species.isin(['buffalo']), :]

df1=pd.DataFrame(z)

data_2=pd.read_csv("all_images.csv")

df2=pd.DataFrame(data_2)

df3=pd.merge(df1,df2,on='CaptureEventID')

p=df3.to_csv('animal_img_list.csv',index=False)

# you need to change the location below
data_final = pd.read_csv("animal_img_list.csv")
output=("/home/avnika/data_serengeti/url_op")

mylist = []

for i in range(0,100):
    x = random.randint(1,10)
    mylist.append(x)

print(mylist)

for y in range(len(mylist)):
    d=mylist[y]
    print(d)

# Opeing the file you manually created with '0' present in it.
counter =  open('counter.txt',"r")
start = counter.read()
count = start
counter.close()

file_name = data_final.URL_Info
print(len(file_name))

# The starting position from the file is used to slice the file_name from 'start' value.
for file in file_name[start:]:
    image_url='https://snapshotserengeti.s3.msi.umn.edu/'+file
    f_name=os.path.split(image_url)[-1]
    print(f_name)
    r=rq.get(image_url)

    with open(output+"/"+f_name, 'wb') as f:
        f.write(r.content)

    # File is downloaded and now, it's time to update the counter in the text file with new position.
    count+=1
    writer = open('counter.txt',"w")
    writer.write(str(count))
    writer.close()

    time.sleep(d)

Hope this helps :)

A: The answer to your problem is Saving Object in python using pickle , you can simply save the object in pickle and retrieve it according to your conditions. so whenever you will get error just catch the error and dump the number in pickle from where you want start the script.
You can refer below link.
https://pythonprogramming.net/python-pickle-module-save-objects-serialization.


text:
Q: Python, advice on grouping functions I have a project, simulating numerics for my diploma thesis in physics, I think one should call this a rather small project... there might be maybe a hundred functions in the end (each doing some rather small logical block).
Somehow, I'm reluctant to put this all into a package, it feels "too big" a tool (and also it feels nicer to have just some text files importing each other than a more complex folder structure)
Is there a reason not to use classes with @staticmethods instead of grouping your functions into packages?
In short: I want to have more then one level of nested functions (not just file -> function), because in this case I have to search for the correct names and type them each time. It should be like: type np. -> get a list in the editor -> chose linalg. -> get a list -> chose function. Is this possible without building a package, as indicated above?
I hope this question is not just a matter of opinion but sufficiently "answerable". Sorry if not.

A: Static method is something used by OOP, functions are used in structural programming. Since OOP is modern - you know, what I'm trying to say. All in all - that is an entry in a dict structure...
To me - group by logic, not the purpose. For instance some projects have subdirectories for models, views, and controllers. If you try to change user functionality - you are supposed to look around, since functionality is in different locations. I know that html templates are located separately to make webmaster's work easier.

A: You could group you functions into modules without creating a class to hold a bunch of static methods.   you would only want to go that route if you felt there were instances of the class you were creating and there was a need to act outside the instance level (maybe on a list of instances or setting some global variable that is used in creation of the instances).   based on your description it sounds more like you need to head with organizing the functions into modules (possibly by responsibility or data acted on in the overall program).


text:
Q: Android: How to change the DatePicker view date format from MM/dd/yyyy to dd/MM/yyyy? I have been trying to get an answer to this question for quite a while. I also had a look at the following link: Android - DatePicker Widget Format.
On my phone/ emulator (v 2.3.3) both the DatePicker widget and the dialog do not take the date format specified in settings (Settings->Date&Time->Select date format). They are always in the format "MM/dd/yyyy". The locale is set to English UK.
I get "d/MM/yyyy" when I read the settings with:
Settings.System.getString(getContentResolver(), Settings.System.DATE_FORMAT);
Does anybody have an idea about how to change the date format in a DatePicker view?

A: That setting is very specific. It is only meant to apply to dates dates shown in "short format". As long as you're using anything else (in this case, the DatePicker seems to be using "medium"), then those settings will be disregarded and the Locale's default formatting will take over.
I can confirm that if you change your phone's the language (and, effectively, the Locale) the order of the elements does changes in the date picker. Which I guess means I disagree with Dan S's assertion that "the system does not use any mechanism to localize the DatePicker". If you look at the code, you can see that (at least since 2.1), there's a reorderPickers() method that does exactly this.
English:

French:

A: To override the DatePicker format the best bet would be to override one of its constructors with a slight edit to the original code. You can edit the ViewGroup in code for you but I'd seriously consider not doing it that way.

*

*Create class LocalizedDatePicker

*Override public DatePicker (Context context, AttributeSet attrs, int defStyle) http://developer.android.com/reference/android/widget/DatePicker.html#DatePicker(android.content.Context, android.util.AttributeSet, int)

*Copy the code from the original DatePicker constructor (you may need to select a different branch after some testing, I have linked the head)

*Override methods that call reorderSpinners() to remove that call.

*Replace line inflater.inflate(R.layout.date_picker, this, true); with inflater.inflate(my.package.R.layout.localized_date_picker, this, true);

*Copy the original date_picker.xml layout to your local resource localized_date_picker.xml

*Edit the file for the desired order, since you're editing this please respect the localization of other places and keep a copy of the original in your global layout folder and put the localized_date_picker.xml in your region specific folder. Since the system's layout is Month Day Year people in other places may expect that order.


text:
Q: Select columns if row exists else default values in oracle In Oracle sql,I want to select few columns values from a table. If no row exists, i want to select default values for each columns. I need something like below
if exists (select 1 from mytable where key ='11')
then
select key, value, comment from mytable where key ='11'
else
select 'key1' as "key", 'value1' as "value", 'default' as "comment"

What is the best way to do this in oracle.

A: Try this:
select
    key,value,comment
from mytable
where key = '11'
union all
select 'key1', 'value1', 'default' from dual
where not exists (select 1 from mytable where key = '11')

A: WITH defaults ( key, value, comment ) AS (
  SELECT 'key1', 'value1', 'Default' FROM DUAL UNION ALL
  SELECT 'key2', 'value2', 'Default' FROM DUAL UNION ALL
  SELECT 'key3', 'value3', 'Default' FROM DUAL UNION ALL
  SELECT 'key4', 'value4', 'Default' FROM DUAL
)
SELECT COALESCE( t.key,     d.key     ) AS key,
       COALESCE( t.value,   d.value   ) AS value,
       COALESCE( t.comment, d.comment ) AS comment
FROM   defaults d
       FULL OUTER JOIN
       your_table t
       ON ( t.key = d.key );


text:
Q: Calling C++ dll from .Net code is excruciatingly slow when a debugger is attached I am using VS 2008 to compile and debug my code. In my application, the front end is C#, the backend is C++. I access the C++ code via interop.
One thing I notice is that if I press F5, and I link in the debug version of the native code, it would take more than 20 seconds to run the native code. If I link in the release version of the native code, the time needed to run it is cut down to 7-8 seconds.
And if I don't have the VS 2008 debugger attached ( i.e., I click on the exe outside of the IDE), and I link in the release version of the C++ code, it takes only 1 second to run the C++ code.
Note that for all the testing, the input to C++ code is always always the same.
For sure, there are some overheads associated with the attachment of debugger, and debug build. But the difference in performance is just too big. Could there be anything I miss or I can tune up?
I find that this is very puzzling; C# in my experience doesn't introduce this much overhead, regardless of whether you are running with a debugger, or whether you are running in debug mode.

A: My best guess would be that loading the debugging symbols is what's slowing you down. I've seen the exact same thing happen with purely unmanaged C++ projects that are set to automatically load the symbol files for all of the Windows system libraries. Make sure that you're not automatically loading debugging symbols:

*

*In the "Tools" menu, click "Options".

*Expand the "Debugging" category to the left, and select the "Symbols" subcategory.

*Check the checkbox labeled "Search the above locations only when symbols are loaded manually".

Additionally, consider that mixed-mode debugging is extremely slow.
If you don't need the ability to step into the code in the C++ DLL, you can try turning off the "Enable unmanaged code debugging" option in your project's properties:


text:
Q: How to do this in C (from Java) I am currently learning the wonderful Arduino and some C and I am trying to get this to work. How do I do the following in C!
String val = "";
while(true) {
    thisChar = "2"; // this will be a "char" in C, this is finished in C, it's reading from a stream, the "2" is just an example
    if(val.length < 3) {
        val = val + thisChar;
    } else {
        int num = val;
        // i will do something with my new int thing
        val = "";
    }
}

So I am trying to basically get a char, bunch three of them into a string, covert it into an int and then do something with it. the numbers sent in threes are anything between 000 and 100!
I will post what I have come up with.
char val[];
if (client.available() > 0) { //finns åtmminstone 1 klient?
  char thisChar = client.read(); //läser av nästa byte från servern
  if( thisChar == 'H' ){
    Serial.println("HIGH from client");
    digitalWrite(led, HIGH); // lys LED
  }
  else if( thisChar == 'L' ){
    Serial.println("LOW from client");
    digitalWrite(led, LOW); // släck LED
  }
  else {
    Serial.println(thisChar);
    int len = strlen(val);
    if(len < 3) { // saknas fortfarande tecken tex 0 eller 02
      val = val +
    }
    else { // värdet är komplett tex 010 eller 100
      val = "";
    }
  }
}

ANSWER:
Thanks to @morgano for the chat he was able to piece together the following code from all three answers!
  static char val[4] = {0}; //we only care about 3 digit numbers.
  static int len = 0;
  //... code blabla
  char thisChar = client.read(); //läser av nästa byte från servern
  //... code blabla
  else {
    val[len] = thisChar;
    len++;
    if(len > 2) { // värdet är komplett tex 010 eller 100
      int i;
      sscanf(val, "%d", &i);
      Serial.println(i);
      //Serial.println(val);
      len = 0;
      //val[3] = 0;
    }
  }

A: What you have looks good--you just need to decide how to "append" text to your char array.
I would keep a variable describing the current "length" of the string.  So, you can try something like:
char val[4]; //we only care about 3 digit numbers.
int valLength = 0; //No characters in the string yet.

char thisChar = client.read();

val[3] = '\0';  /* Need to terminate the string, or else... */
if (valLength < 3) {
  val[valLength] = thisChar;
  valLength++;
}
else {
  int myIntVal = strtol(val, 0, 10); //I believe this is the right syntax.  I'm not 100% sure.
  val[0] = 0;
  val[1] = 0;
  val[2] = 0;
}

A: Converting your Java code directly to C gives me this. Change the array size to what your max string size could be.
char *val;
char inputchar[10];
int num;
val= malloc(sizeof(char) *20);
while(1){
  inputchar=readclient();
  if(strlen(val) < 3)
   val = strcat(val, inputchar);
  else {
   num= atoi(val);
   memcpy(val, '\0', 10 );
   }
  }
 free(val);

You need to check the functions atoi and memcpy once.

A: Adding yet another solution that doesn't imply using char[] or "string" functions:
int val = 0;
int len = 0;

while(1) {
    char thisChar = clientread();
    if(len < 3) {
        val = val * 10 + (thisChar - 0x30);
        len++;
    } else {
        do_something_with_val(val);
        val = 0;
        len = 0;
    }
}


text:
Q: How to determine when a noun is an objective genitive versus a subjective genitive? St. Augustine writes in Soliloq. i, 10, as quoted in the English translation of St. Thomas Aquinas's Summa Theologica II-II q. 151 a. 3 ad 2:

I consider that nothing so casts down the manly mind from its heights as the fondling of women, and those bodily contacts which belong to the married state.

Is the genitive "of women" here being used subjectively or objectively? Viz., are the women fondling (subjective genitive), or is St. Augustine referring to men's fondling women (objective genitive)? How do we know?
English version of this Latin StackExchange question

A: We might be able to infer the meaning from context, but there is nothing in Augustine's sentence that would allow us to say with certainty whether the women were being fondled or doing the fondling.
By the way, this ambiguity is fairly common in English and does not require a gerund. For example: "I enjoyed the story of the old man." Was the story told by the old man, or was it about him?

A: One  thing is certain at the outset: it can't be  both. Suppose it  is subjective;  the objective possibility is then more or less considered as irrelevant. This means  that only the caresses from women would be detrimental; but then the author adds a complement of information: what also  matters is mere contact, which  must include some  fondling of some sort as performed by the man, the usual sort pertaining to the conjugal state, whatever precisely that sort is. Can we infer that  the married man's active part in the practice of fondling is  negligible compared to that of his partner? I don't think so, nor  would  certainly anyone else. Therefore, that marital sort of fondling, which is quite similar to that in non marital situations, would matter in the bringing about of this  possible demise from "the heights of the manly mind", but not  that in non marital contexts. This is very improbable, and one can  safely conjecture from the  linguistic context that what is meant is fondling as performed by the man.


text:
Q: Date axis in linechart using primefaces and jqplot I've tried to show a linechart with primefaces and jqplot. But I don't get it. I have this code in my bean:
CartesianChartModel graphic = new CartesianChartModel();
LineChartSeries series = new LineChartSeries();
DateFormat dateFormat = new SimpleDateFormat("mm/dd/yy");
String date1 = "01/10/13";
String date2= "01/15/13";
String date3= "02/20/13";

p=dateFormat.parse(date1);
series.set(p.getTime(), 10);
p=dateFormat.parse(date2);
series.set(p.getTime(), 20);
p=dateFormat.parse(date3);
series.set(p.getTime(), 15);

graphic.addSeries(series);

And I have this code in my extender function:
function extender(){
this.cfg.axes = {
   xaxis :{
      renderer:$.jqplot.DateAxisRenderer,
      rendererOptions : {
             tickRenderer:$.jqplot.CanvasAxisTickRenderer
      },
      tickOptions : {
           fontSize:'10pt',
           fontFamily:'Tahoma',
           angle:-40,
           formatString:'%D'
       }

    };

    this.cfg.axes.xaxis.ticks = this.cfg.categories;
}

PROBLEM
It doesn't work properly because I get date3 before the others and the date is not shown in the x axis.
I've just tried to do like PrimeFaces - customise Date Chart. I've changed the time format and I've added the tickInterval element. With these changes I get an empty graphic. And if I remove the tickInterval element I get on the x axis something like that on each tick 111011000001110111000000000-%y

A: Ok..I am not sure if you still need this, but I was facing a similar problem and this is how I solved it. I also needed to zoom into the dates.
Firstly, primefaces does not contain DateAxisRenderer . You need to download it and add it seperately in your code. You can get it here -
DateAxisRenderer.js
And then add it into your code like so -
<h:outputScript library="js/plugins" name="jqplot.dateAxisRenderer.min.js" target="head" />

Place the file under webapp/js/plugins ..this might ofcourse vary between projects...
Then send the date as long from the backing bean and remove the following line from your javascript -
this.cfg.axes.xaxis.ticks = this.cfg.categories;

It should work properly then.

A: I've solved my problem creating a new proyect like that and it works. I don't know what was the problem.
But I have a new problem.
I've just tried to plot a range of data between 01/01/2013 and 01/03/2013 and I only get data in January. It means, I get a plot with the data in January and February printing in the same date, in January.

A: You have to set the X axis value using epoch millis. I had to figure it out.


text:
Q: Why can't my custom domain on Heroku be resolved? I configured a custom domain for a small site on Heroku on Friday. It worked then, but now, it's broken. The host is nedgros.de. nedgros.herokuapp.com has address 23.21.239.236.
Is does not resolve to the right application. How can I configure the DNS to follow the Dyno dynamics?

A: $ dig  nedgros.de any
...
;; QUESTION SECTION:
;nedgros.de.                    IN      ANY

;; ANSWER SECTION:
nedgros.de.             86301   IN      CNAME   nedgros.herokuapp.com.

Short answer: you cannot have a CNAME at the "top" of the zone, a CNAME is an alias or reference, it cannot coexist with any other data. Specifically, it cannot coexist with a NS and SOA records which are rather important for the correct operation of your domain. RFC 1912 Section 2.4.
You have not properly followed the Heroku instructions. See https://devcenter.heroku.com/articles/custom-domains , if this setup is what you want read the part on "Apex domains".


text:
Q: Import complex XML in to Excel 2016 :UPDATED:
I am trying to import an XML file from an online source in to Excel 2016 which is working fine but the response is limited to 200 records and I want to create a single table and populate it with data with multiple requests. The response data sample I'm working with is as follows:-
<?xml version="1.0" encoding="UTF-8"?>
<response uri="/crm/private/xml/Products/getRecords">
<result>
<Products>
<row no="1">
<FL val="PRODUCTID">1250447000004184129</FL>
<FL val="Product Code">
<![CDATA[
1321321321321321
]]>
</FL>
</row>

I have now the following VB code (with a little help from other threads) but am getting all of the values together in one cell, I cant seem to pull only the product code records into seperate rows?
Sub XMLfromPPTExample2()

Dim XDoc As MSXML2.DOMDocument60
Dim xProducts As MSXML2.IXMLDOMNode
Dim xrow As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode

Dim wb As Workbook
Dim Col As Integer
Dim Row As Integer

Set XDoc = New MSXML2.DOMDocument60
XDoc.async = False
XDoc.validateOnParse = False
XDoc.Load ("xml")
LoadOption = xlXmlLoadImportToList

Set xProducts = XDoc.DocumentElement
Set xrow =
xProducts.SelectSingleNode("/response/result/Products/row/FL[val='Product
Code']")

Col = 1
Row = 1

For Each xrow In xProducts.ChildNodes
 Row = 1

For Each xChild In xrow.ChildNodes
  Worksheets("Sheet2").Cells(Col, Row).Value = xChild.Text
   Row = Row + 1
Next xChild

Next xrow

End Sub

A: Well I have got the vba code up and running to bring in the first 200 records, now i just need to build a loop in to get the rest of them!
Sub Tester()
Dim xDoc As MSXML2.DOMDocument60
Set xDoc = New MSXML2.DOMDocument60

xDoc.async = False
xDoc.validateOnParse = False

If xDoc.Load("xml") Then
' The document loaded successfully.
Else
' The document failed to load.
End If

Dim i As Integer
Dim list As IXMLDOMNodeList
Set list = xDoc.SelectNodes("//response/result/Products/row")

Dim node As IXMLDOMNode

i = 1
For Each node In list
    i = i + 1

    With Sheet1.Rows(i)
        .Cells(1).Value = GetNodeValue(node, "FL[@val=""Product Code""]")
        .Cells(2).Value = GetNodeValue(node, "FL[@val=""PRODUCTID""]")
    End With

Next node

End Sub


text:
Q: Estimate growth rates in a probit/logit model I consider a situation where k different kinds of bacteria grow together in a petri dish and each kind of bacteria exhibits exponential growth, i.e. the population size over time is given by $N_i(t) = N_i(0)e^{r_it}$ for each $i = 1,\dots, k$. All growth rates but the first are unknown, and $r_1 = 1$. At specified points in time $t = 0, 1, \dots, T$, I take a random sample from the petri dish of fixed size, say M. Now let $n_i(t)$ denote the number of bacteria of type i sampled at time t. Then $n_i(t)$ is a realization of a binomial random variable with parameters $(M,p_i)$ where $p_i = N_i(0)e^{r_it} /\sum_{j = 1}^k N_j(0)e^{r_jt}$.
My goal is to find a method to estimate the unknown growth rates $r_i$ based on the samples $\{ n_i(t) \}_{i,t}$. One way to do so is to compute the log ratios $\log(N_i(t)/N_1(t))$ and regress them on the time vector. This yields reasonable results but I feel it is conceptually wrong. On the other hand I could also compute a probit/logit regression but I don't know how to obtain the growth rates from the regression coefficients.
Sorry in case the format of the question is not fine. It's my first post here. Many thanks for any ideas!


text:
Q: Fire an event in netbeans I am currently coding my first GUI application in netbeans.I have a JComboBox and a JTable in my JFrame.
When an Item is selected in the ComboBox , I want to add rows to the JTable but in what event shall i put the code that will fill the Jtable

A: You need to add the listener to the comboBox and then get the model of the jtable and add the row
Example:
ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Selected: " + comboBox.getSelectedItem());
        System.out.println(", Position: " + comboBox.getSelectedIndex());

        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

        model.addRow(row);

    }
};

A: You can use either ActionPerformed event or ItemStateChanged event of JCOMBOBOX.
You can right click on the JCOMBOBOX and do the following
   public void populateTable(JTable jt, String value) {
        DefaultTableModel dtm = (DefaultTableModel) jt.getModel();
        int rowCount = jt.getRowCount();
        for (int i = rowCount - 1; i >= 0; i--) {
            dtm.removeRow(i);
        }
        Object data[] = new Object[1];
        data[0] = value;
        dtm.addRow(data);

    }
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String selValue =(String) jComboBox1.getSelectedItem();
        populateTable(jTable1, selValue);
    }

Following is the Output:
Output


text:
Q: Join tables based on dates with check I have two tables in PostgreSQL:
Demans_for_parts:
   demandid partid  demanddate        quantity
    40       125     01.01.17          10
    41       125     05.01.17          30
    42       123     20.06.17          10

Orders_for_parts:
  orderid  partid orderdate        quantity
   1        125     07.01.17     15
   54       125     10.06.17     25
   14       122     05.01.17     30

Basicly Demans_for_parts says what to buy and Orders_for_parts says what we bought. We can buy parts which do not list on Demans_for_parts.
I need a report which shows me all parts in Demans_for_parts and how many weeks past since the most recent matching row in Orders_for_parts. note quantity field is irrelevent here,
The expected result is (if more than one row per part show the oldes):
partid   demanddate        weeks_since_recent_order
125     01.01.17                  2   (last order is on 10.06.17)
123     20.06.17                Unhandled

A: I think the tricky part is getting one row per table.  But that is easy using distinct on.  Then you need to calculate the months.  You can use age() for this purpose:
select dp.partid, dp.date,
       (extract(year from age(dp.date, op.date))*12 +
        extract(month from age(dp.date, op.date))
       ) as months
from (select distinct on (dp.partid) dp.*
      from demans_for_parts dp
      order by dp.partid, dp.date desc
     ) dp left join
     (select distinct on (op.partid) op.*
      from Orders_for_parts op
      order by op.partid, op.date desc
     ) op
     on dp.partid = op.partid;

A: smth like?
with o as (
  select distinct partid, max(orderdate) over (partition by partid)
  from Orders_for_parts
)
, p as (
  select distinct partid, min(demanddate) over (partition by partid)
  from Demans_for_parts
)
select p.partid, min as demanddate, date_part('day',o.max - p.min)/7
from p
left outer join o on (p.partid = o.partid)
;


text:
Q: Why is $\sqrt{ ( \sum (x_i^2) + x_{i+1}^2 ) ( \sum (y_i^2) + y_{i+1}^2 ) } \geq \sqrt{\sum (x_i^2)} \sqrt{ \sum (y_i^2) } + |x_{k+1} y_{k+1}|$ Without the restriction of character count constraints in the title, my question is more accurately to ask why it is the case that:
$\sqrt{ ( \sum_{i=1}^{k} (x_i^2) +  x_{i+1}^2 ) ( \sum_{i=1}^{k} (y_i^2) +  y_{i+1}^2  ) } \geq \sqrt{\sum_{i=1}^{k} (x_i^2)} \sqrt{ \sum_{i=1}^{k} (y_i^2) } + |x_{k+1} y_{k+1}|$
I expand via FOIL to get:
$\sqrt{ \Big( \sum_{i=1}^{k} (x_i^2) +  x_{i+1}^2 \Big) \Big( \sum_{i=1}^{k} (y_i^2) +  y_{i+1}^2  \Big) } \\
    = \sqrt{ \Big( \sum_{i=1}^{k} (x_i^2) \Big) \Big( \sum_{i=1}^{k} (y_i^2) \Big) + \Big( \sum_{i=1}^{k} (x_i^2) \Big) y_{i+1}^2 + \Big( \sum_{i=1}^{k} (y_i^2) \Big) x_{i+1}^2 + x_{i+1}^2  y_{i+1}^2}$
However, I'm unsure how to proceed from here to show that this is greater than or equal to $\sqrt{\sum (x_i^2)} \sqrt{ \sum (y_i^2) } + |x_{k+1} y_{k+1}|$.

A: Note that
$$(A^2+a^2)(B^2+b^2)-(AB+ab)^2=A^2b^2-2AbBa+B^2a^2=(Ab-Ba)^2\geq 0.$$
Now let  $A:=\sqrt{\sum_{i=1}^k x_i^2}$, $B:= \sqrt{\sum_{i=1}^k y_i^2 }$, $a:=|x_{k+1}|$, and $b:=|y_{k+1}|$.


text:
Q: Can a weapon have a negative Strength requirement through upgrades? Through the use of Upgrade Scrolls, is it possible to reach a negative strength requirement? Assuming there are enough Upgrade Scrolls in the game and you don't die due to your lack of quality armour or weapon.

A: Yes. I once got a glaive on Lvl 1 of the dungeon and I was like "This is great!" I then proceeded to put every scroll I found into it. By the Tengu I got it to +20 and it did require a minumum strength of -2 to use. I was playing an Assassin and was eventually killed by ranged attacks (Dwarf Warlock).


text:
Q: I have just downloaded Ubuntu 20.04.4 LTS but its failing with error messages when I run sudo apt update I downloaded using WindowStore. I searched for Ubuntu 20.04.4 LTS and used that to get and install.
I have just downloaded Ubuntu 20.04.4 LTS  but its failing with error messages when I run sudo apt update
My windows is
OS Name:                   Microsoft Windows 10 Enterprise
OS Version:                10.0.19044 N/A Build 19044

I am running WSL 2
  NAME                   STATE           VERSION
* docker-desktop-data    Running         2
  Ubuntu20.04LTS         Running         2
  docker-desktop         Running         2

Installation successful!
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.10.60.1-microsoft-standard-WSL2 x86_64)

* Documentation:  https://help.ubuntu.com
* Management:     https://landscape.canonical.com
* Support:        https://ubuntu.com/advantage
  System information as of Sat Mar 19 19:26:11 GMT 2022
  System load:  0.25               Processes:             8
  Usage of /:   0.5% of 250.98GB   Users logged in:       0
  Memory usage: 9%                 IPv4 address for eth0: 172.29.53.52
  Swap usage:   0%

1 update can be applied immediately.
To see these additional updates run: apt list --upgradable

The list of available updates is more than a week old.
To check for new updates run: sudo apt update
This message is shown once a day. To disable it please create the
/home/tonycav/.hushlogin file.

tonycav@LAP-8M8NK13:~$ sudo apt update
[sudo] password for tonycav:

Err:1 http://archive.ubuntu.com/ubuntu focal InRelease
  Temporary failure resolving 'archive.ubuntu.com'

Err:2 http://security.ubuntu.com/ubuntu focal-security InRelease
  Temporary failure resolving 'security.ubuntu.com'

Err:3 http://archive.ubuntu.com/ubuntu focal-updates InRelease
  Temporary failure resolving 'archive.ubuntu.com'

Err:4 http://archive.ubuntu.com/ubuntu focal-backports InRelease
  Temporary failure resolving 'archive.ubuntu.com'

Reading package lists... Done
Building dependency tree
Reading state information... Done
All packages are up to date.
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal-updates/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal-backports/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/focal-security/InRelease  Temporary failure resolving 'security.ubuntu.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.

tonycav@LAP-8M8NK13:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: bond0: <BROADCAST,MULTICAST,MASTER> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 36:09:ba:44:25:83 brd ff:ff:ff:ff:ff:ff
3: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 6a:5e:23:15:f5:90 brd ff:ff:ff:ff:ff:ff
4: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
    link/ipip 0.0.0.0 brd 0.0.0.0
5: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
    link/sit 0.0.0.0 brd 0.0.0.0
6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:91:6f:4e brd ff:ff:ff:ff:ff:ff
    inet 172.29.53.52/20 brd 172.29.63.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::215:5dff:fe91:6f4e/64 scope link
       valid_lft forever preferred_lft forever

Permissions
tonycav@LAP-8M8NK13:~$ ls -l /etc/resolv.conf

lrwxrwxrwx 1 root root 29 Mar 19 19:25 /etc/resolv.conf -> ../run/resolvconf/resolv.conf

Host file I commented out all the IPv6
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateHosts = false
127.0.0.1       localhost
127.0.1.1       LAP-8M8NK13.localdomain LAP-8M8NK13
<feff>

192.168.0.11    host.docker.internal
192.168.0.11    gateway.docker.internal
127.0.0.1       kubernetes.docker.internal

# The following lines are desirable for IPv6 capable hosts
#::1     ip6-localhost ip6-loopback
#fe00::0 ip6-localnet
#ff00::0 ip6-mcastprefix
#ff02::1 ip6-allnodes
#ff02::2 ip6-allrouters


text:
Q: Normal Matrix vs Diagonalizable Matrix I'm trying to understand the difference between a normal matrix ($A^TA = AA^T$) versus a matrix that can be diagonalized (let's stick with real matrices for this question).  In particular, does one of these concepts enclose the other:

*

*Is a diagonalizable matrix a subset of normal matrices?

*Or, is a normal matrix a subset of diagonalizable matrices?

Perhaps the answer depends on some nuance I haven't appreciated or they are interrelated in a way I haven't come across.  I have consulted a number of sources and I don't see a clear answer.  Can someone clarify this?

A: Every normal matrix is (unitarily) diagonalizable (a standard result), but not every diagonalizable matrix is normal.
If $S$ is an invertible matrix that is not unitary (i.e., $S^* \ne S^{-1}$) and $D$ is a diagonal matrix that does not commute with $S$, then $A := SDS^{-1}$ is diagonalizable but not normal.

A: Take $A=\begin{pmatrix}1&-2\\1&4\end{pmatrix}$ which is diagonalizable but not normal to see why first bullet is false.


text:
Q: How to find out the maximum and minimum length of strings that match to a given regular expression A theoretical question. I have a regex. I want to find the strings that match to this. How can i get the minimum and maximum length of these strings?

A: Convert the regular expression to an NFA (with epsilon transitions, if you like). Delete every state that cannot reach an accepting state (this might be a no-op). The minimum length is the length of a shortest path to an accepting state (use Dijkstra from the start state, where transitions with symbols have length 1 and epsilon transitions have length 0). Using a double-ended queue, this is linear-time. The maximum length is infinity iff there is a cycle. Otherwise, the transition graph is acyclic; use an algorithm for longest path in an acyclic graph.

A: You would need to parse and analyse the regex.  For classical regexes it is pretty straight-forward to work out the bounds on the lengths.  If you include look-aheads and look-behinds it could get rather complicated, but the problem is tractable (I think).
I'm not aware of any library methods that would do this (in Java).  But that is hardly surprising.  The use-cases for this functionality must be few and far between.


text:
Q: Is it viable to make cross-domain ajax requests within iframed content? I have an application on one domain which needs to get data from an application on another domain.
I would like to use an iframe based cross domain ajax tool such as porthole.js to implement the following:

*

*My application loads a page on the other server in an iframe.

*A message is sent using porthole to the iframe.

*The page on the other server checks to make sure the calling url is valid, and reads in the url of the ajax request it will make from the message.

*The remote page then uses the passed url to make an ajax request.

*The results are passed back to my application.
This solution lets me use the remote json data without systematically altering all of the services, which are built and managed by another team. If it doesn't work, I would work with them to use a system that uses porthole.js or jsonp for cross domain scripting.
The point that concerns me, though, is step 4. Does this count as an ajax call from the remote document inside the iframe, which would be able to make ajax calls against it, or does it count as a call from the outer window, which can't use ajax to call that domain?

A: Jeez, just use CORS.  It's a one-line change to the web-server config.


text:
Q: Vue 3 router with long url-param including special chars not working as intended? I have a router in Vue looking like this:
    {
      path: '/temporaryList/:tempUrl',
      name: 'temporaryList',

      component: () => import('../views/TemporaryListView.vue')
    }

I want to send a value for the "tempUrl"-param that could for example look like this:
https%3A%2F%2Fwww.amazon.se%2F%5Bn%5Btest%5B~%5B
(this value is coming from encodeURIComponent() function, so it should be able to be used in the URL)
This does not seem to work for some reason, When I try to access this page I get:
"There was no web page at the URL: http://localhost:3000/temporaryList/https%3A%2F%2Fwww.amazon.se%2F%5Bn%5Btest%5B~%5B "
I have built this exact same solution with node and express where this didn't seem to be an issue. I don't know if the value of the param I send is to long for Vue? It also seems like Vue does not like when a params includes a "%" for example.
Is there any way you can make Vue routers allow this type of param-value?

A: Vite uses the decodeURIComponent function on the request URL. The value of the param i sent had "%" included in it which made Vite read every "%" as a "/". That made Vite searchfor a location that did not exist.
This npm-package solved my issue: https://github.com/ivesia/vite-plugin-rewrite-all


text:
Q: Container and Component of the same Class I'm new to React and Redux,
I'm trying to use a Class as a Redux Container (so the state is managed by reducer) and also a classic Component with another instance (no link to reducer)
So basically something like this:
class BaseLogo extends Component {

    constructor(props){
        super(props);
    }

    render(){
        let link = this.props.linkLogo || this.props.link;
        return (
            <Link className="btn btn-primary" to={link}>
                {this.props.logoName}
            </Link>
        );
    }
}

function mapStateToProps(state){
    return {
        linkLogo: state.linkLogo
    };
}

let Logo = connect(mapStateToProps)(BaseLogo);
export {Logo, BaseLogo as Button};

So I wanna use Logo as a Container, and Button as a Component (no reducer) with a specified props.
But as the way Redux bind it, whenever I create an instance of class Logo, there will be a reducer.
Is there somehow I can isolate the connect()() from the class itself ?
Thank you.

A: I found the error, it dues to a bad implementation in the code. Thank you all


text:
Q: How to integrate ceritifacte with nginx I used letsencrypt to create sertificate for my website and I got following keys generated by certbot
cert.pem
chain.pem
fullchain.pem
privkey.pem

Following is my nginx conf file. I created public and private key sometime ago which are in followig file
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen 443 ssl;
    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;
    server_name ec2-54-244-132-69.us-west-2.compute.amazonaws.com;
        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;
    location / {
        try_files $uri $uri/ =404;
    }
        location /coupons {
            proxy_pass  http://127.0.0.1:9000;
        }
        location /bot {
            proxy_pass  http://127.0.0.1:5000;
        }
        location /v1/coupons/images {
            alias /home/ubuntu/coupon-engine/resources/public/storage/img/;
        }
}

A: I recommend this configuration. It's work for me.
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen 443 ssl;
    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;
    server_name ec2-54-244-132-69.us-west-2.compute.amazonaws.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;

    location / {
        try_files $uri $uri/ =404;
    }
        location /coupons {
            proxy_pass  http://127.0.0.1:9000;
        }
        location /bot {
            proxy_pass  http://127.0.0.1:5000;
        }
        location /v1/coupons/images {
            alias /home/ubuntu/coupon-engine/resources/public/storage/img/;
        }
}

I wrote some documentation for my self, you can see in my blog http://docs.harapan.me/2016/07/konfigurasi-secure-https-pada-web.html , but I am soory that the language in Indonesia


text:
Q: Vectorized "and" for pandas columns With a data like this one
import pandas as pd
tcd = pd.DataFrame({
 'a': {'p_1': 1, 'p_2': 1, 'p_3': 0, 'p_4': 0},
 'b': {'p_1': 0, 'p_2': 1, 'p_3': 1, 'p_4': 1},
 'c': {'p_1': 0, 'p_2': 0, 'p_3': 1, 'p_4': 0}})
tcd
#      a  b  c
# p_1  1  0  0
# p_2  1  1  0
# p_3  0  1  1
# p_4  0  1  0

(but with 40e3 columns)
I look for a vectorized way to put the boolean and in a result Series:
a & b = ab -> 1 or True    a & c = ac -> 0 or False
1   0   0                  1   0   0
1   1   0                  1   0   0
0   1   1                  0   1   0
0   1   0                  0   0   0

For now I only get an ugly solution with a for loop::
res = pd.Series(index=['a&a', 'a&b', 'a&c'])
for i in range(3):
  res[i] = (tcd.iloc[:, 0] & tcd.iloc[:, i]).any()

res
aa    1
ab    1
ac    0

with the B.M. answer I get this
def get_shared_p(tcd, i):
    res = (tcd.iloc[:, i][:, None] & tcd).any()
    res.index += '&_{}'.format(i)
    return res

res = pd.DataFrame(columns=range(cols), index=range(cols))
for col_i in range(cols):
    res.iloc[:, col_i] = list(get_shared_p(tcd, col_i))

print res
#        0     1      2
# 0   True  True  False
# 1   True  True   True
# 2  False  True   True

We can probably avoid this new for loop.

A: You can use np.logical_and and numpy's broadcasting.
Say you define x and y as the first column, and entire matrix, respectively:
import numpy as np

x = tcd.as_matrix()
y = tcd.a.values.reshape((len(tcd), 1))

now, using broadcasting, find the logical and of x and y, and place it in and_:
and_ = np.logical_and(x, y)

Finally, find if any of the rows in any of the columns is true:
>>> np.sum(and_) > 0
array([ True,  True, False], dtype=bool)

A: Use [:,None] to align data and force broadcasting :
In[1] : res=(tcd.a[:,None] & tcd).any(); res.index+='&a'; res

Out[1]:
a&a     True
b&a     True
c&a    False
dtype: bool

A: I would solve this problem by that way:
import pandas as pd
import numpy as np
from itertools import combinations

tcd = pd.DataFrame({
 'a': {'p_1': 1, 'p_2': 1, 'p_3': 0, 'p_4': 0},
 'b': {'p_1': 0, 'p_2': 1, 'p_3': 1, 'p_4': 1},
 'c': {'p_1': 0, 'p_2': 0, 'p_3': 1, 'p_4': 0}})

for c in combinations(tcd.columns, 2):
    tcd[c[0]+c[1]] = np.logical_and(tcd[c[0]], tcd[c[1]])

print(cd)

With output:
     a  b  c     ab     ac     bc
p_1  1  0  0  False  False  False
p_2  1  1  0   True  False  False
p_3  0  1  1  False  False   True
p_4  0  1  0  False  False  False


text:
Q: Form model bypasses validation I have a user model MyProject\SecurityBundle\Entity\User with validation constraints. For my registration, I created MyProject\SecurityBundle\Form\Model\Registration:
namespace MyProject\SecurityBundle\Form\Model;

use MyProject\SecurityBundle\Entity\User;

class Registration
{
    private $user;

    private $termsAccepted;

    public function setUser(User $user)
    {
        $this->user = $user;
        return $this;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function setTermsAccepted($termsAccepted)
    {
        $this->termsAccepted = (boolean)$termsAccepted;
        return $this;
    }

    public function getTermsAccepted()
    {
        return $this->termsAccepted;
    }
}

with validation:
MyProject\SecurityBundle\Form\Model\Registration:
    properties:
        user:
            - Type: { type: MyProject\SecurityBundle\Entity\User }
        termsAccepted:
            - NotBlank: ~
    getters:
        termsAccepted:
            - "True": ~

This validation works, but the validation for the user entity is bypassed by this. Is there a way I can tunnel the validation into my registration model?

A: If I had searched in the right place, I would have found http://symfony.com/doc/2.0/reference/constraints/Valid.html this in the documentation and with it the solution:
MyProject\SecurityBundle\Form\Model\Registration:
    properties:
        user:
            - Type: { type: MyProject\SecurityBundle\Entity\User }
            - Valid: ~


text:
Q: How to give custom configurations for the mysql my.ini file in a shared database environment Hi, the mysql database server I'm working on hosts several other databases. I want to give a configuration like this:
[mysqld]
ft_min_word_len=2
ft_stopword_file=""

for a specific database only. I don't won't to affect these changes to the other databases. Is there a way to do it?

A: No you can't because, its a GLOBAL variable look here
So you can't even set it at at every session for that database.
Alternatively you can install separate instance of MySQL on the same server.


text:
Q: Python asyncio web scraping output not exporting in excel I'am new to Python asyncio web scraping. I want to export scraped data to excel using pandas. Seems like my code bellow is scraping target fields but while I am exporting output using pandas to excel then I am getting empty output file.
import asyncio
from concurrent.futures.thread import ThreadPoolExecutor
import pandas as pd
import os
import requests
from bs4 import BeautifulSoup

input_file = os.path.join(os.getcwd(), 'Sample.xlsx')
df = pd.read_excel(input_file, usecols=0)

req = requests.Session()
req.trust_env = False

Url, title, price = [], [], [],
executor = ThreadPoolExecutor(10)

def scrape(url, *, loop):
    loop.run_in_executor(executor, load_html, url)

def load_html(url):
    print(url)
    res = req.get(url)
    soup = BeautifulSoup(res.content, 'html.parser')
    Url.append(url)
    title.append(soup.select('.pinfo-title')[0].text)
    price.append(soup.select('.sale-price')[0].text)

loop = asyncio.get_event_loop()
for url in df['Urls']:
    scrape(url, loop=loop)

loop.run_until_complete(asyncio.gather(*asyncio.all_tasks(loop)))

output = pd.DataFrame({
        'Url': Url,
        'Title': title,
        'Price': price
})
output.to_excel('Output.xlsx', index=False)

but If i use print instead of appending lists like bellow, then it's print desired output.
def load_html(url):
    print(url)
    res = req.get(url)
    soup = BeautifulSoup(res.content, 'html.parser')
    print(url)
    print(soup.select('.pinfo-title')[0].text)
    print(soup.select('.sale-price')[0].text)

A: Looks like run_in_executor does not add a Task to the loop. It has to be awaited. So you need to wrap it in a co-routine and create a task in the loop. Simpler example below.
import asyncio
from urllib.request import urlopen
import json

URLS = [
    "http://localhost:8000/a",
    "http://localhost:8000/b",
    "http://localhost:8000/c",
    "http://localhost:8000/d",
]

data = []

def load_html(url):
    print(url)
    res = urlopen(url)
    data.append(res.read().decode())

async def scrape(url, loop):
    await loop.run_in_executor(None, load_html, url)

def main():
    loop = asyncio.get_event_loop()
    for url in URLS:
        loop.create_task(scrape(url, loop))

    loop.run_until_complete(asyncio.gather(*asyncio.all_tasks(loop)))
    with open('/tmp/j_dump', 'w') as fp:
        json.dump(data, fp)

if __name__ == '__main__':
    main()

Update:
Code can be simplified as below. No need extra co-routines or global data.
def load_html(url):
    print(url)
    res = urlopen(url)
    return res.read().decode()

def main():
    loop = asyncio.get_event_loop()
    tasks = [loop.run_in_executor(None, load_html, url) for url in URLS]
    data = loop.run_until_complete(asyncio.gather(*tasks))
    with open('/tmp/j_dump', 'w') as fp:
        json.dump(data, fp)


text:
Q: VisualForce page with AngularJS tag I've got an interesting question.
I have  a VisualForce page with some Angular JS.
The problem is with the ng-repeat-end tag.
The HTML looks like this:
You are here: {{breadcrumb.label}}

VisualForce won't save with this error:
Attribute name "ng-repeat-end" associated with an element type "span" must be followed by the ' = ' character.

So I change the offending tag to this:
You are here: {{breadcrumb.label}}

Which makes VisualForce happy but Angular JS mad with this error:
Unterminated attribute, found 'ng-repeat-start' but no matching 'ng-repeat-end' found.

How can I satisfy both VisualForce's parser and AngularJS?

A: At the end of the day Visualforce needs a valid XML document. Try searching for "Angular + XHTML" I guess?  I've found https://groups.google.com/forum/#!topic/angular/8iorDWKsMyI for example.
Will ng-repeat-end="ng-repeat-end" work? I remember that a trick with attr. name as attr. value is what's a perfectly fine workaround to convert for example <input type="checkbox" checked /> into valid XHTML.
SF themselves didn't include an example similar to what you're trying to do and I'm not familiar with AngularJS... It might be that they promote it but only for hybrid apps (where you could have local HTML file without the restrictions) or apps where you'd build your DOM from javascript, without having any skeleton in VF other than


text:
Q: How can I disable radio buttons or radio groups using sharedpreferences? I already tried these set of codes:
radioButton.setEnabled(false);
radioButton.setClickable(false);

but it didn't work for me because when I tried to go back again to the activity with radio buttons, it will be clickable again.
What I want is that when I click it once , it will not be clickable again even if I tried to go back to the activity.
These were the codes of my activity
public class TeacherSideQuestion extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.question1);

        Button btnNext = (Button) findViewById(R.id.btnNext);
        Button btnCheck = (Button) findViewById(R.id.btnCheckTeacher1);

        btnNext.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(v.getContext(),
                        TeacherSideQuestion2.class);
                startActivityForResult(intent, 0);

            }
        });

        btnCheck.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SharedPreferences my_preferences = PreferenceManager
                        .getDefaultSharedPreferences(getApplication());
                SharedPreferences.Editor editor = my_preferences.edit();
                RadioButton rbtnTeacher1_1 = (RadioButton) findViewById(R.id.rbtnTeacher1_1);
                RadioButton rbtnTeacher1_2 = (RadioButton) findViewById(R.id.rbtnTeacher1_2);
                RadioButton rbtnTeacher1_3 = (RadioButton) findViewById(R.id.rbtnTeacher1_3);

                if (rbtnTeacher1_1.isChecked()) {

                    Toast.makeText(TeacherSideQuestion.this, "Correct",
                            Toast.LENGTH_SHORT).show();
                    rbtnTeacher1_1.setClickable(false);
                    rbtnTeacher1_2.setClickable(false);
                    rbtnTeacher1_3.setClickable(false);

                    if (rbtnTeacher1_1.isChecked()) {
                        editor.putInt("key1", 1);
                    } else {
                        editor.putInt("key1", 0);
                    }
                    editor.commit();

                } else if (rbtnTeacher1_2.isChecked()) {

                    Toast.makeText(TeacherSideQuestion.this, "Incorrect",
                            Toast.LENGTH_SHORT).show();
                    rbtnTeacher1_1.setTextColor(Color.RED);
                    rbtnTeacher1_1.setClickable(false);
                    rbtnTeacher1_2.setClickable(false);
                    rbtnTeacher1_3.setClickable(false);

                    if (rbtnTeacher1_2.isChecked()) {
                        editor.putInt("key1", 0);
                    }
                    editor.commit();

                } else if (rbtnTeacher1_3.isChecked()) {

                    Toast.makeText(TeacherSideQuestion.this, "Incorrect",
                            Toast.LENGTH_SHORT).show();
                    rbtnTeacher1_1.setTextColor(Color.RED);
                    rbtnTeacher1_1.setClickable(false);
                    rbtnTeacher1_2.setClickable(false);
                    rbtnTeacher1_3.setClickable(false);

                    if (rbtnTeacher1_3.isChecked()) {
                        editor.putInt("key1", 0);
                    }
                    editor.commit();

                } else {

                    return;
                }
            }
        });
    }
}

A: You need to check what is value in sharedpreferences?  As per value you need to set
radioButton.setEnabled(false).

Post your code, I will explain you more about how to handle this.
Edit :
As per your code, You need to check checked states when user click on Submit button.
You can do like following.
@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.temp);

        SharedPreferences _mypref = getApplicationContext()
                .getSharedPreferences("mypref", 0); // <--- 0 - for private

        Editor editor = _mypref.edit();

        first = _mypref.getString("first", "");
        second = _mypref.getString("second", "");

        Log.e("=first==>", "===>" + first);
        Log.e("=second==>", "===>" + second);
        rbtnTeacher1_1 = (RadioButton) findViewById(R.id.radioMale);
        rbtnTeacher1_2 = (RadioButton) findViewById(R.id.radioFemale);
        if (first.length() >= 0) {
            if (first.equals("true")) {
                rbtnTeacher1_1.setChecked(true);

            } else {
                rbtnTeacher1_1.setChecked(false);

            }
        }

        if (second.length() >= 0) {
            if (second.equals("true")) {
                rbtnTeacher1_2.setChecked(true);

            } else {
                rbtnTeacher1_2.setChecked(false);

            }
        }

    }

    public void onCheck(View v) {

        if (rbtnTeacher1_1.isChecked() == true) {

            SharedPreferences _mypref = getApplicationContext()
                    .getSharedPreferences("mypref", 0); // <--- 0 - for private

            Editor editor = _mypref.edit();
            editor.putString("first", "true");
            editor.commit();
        } else {
            SharedPreferences _mypref = getApplicationContext()
                    .getSharedPreferences("mypref", 0); // <--- 0 - for private

            Editor editor = _mypref.edit();
            editor.putString("first", "false");
            editor.commit();
        }

        if (rbtnTeacher1_2.isChecked() == true) {

            SharedPreferences _mypref = getApplicationContext()
                    .getSharedPreferences("mypref", 0); // <--- 0 - for private

            Editor editor = _mypref.edit();
            editor.putString("second", "true");
            editor.commit();

        } else {
            SharedPreferences _mypref = getApplicationContext()
                    .getSharedPreferences("mypref", 0); // <--- 0 - for private

            Editor editor = _mypref.edit();
            editor.putString("second", "false");
            editor.commit();
        }

    }

And your xml looks like...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="true"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/radioSex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="male" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="female" />
    </RadioGroup>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onCheck"
        android:text="Check" />

</LinearLayout>

Select radio any of them, click on check button. Now when you come again to your activity you can see selected radio button which you checked.
Thanks.

A: In oncreate check below code.
        SharedPreferences my_preferences = PreferenceManager
                .getDefaultSharedPreferences(getApplication());
        int i = my_preferences.getInt("key1", 0);
        if(i == 1)
           // set clickable false