text:
Q: If task start time is chosen from a uniform random distribution, is inter-arrival time exponentially distributed Question: If the start time is generated from uniform random distribution, is the inter arrival time exponentially distributed?
Context:
We have a number of tasks to be run every day (and we have the flexibility to set the actual start time). To avoid overloading the system by running everything at a fixed time, and we want to spread the load through out the day. And everyday we want to run the task at the same time.
To spread the load, we hash the taskid to generate the start time. (Almost equivalent to generating from uniform random distribution)
The question is, since the arrival time is uniformly distributed and independent of each other, does the inter arrival time follow exponential distribution? I want to use queueing theory to model the system performance, since exponentially distributed inter arrival time is the most studied distribution, I want to see if I can use M/M/1 queuing model.
I understand there are some differences. The start time generated is discrete, but the exponential distribution is continuous. I assume, I can increase the granularity of the time to approximate continuous time.

Another option is to generate the start time as a Poisson process (At every t, decide whether to run or not with probability p. ) But at some point, we want to ensure the task runs every day, so we might have to force it to run at midnight eventually. So this might get a bit weird.

A: If the day is of length $1$, and there are $n$ independent uniformly distributed start times then this is equivalent to breaking a stick into $n+1$ pieces and there is probably a duplicate question on this site.
The inter-arrival times are not independent but they are identically distributed (as is the time before the first arrival and the time after the last, so $n+1$ gaps overall).  Jointly they have a uniform Dirichlet distribution.
Each gap actually has a $\text{Beta}(1,n)$ distribution so with CDF $1-(1-x)^n$ and density $n(1-x)^{n-1}$, with mean $\frac1{n+1}$ and variance $\frac{n}{(n+1)^2(n+2)}$.  I have seen this called a "reverse power function distribution".
If the day is not length $1$ but $d$ then stretch these results so the CDF of the inter-arrival times is $1-\left(1-\frac xd\right)^{n}$ and density $\frac nd\left(1-\frac xd\right)^{n-1}$ and mean $\frac d{n+1}$ and variance $\frac{n d^2}{(n+1)^2(n+2)}$.  For large $n$ this is close to an exponential distribution with rate $\frac{n+1}{d}$, as you might guess.
For example, here are the densities using R when $d=1$ and $n=100$, with the Beta distribution in red and exponential distribution in blue. They are very close to each other, and further right would be very close to $0$ (there is a slight distinction beyond $1$ as the Beta density would be exactly $0$ while the exponential density would be positive but less than $10^{−40}$). For larger n they would be even closer
n <- 100
curve(dbeta(x,1,n), from=0, to=6/n, col="red")
curve(dexp(x, n+1), from=0, to=6/n, add=TRUE, col="blue")


text:
Q: Multiprocessing some_process.start() does not execute the function In the code snippet below, .start() does not execute the method. The first print statement in self.listen_items() is never printed. There is a main file that instantiates a class to schedule and manage the instantiation of other classes as needed. The code here is from one of those classes. I have searched all morning for a hint as to the problem. Haven't found anything relating to the circumstances in my situation. Any ideas?
self.get_items_process = Process(target=self.listen_items, daemon=True, args=())
self.get_items_process.start()

def listen_items(self):
    """Method replaces listen_to_scheduler_utility() so we can manage exiting the thread on a test restart."""
    print("@@@ listen_items(start) @@@")
    while not self._restart_pending:
        print("@@@ listen_items(loop) @@@")
        item: QueueItem = self._scheduler_utility.get_item_from_queues(STR_ITERATION_CONTROLLER, self._iteration)
        if item is not None:
            print("@@@ listen_items(item) @@@")
            self.process_input(queue_item=item)

"""

A: So, here is what I have found out. First, the start() method was working all along. A shell script starts the application process and I usually redirect stdout and stderr to a file. The print statements were not showing up in that file; however, if I did not redirect output, behold, they were spewed out to the terminal screen. I am a little fuzzy on why they don't show up in the redirect but I now understand what is happening. Multiprocessing on a Linux box does a fork main thread of execution so forked process was writing the messages but the parent process was the only one writing to the log file. Thanks for all the comments...

redpajama_set_name: RedPajamaStackExchange


text:
Q: One NSDictionary visible everywhere in application Now I am developing an iOS application which works like this:
User scans QR code,
App searches for a specific key - > value,
it gives out a value to the user.
Currently I have two ViewControllers - the main and "value" ViewController, which is inherited from main. The problem is that if I create NSDictionary in main VC it is not visible in "value" VC. Main VC gives only the string (QR code, the key) through the segue. So, the value VC has to search for key and display the value.
What I ask is some kind of global variable or one DataSource visible across the whole app. Of course, I can implement NSDictionary initialisation inside value ViewDidLoad method and it will work, but this is not the point. New modules are to be added there and the variable has to be global. I googled a lot and got the idea that singleton pattern can be helpful here. I tried to implement it, but no idea how to do. Do I need it, or it is too complex for this kind of DataSource?
Thank you!

A: The basic idea is, you will still need to #include the header file of the place where this dictionary will be. The solution that Naveen proposes means that you will be including the header for the app delegate wherever you want to access it. Whether to use the app delegate for this purpose or not is kinda grayish. Some people often do this, some say its a bad use of it.
The singleton approach means that you will create a class, that will always contain the same information since the init method will return object that was previously created.
For the singleton aproach, imagine I have a database manager class. So in the header of this class (the DatabaseManagerSingleton.h) ill have this:
@interface DatabaseManager : NSObject

+ (DatabaseManager*)sharedInstance;

// Your dictionary
@property (nonatomic,strong) NSMutableDictionary* someDictionary;

The implementation will look like this: (check how "sharedInstance" initializes the object)
@implementation DatabaseManager

#pragma mark - Singleton Methods

+ (DatabaseManager*)sharedInstance {

    static DatabaseManager *_sharedInstance;
    if(!_sharedInstance) {
        static dispatch_once_t oncePredicate;
        dispatch_once(&oncePredicate, ^{
            _sharedInstance = [[super allocWithZone:nil] init];
        });
    }

    return _sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone {

    return [self sharedInstance];
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        // Custom initialization
        _someDictionary = [[NSMutableDictionary alloc] init];
    }
    return self;
}

Now, a VERY important thing is that, any place you want to use this object should first include the header:
EDIT: To use it in your code:
1) add the header
#import "DatabaseManager.h"

2) initialize the object
DatabaseManager *databaseManager = [DatabaseManager sharedInstance];

3) do whatever you need
// Initialize the dictionary
databaseManager.someDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"OBJECT",@"someKey", nil];  // In this case the object is just a NSString.

// Access
[databaseManager.someDictionary objectForKey:@"someKey"];

A: Put as a property on Appdelegate
 @property (nonatomic,strong) NSDictionary * sharedData;

Access anywhere like
NSDictionary *sharedData= ((APPDelegate *) [UIApplication sharedApplication].delegate).sharedData;


text:
Q: Lookup and fill values in one data frame by matching closest value in another Hi I have 2 dataframes:
df 1:
Year City     Address  Total_Area Basement_Area
1989 Ottawa   empty    280         130

Second data frame is a bigger one where I need to match closest neighbour by Total Area and basement Area
df2:
Year Address(with city in it) Total_Area Basement_Area
1989 123 Test Ottawa          279        120
1989 146 Test Ottawa          276        140
1989 156 Test Ottawa          283        134

Expected result:
df1:
Year City     Address       Total_Area Basement_Area
1989 Ottawa   156 Test Ottawa    280         130

I am struggling to find a correct way to do this. I made a function to extract filter values from df1 but can't get it to filter and give me the address
def filter_df(df,year,city,basement=0, floor_area=0, heated_floor_area=0,mp_storeys=0):
    if basement == 0:
        df = df[df[const.BASEMENT_COLUMN_df2_NAME].isnull()]
    else:
        df = df[(df[const.BASEMENT_COLUMN_df2_NAME]- floor_area).abs()< 10]

    filtered_df = df[(df[const.YEAR_COLUMN_df2_NAME] == year)]
    filtered_df = df[(df[const.ADDRESS_COLUMN_df2_NAME].str.contains(city))]
    filtered_df = df[(df[const.TOTAL_AREA_COLUMN_df2_NAME] - floor_area).abs()< 10]

    return filtered_df[0]

Please advise.

A: I'm sure there are more elegant solutions, but this one works.
I've added another entry to the dataframes for testing:
data1 = {'Year': [1989, 1990],
     'City': ['Ottawa', 'Chicago'],
     'Address': ['empty', 'empty'],
     'Total_Area': [280, 340],
     'Basement_Area': [130, 210]}
df1 = pd.DataFrame(data1)
data2 = {'Year': [1989, 1989, 1989, 1990, 1990],
     'Address(with city in it)': ['123 Test Ottawa', '146 Test Ottawa', '156 Test Ottawa',
     '190 Test Chicago', '201 Test Chicago'],
     'Total_Area': [179, 276, 283, 343, 338],
     'Basement_Area': [120, 140, 134, 210, 214]}
df2 = pd.DataFrame(data2)

Add City column to df2:
df2['City'] = [entry[2] for entry in df2['Address(with city in it)'].str.split(' ')]

Iterate over the rows in df1 and add the entry from df2 with the minimum absolute difference for Total_Area and Basement_Area.
for row in df1.iterrows():
    index = row[0]
    year, city, address, total_area, basement_area = row[1]
    df_compare = df2[(df2.Year == year) & (df2.City == city)]
    df1.loc[index, 'Address'] = df2.loc[
        (abs(df_compare[['Total_Area', 'Basement_Area']] - [total_area, basement_area])
        ).sum(axis=1).idxmin()]['Address(with city in it)']

It's more pythonic to use something like .map() for the last step, but I wasn't able to get this working.

A: I would use a cross join, or a join on a common feature (looks like you want the same year for example to match your closest neighbour), if you df2 is not too big (you can quickly have memory issue else).
Something like :
df = df1.reset_index().merge(
    df2,
    on="Year",
    how="inner",
    suffixes=("_df1", "_df2")
)

df["diff"] = abs(df["Basement_Area_df1"] - df["Basement_Area_df2"]) + abs(df["Total_Area_df1"] - df["Total_Area_df2"])

df.sort_values(["index", "diff"]).groupby("index").head(1)

Note that I'm using the index of df1 (that I get via reset_index() to keep only one match per df1 rows (hence the use of groupby / head).
If you df2 is too large to perform this kind of join, even if you add some features in your merge, you should take a look at the library recordlinkage which may help you with this kind of "inexact" join.


text:
Q: Looping subplot with two scales does not work Using Python, I try to create a plot that has one x-axis and two y-axes. This is not a problem, but somehow during looping only the curves in the host plot and the last curve in the par plot are shown. Below is my code.
files = ['File-01', 'File-02', 'File-03']
p = [None]*len(files)
d = [None]*len(files)

for i in xrange(len(files)):
    p[i] = Read(files[i])
    d[i] = Process(p[i])
    d[i].PlotI()

#some other coding

def PlotI(self):
    plt.figure('ParameterA and parameterB vs time')
    host = plt.subplot()
    par = host.twinx()
    host.plot(self.time, self.A, label = self.file,
              c = self.colour, linewidth =2, linestyle = '-')
    par.plot(self.time_hrs, self.B, label = self.file,
             c = self.colour, linewidth = 2, linestyle = ':')
    host.set_xlabel('Time [-]')
    host.set_ylabel('A [-]')
    par.set_ylabel('B [-]')
    plt.legend(loc = 'best', frameon=0)

So what I try to do is, plot for n different files parameter A and B (both vectors) in the same graph. Where the x-axis is shared and both parameters have their own y-axis.
Hopefully you can help me out!


text:
Q: ECS doesn't have enough free data blocks for docker image. How to provision enough volume/storage? I manage our ECS tasks with terraform and it's been all well and good but recently, I've run into this error when the task tries to fetch the image from ECR:
CannotPullContainerError: failed to register layer: devmapper: Thin Pool has 4143 free data blocks which is less than minimum required 4449 free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior

I'm a bit confused here on what to update. Our ECS service uses an EC2 launch type, but I think I have a fundamental misunderstanding of what's happening here. Reading https://docs.aws.amazon.com/AmazonECS/latest/developerguide/CannotCreateContainerError.html it seems like it's because the volume is too small but the AWS help page suggests docker prune. This confuses me since it was my understanding that the ECS task would have access to the full volume as a fresh start every time -- why would there be stale images/containers on the volume? Or is the page just suggesting that in cases where your ECS task might be fetching too multiple images, you should remove stale ones.
Other than that, I'm not sure how to proceed. Would increasing the ephemeral_storagein the aws_ecs_task_definition help here, or do I need to manage my own volume that's attached to the aws_launch_template instance that's tied to the aws_autoscaling_group that's tied to relevant aws_ecs_service

A: Just had to add this block to my aws_launch_template
resource "aws_launch_template" "instance" {
  ...
  block_device_mappings {
    device_name = "/dev/xvdcz"

    ebs {
      volume_size           = 50
      delete_on_termination = true
    }
  }

}


text:
Q: Uncaught Error when append data by Google Apps Script I have just learnt Google Apps Script a week to build a small online survey for my work.
Everything work fine, until I added 1 more question about taking Photo in the Index. Before that, it worked OK with 1 element taking Photo, but when I added 1 more element than an "Uncaught" error appear. I have tried to find this issue but it seems my English is not good enough to "google" right search key and didn't find any same error.
Please see my Index HTML code below: The error occurs when I added element with id "ds_q_Q06"
<!DOCTYPE html>

  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=10" />
  <meta http-equiv="Expires" content="0" />
  <meta name="msapplication-TileColor" content="#0072C6" />
  <title>GAS Question Templates</title>

    <base target="_top">

    <link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"  />

    <?!= include('CSS'); ?>
    <?!= include('JS'); ?>
    <?!= include('Json_data'); ?>
    <?!= include('Routing'); ?>

    <form class="form-survey test" id="mainForm">

        <input type="text" name="respID" id="respId" class="respId" ></input>
        <input type="text" name="currentPage" id="currentPage" class="currentPage" ></input>
        <input type="text" name="routing" id="routing" class="routing" ></input>

            1. Điểm bán:

            <select class="">
              <option disabled selected value>Vui lòng chọn...</option>
              <option value="Điểm bán mở cửa - Khảo sát TC">Điểm bán mở cửa - Khảo sát TC</option>
              <option value="Điểm bán không tìm thấy">Điểm bán không tìm thấy</option>
              <option value="Điểm bán thay đổi KD">Điểm bán thay đổi KD</option>
              <option value="Điểm bán đóng cửa">Điểm bán đóng cửa</option>
              <option value="Điểm bán mở cửa - Từ chối hợp tác">Điểm bán mở cửa - Từ chối hợp tác</option>
            </select>

              <input type="text" name="answer" class="hidden answer" ></input>

            Chụp hình

            <input type="file" accept="image/*" name="file" id="Q02_img"></input>

Upload

              <input type="text" name="answer" class="hidden answer" ></input>

            2. Ghi chú

            <textarea type="text" name="answer" class="answer" ></textarea>

            3. Tên điểm bán / Biển hiệu:

            <select class="">
              <option disabled selected value>Vui lòng chọn...</option>
              <option value="Đúng">Đúng</option>
              <option value="Sai">Sai - Cập nhật tên điểm bán mới</option>
            </select>

              <input type="text" name="answer" class="hidden answer" ></input>

            <input type="text" name="answer" class="answer" placeholder="Nhập tên điểm bán..." ></input>

            4. Địa chỉ:

            <select class="">
              <option disabled selected value>Vui lòng chọn...</option>
              <option value="Đúng">Đúng</option>
              <option value="Sai">Sai</option>
            </select>

              <input type="text" name="answer" class="hidden answer" ></input>

            <input type="text" name="answer" class="answer" placeholder="Nhập địa chỉ..." ></input>

            5. Single Question

                <input type="radio" name="ds_sa_Q01" id="Q01_C1" class="dsSingleChoice"></input>
                Câu 2

                <input type="radio" name="ds_sa_Q01" id="Q01_C2" class="dsSingleChoice"></input>
                Câu 3

                <input type="radio" name="ds_sa_Q01" id="Q01_C3" class="dsSingleChoice"></input>
                Câu 4

              <input type="text" name="answer" class="hidden answer" ></input>

      **

            6. Take Photo

            <input type="file" accept="image/*" id="Q06_img"></input>

Upload

            <input type="text" name="answer" class="answer" ></input>

**

            7. Drop Down Question

            <select class="">
              <option disabled selected value>------</option>
            </select>

              <input type="text" name="answer" class="hidden answer" ></input>

            8. Text / Search Question

            <input type="text" name="answer" class="answer" ></input>

            9. Text / Search Question

            <input type="text" name="answer" class="answer" ></input>

Previous Page

Next Page

Thank you for submitting!

    </form>

Here is my app script that input data when click on submit button
function doGet() {
  return HtmlService.createTemplateFromFile('Index').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).addMetaTag('viewport', 'width=device-width, initial-scale=1');
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

function uploadFiles(imageFile) {
   //var folderId = getFolderID("App_Img");

    var blob = Utilities.newBlob(imageFile.bytes, imageFile.mimeType, imageFile.filename);

    var file = DriveApp.getFolderById("ID_FOLDER");

    try {
      var child = file.getFoldersByName(imageFile.folderName).next();
    }
    catch(e){
      var child = file.createFolder(imageFile.folderName);
    }

    child.createFile(blob);

    return {fileURL:file.getUrl(),fileDir:imageFile.fileDir};
}

function getFolderID(folderName)
{
  var folders = DriveApp.getFolders();
  while (folders.hasNext()) {
   var folder = folders.next();
   if(folder.getName() == folderName)
   {
    return folder.getId();
   }
 }
}

**
function inputData(formSurvey){

  var url = "URL_GOOGLE_SHEETS";
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Sheet1");
  Logger.log(ws.getName());
  console.log(ws.getName());

  var data = [];
  for (var i = 0; i<formSurvey.answer.length; i++){
    data.push(formSurvey.answer[i]);
  }

  Logger.log(data.join(";"));
  console.log(data.join(";"));
  //ws.appendRow(data);

}
**

Here is my JS when click Submit button (last page)
function endSurvey(){
    $(".survey-loading").show(0).delay(5000).hide(0);
    google.script.run.withSuccessHandler(submitSuccess).inputData($("#mainForm")[0]);

  }

  function submitSuccess(){
    $(".survey-done").toggleClass("hidden",false);
  }

The error is quite weird , without any more information.

Please help me on this.

A: I've faced a similar situation with an "uncaught" console error after running some specific server side function. After a day of searching where the problem is, in my case It was caused by running the google app script from one account while logged in chrome to another one.
Once I changed and opened the app from the same account as logged in to Chrome, the problem disappeared.


text:
Q: proof that $\rho,\psi \in V^{*}$ s.t. $\rho(v)\psi(v) = 0, \forall v \in V,$ implies $\rho = 0$ or $\psi = 0$ I'm in the middle of revising for an exam, an this question came up on an old midterm that the professor gave us as an example of what to expect.
My attempt to show that; given $\rho,\psi \in V^{*} \textrm{ s.t. } \rho(\textbf{v})\psi(\textbf{v}) = 0, \forall \textbf{v} \in V\Rightarrow \rho = 0 \textrm{ or } \psi = 0.$ is as follows:
First, note that it is logically equivalent to prove that given
$\rho,\psi \in V^{*} \textrm{ s.t. } \rho(\textbf{v})\psi(\textbf{v}) = 0, \forall \textbf{v} \in V$ and $\rho(\textbf{v}) \neq 0 \Rightarrow \psi = 0$.
So with this in mind we let $\textbf{x} \in V$, and observe that $\rho(\textbf{x}),\psi(\textbf{x}) \in F$, where $F$ is a field, since $\rho: V \rightarrow F$ and $\psi: V \rightarrow F$.  Thus, since $\rho(\textbf{x}) \neq 0$, we know that $\exists \big(\rho(\textbf{x})\big)^{-1} \in F$ s.t. $\rho(\textbf{x})\big(\rho(\textbf{x})\big)^{-1} = \big(\rho(\textbf{x})\big)^{-1}\rho(\textbf{x}) = 1_{F}.$  Hence:
\begin{align}
0 &= \big(\rho(\textbf{x})\big)^{-1}0 = \big(\rho(\textbf{x})\big)^{-1}\big(\rho(\textbf{x})\psi(\textbf{x})\big) \\
&= \Big(\big(\rho(\textbf{x})\big)^{-1}\rho(\textbf{x})\Big)\psi(\textbf{x}) \\
&= (1_{F})\psi(\textbf{x}) \\
&= \psi(\textbf{x}).
\end{align}
It follows that $\psi: V \rightarrow \{0\} \hspace{4.5in}\square$
I explained my solution to the instructor and they said that it doesn't work, but didn't have time to explain why.  Help?!

A: The argument you give does nothing: you are showing that if $\rho(x)\ne0$, then $\psi(x)=0$; that's an obvious conclusion from $\rho(x)\psi(x)=0$. Note in particular that your argument doesn't use linearity at all.
Here is one way of doing it. Let $x,y\in V$. Then, since $\rho(x)\psi(x)=\rho(y)\psi(y)=0$,
$$\tag{1}
0=\rho(x+y)\psi(x+y)=\rho(x)\psi(y)+\rho(y)\psi(x).
$$
Suppose that $\psi\ne0$. This means that there exists some $x_0\in V$ with $\psi(x_0)\ne0$. Note that by hypothesis, $\rho(x_0)=0$. Then, from $(1)$, we get
$$
\rho(y)=-\frac{\rho(x_0)}{\psi(x_0)}\,\psi(y)=0.
$$
As this can be done for arbitrary $y$, we get that $\rho(y)=0$ for all $y\in V$, i.e. $\rho=0$.

A: Your logic is not very clear. The use of $\exists$ and $\forall$ is not precise in what you write. Anyway if $Z=\ker \rho$ and $\rho$ is non-zero then there is $u_0$ so that $\rho(u_0)=1$. Then for every $z\in Z$ the condition on the product means that:
 $$ 0= \psi(u_0+z) \rho(u_0+z) = \psi(u_0+z)(1+0)=\psi(u_0+z)$$
Now use linearity to show that $\psi\equiv 0$.


text:
Q: Setting the working directory of a Java Applet I have two signed Jars, a.jar and b.jar.
a.jar is launched as an applet inside the browser and b.jar is in Appdata/locallow/xyz (Vista). a adds b to it's classpath and calls some functions of b.jar. So far so good. Now b unpacks some dlls into the working directory and depends on them. It must be the working directory, because the dlls reference each other, so no alternative directory is possible.
The bad thing is, that the working directory (user.dir) in Firefox is "c:\program files\mozilla firefox"... So my application works as long as the user has admin-rights. But as soon as a normal user launches the applet, it crashes as the application wants to unpack the dlls. And it really isn't nice to have application-dlls in the directory of Firefox anyway...
A solution would be to set the working directory to the dir, where b.jar is. Is this possible in any way?

A: The applet approach is not well suited for native libraries.
I would suggest considering Java Web Start which contains support for DLL's directly.  It was reworked in Java 6 to work well with applets too.


text:
Q: Null instead of None when interpretting JSON? Im trying to post JSON data to a remote host.
When I open the file and use the json.load function from the imported json library it converts all the null values to None, all the true values to True, and all the false values to False, to retain the pythonic dictionary format.
Whereas when I open the file using the read() method it retains the original json values because the entire file is interpreted as a string. This would be fine if the data didn't lose its dictionary-like properties that json.load() would otherwise offer.
I have a hunch that the remote host cannot interpet the converted values, and sends me back a 400 response with a malformed text error.
Is there a function or method for loading JSON data so boolean and none values aren't pythonified? Or maybe something can be done when posting the request data?
import requests
import json

session = requests

key='REDACTED'

with open('create.json', encoding='utf-8') as json_file:
    #DATA = json.load(json_file)
    DATA = json_file.read()

HEADERS={
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {0}'.format(key)
    }

URL='https://api.digitalocean.com/v2/droplets'

x = session.post(url=URL,headers=HEADERS,data=DATA)
print(x.status_code)
print(json.loads(x.text))

A: This is a misunderstanding of serialization. Serialization is not a python specific subject as it works similarly in different languages.
The idea is simple. Convert object's in memory representations into a format adequate to a file; usually to later be read back again.
Python Json Module
The python json module handles serialization and deserialization to/from json format, via the dumps and loads functions respectively.
Suppose a simple json file /file.json
{
  "name": "Pedro",
  "awesome": true
}

Note. Values are essentially Javascript like values (hence the JavaScript Object Notation name).
For this to be in any use in python (ie. if pedro['awesome']: # do something) the values most be converted, deserialized, to a python like format.
import json

with open('file.json', 'r') as f:
    data = f.read()
    pedro = json.loads(data)     # this deserializes the JSON data

print(pedro)
print(pedro['awesome'] == True)  # this only works because it was deserialized

data = json.dumps(pedro)         # this serializes the python object to JSON
print(data)

Running this script yields:
{'name': 'Pedro', 'awesome': True}
True
{"name": "Pedro", "awesome": true}


text:
Q: Are there any Simpler functions to fetch particular HTML node from the given input element? Say My input is  Content  which is a sample and the tags may vary dynamically. Can I get the following outputs using Agility pack?
Output :
 Tag - <td id="id34" class="dfg">
 ID- id34
 Class - Dfg

EDIT: By parsing the input string, I need to fetch the parameters . This can be achieved by writing a method .


text:
Q: Bind cache Django class based view response with parameter from request I want to cache my API response and bind it with parameter that is present in GET request.
The request looks like this:
GET /products?producent=some_company

Here is my simplified class:
class ProductsListCreate(generics.ListCreateAPIView):

    def list(self, request, *args, **kwargs):
        producent = request.query_params.get("producent")
        cached_response = cache.get(f"response-products-{producent}", None)
        if not cached_response:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            serializer = self.get_serializer(page)
            response = self.get_paginated_response(serializer.data)

            cache.set(f"response-products-{producent}", response , timeout=20)
            return response

        return cached_response

But when I'm trying to cache the response I receive error:
django.template.response.ContentNotRenderedError: The response content must be rendered before it can be pickled.

Do you have any tips for me? I was searching here https://docs.djangoproject.com/en/3.2/topics/cache/ when I was trying to figure out this. At first I tried the approach with @cache_page but it won't allow me to use the parameter from request, so I guess the way to go is Low level cache API.

A: The error message is actually pretty descriptive. You must call render() on the response before attempting to pickle it into a cacheable format. The problem is: that will lead you on a rabbit hole to deconstruct the response and reconstruct from the cached data. IMO, you'd be better off caching the queryset. Nevertheless, this is what it would look like:
class ProductsListCreate(generics.ListCreateAPIView):

    def list(self, request, *args, **kwargs):
        producent = request.query_params.get("producent")
        response_triple = cache.get(f"response-products-{producent}", None)
        if not response_triple:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            serializer = self.get_serializer(page)
            response = self.get_paginated_response(serializer.data)

            response.render()

            if not response.status_code >= 400:
                # django 3.0 has no .items() method, django 3.2 has no ._headers
                if hasattr(response, '_headers'):
                    headers = response._headers.copy()
                else:
                    headers = {k: (k, v) for k, v in response.items()}
                response_triple = (
                    response.rendered_content,
                    response.status_code,
                    headers
                )
                cache.set(f"response-products-{producent}", response_triple, timeout=20)
        else:
            # build smaller Django HttpResponse
            content, status, headers = response_triple
            response = HttpResponse(content=content, status=status)
            for k, v in headers.values():
                response[k] = v
        if not hasattr(response, '_closable_objects'):
            response._closable_objects = []

        return response

Taken from: https://github.com/chibisov/drf-extensions/blob/ecdf3a95d7f18ccf9cffa55809635c3715179605/rest_framework_extensions/cache/decorators.py#L63


text:
Q: How to use noitemsep with roman numerals in enumerate The following code works
\documentclass[12pt]{article}
\usepackage{enumerate}          % line 2
%\usepackage{enumitem}          % line 3

\begin{document}
\begin{enumerate}[(i)]          % line 6
%\begin{enumerate}[noitemsep]   % line 7
\item one
\item two
\end{enumerate}
\end{document}

and gives me something like

i. one
ii. two

But if I want to make the separation smaller, I would like to use enumitem package (following Wikibooks). However, I cannot use [(i)] when I use package enumitem. How can I get both of these features.

A: I prefer the Phelype Oleinik's way, using the enumitem package:
You can use noitemsep as an environment option:
\documentclass[12pt]{article}
%\usepackage{enumerate}          % line 2
\usepackage{enumitem}          % line 3

\begin{document}
   \begin{enumerate}[label=(\roman*),noitemsep]          % line 6
      \item one
      \item two
    \end{enumerate}
\end{document}

A: With the [shortlabels] option, the enumitem package allows to write the very simple and user-friendly syntax of the enumerate package.
\documentclass[12pt]{article}
\usepackage[shortlabels]{enumitem}

\begin{document}
   \begin{enumerate}[(i),noitemsep]
      \item one
      \item two
    \end{enumerate}
\end{document}


text:
Q: Make Web push notification work using webview in a native android app? I have a website which is responsive and push notification feature enabled. In my native android app, if i load my website in a WebView, then the pop up which usually comes in chrome/firefox to ask if user wants to allow push notification or not, doesn't shows up in WebView. And obviously the WebView won't support the same web push notification for the app. I know how to implement GCM or FCM in app to enable mobile push, but i wanted to know if it possible just to club the web push notification with android webview so that it would work in my app as it is working in chrome/firefox etc.
What I tried: After digging deeper into this, I finally concluded that as android WebView doesn't support Push Api (with the help of caniuse.com), clubbing of web push with mobile push using WebView is not possible as of now. Am I right? Or is there any app which already does this? Is it possible somehow?

A: Ow, of course this is possible!
I easily implemented push web notifications from one signal in my webview App using crosswalk.
Uses crosswalk, extends Main activity to XWalkactivity
Put this on on create:
OneSignal.startInit(this)
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .unsubscribeWhenNotificationsAreDisabled(true)
                .init();

Yeah, you will have web push notifications working!!!

A: As I'm aware, it's not possible using only WebView .
The solution that worked for me was to find whether the website you want to display in the WebView uses WebSockets. If yes, the notification will probably be available in the according WebSocket communication. The workflow is following:

*

*Determine WebSocket on the website. You can use Firefox "Inspect Code" and in "Network" tab filter out only WebSocket entries.

*You can test connection to ws via various tools. Simple-WebSocket-Client for Firefox or command line tool. Simply provide URI to your WebSocket (ws://domain.example/ws).

*Implement WebSocket client in your application. There's been different posts on how to do that. I've used this lib to make it nice and clean.

*Now you are receiving messages from server, such as notifications.

*Parse them and do whatever you want.


text:
Q: how to call a firebase sample cloud function from unity? The sample function that firebae creates is this below. Now i want to call it from unity. added and configured firebase in unity already.
/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || 'Hello World!';
  res.status(200).send(message);
};

now i am not sure that to call a function do i need authentication? if yes how should i call the function?
i used this code to call the function. My function name is testunity and i have posted the code snipped of cloud function above.
 System.Threading.Tasks.Task<string> Start()
    {
        FirebaseFunctions functions = FirebaseFunctions.GetInstance(projectId);

        Debug.Log("Calling");
        var function = functions.GetHttpsCallable("testunity");
        return function.CallAsync("helloWorld").ContinueWith((task) => {
            return (string)task.Result.Data;
        });
    }

A: Your client is using a callable type function, but your backend is not.  If you want to use a callable function from the client, you will need to implement a callable function on the backend (not an HTTP function has you have now).  See the documentation for details:
https://firebase.google.com/docs/functions/callable
Your callable function will look more like this:
exports.testunity = functions.https.onCall((data, context) => {
  // ...
});


text:
Q: Realm where clause returns 0 even if data is present in realmDB Im using where clause in IntentService in android ,If I use the where clause the first 7 or 8 times it gives me the desired output but after certain time it fails and gives 0 for the result
 Realm realm = Realm.getInstance(ApplicationController.getInstance().getRealmConfig(Constants.SCHEMA_LIVE));
            RealmResults<RContactDTO> localContacts = realm.where(RContactDTO.class).equalTo("operationType", HttpOperation.PUT.name()).findAll();
            Utils.Log("update contact count ::: " + localContacts.size(), Utils.LogType.DEBUG);
            ArrayList<ContactDTO> contactList = new ArrayList<ContactDTO>();
            RContactDTO rContactDTO = null;
            for(RContactDTO rContact : localContacts){
                contactList.add(new ContactDTO(rContact));
            }

I have checked the actual data by exporting the realmDB.

A: I had the same issue in Swift. Realm have some issue with auto refresh.
Use
realm.refresh()  before doing your clause.

A: In an IntentService, you're on a looper thread that doesn't loop. So that means your Realm cannot auto-update on an IntentService's thread, and it can't wait for changes either. So the workaround is to either use a normal thread and use waitForChange() instead of an IntentService, or close the Realm when you no longer need it for an operation and then re-open it with getDefaultInstance().


text:
Q: Memory access conflict with structs and observer pattern I'm implementing an Observer design pattern on a Struct model object. The idea is that I will pass my model down a chain of UIViewController and as each controller modifies it, previous controllers will also be updated with changes to the object.
I'm aware this problem could be solved by using a class instead of struct and modifying the object directly through reference, however I'm trying to learn more about using structs.
struct ModelObject {
    var data: Int = 0 {
        didSet {
            self.notify()
        }
    }
    private var observers = [ModelObserver]()

    mutating func attachObserver(_ observer: ModelObserver){
        self.observers.append(observer)
    }

    private func notify(){
        for observer in observers {
            observer.modelUpdated(self)
        }
    }
}

protocol ModelObserver {
    var observerID: Int { get }
    func modelUpdated(_ model: ModelObject)
}

class MyViewController : UIViewController, ModelObserver {
    var observerID: Int = 1
    var model = ModelObject()

    override func viewDidLoad() {
        self.model.attachObserver(self)
        self.model.data = 777
    }

    func modelUpdated(_ model: ModelObject) {
        print("received updated model")
        self.model = model //<-- problem code
    }
}

Simply put, my model object notifies any observer when data changes by calling notify().
My problem right now is memory access: when data gets set to 777, self.model becomes exclusively accessed, and when it calls notify which calls modelUpdated and eventually self.model = model, we get an error:
Simultaneous accesses to 0x7fd8ee401168, but modification requires exclusive access.

How can I solve this memory access issue?

A: If you're observing "a thing," then that "thing" has an identity. It's a particular thing that you're observing. You can't observe the number 4. It's a value; it has no identity. Every 4 is the same as every other 4. Structs are values. They have no identity. You should not try to observe them any more than you'd try to observe an Int (Int is in fact a struct in Swift).
Every time you pass a struct to a function, a copy of that struct is made. So when you say self.model = model, you're saying "make a copy of model, and assign it to this property." But you're still in an exclusive access block because every time you modify a struct, that also makes a copy.
If you mean to observe ModelObject, then ModelObject should be a reference type, a class. Then you can talk about "this particular ModelObject" rather than "a ModelObject that contains these values, and is indistinguishable from any other ModelObject which contains the same values."


text:
Q: jQuery autocomplete doesn't want to send particular POST data I'm trying to add an item (fund). The autocomplete succeeds in showing all the funds. It should retrieve the fund.id corresponding to that 'fund'. If I could get another set of eyes on this, it would be greatly appreciated...
Just to be clear: I'm not getting a specific error. My view just redirects if there is no 'fund' in the POST. I'm just trying to figure out why my autocomplete isn't posting the fund POST value' (fund.id).
-- Thank you advance
Template:

...
<form method="POST" action="/profile/edit/">
 {% csrf_token %}
      <input type="hidden" name="fund" id="id_fund" />

           Fund
           <input id="id_omnibox" name="omnibox" placeholder="Enter a fund name or search for an existing..." type="text" />

           Allocation
           $
           <input id="id_amount" name="amount" type="text" placeholder="Enter amount" />

      <button class="add" type="submit" name="add_position">Add</button>
 </form>

add_fund_autocomplete.js:
$(document).ready(function() {
    $.get('/autocomplete/funds/', function(data) {
        var completions = new Array();
        var dict = JSON.parse(data, function(key, value) {
            completions.push(key);
            return value;
        });
        $('#id_omnibox').autocomplete({
            source: completions,
            minLength: 2,
            select: function(event, ui) {
                $('#id_fund').val(dict[ui.item.value]);
            }
        });
    });
});

(autocomplete)View:
@login_required
def funds(request):
    funds = Fund.objects.exclude(name='Placeholder')
    result = {}
    for fund in funds:
        result[fund.name] = str(fund.id)
    return HttpResponse(json.dumps(result))

For example:
Adding the fund     Hoth Ltd with an amount of $123.
Hoth Ltd's fund.id should be 1.
POST data
POST
---------------------------------------------------------
Variable               Value
---------------------------------------------------------
fund                   u'' #empty? :\
csrfmiddlewaretoken    u'436f77eb2023043be2f5242bb0443d80'
omnibox                u'Hoth Ltd'
amount                 u'123'
add_position           u'' #Just a trigger used in my view

A: The variable dict is undefined when the select callback function is called.
You can just use ui.item.value.


text:
Q: How to bound this complex number from below? I am doing an $\epsilon-\delta$ proof ($z \rightarrow i, f(z) \rightarrow \infty$) and currently have the absolute value $$|f(z)|=\left|\frac{z-1}{z^2+1}\right|$$ and I wish to make a statement about $|z-i|$ I have made the fraction above into $$\frac{|z-1|}{|z-i||z+i|}$$ but I cannot proceed. Any tips.

A: Actually, you are almost done. Consider this:
$$\frac{|z-1|}{|z-i||z+i|} \overset{(\text{triangle eq.})}{\geq} \frac{|z-1|}{|z-i|\cdot(|z|+|i|)} = \frac{|z-1|}{|z|+1} \cdot \frac{1}{|z-i|}$$
Let's say you have $K \in \mathbb{R}$. Now you need to choose an appropriate $\delta$ so that $|f(z)| \gt K$ $\forall z \in B_\delta(i)$. Suppose you have a $z \in B_\delta(i)$, then $$\frac{1}{|z-i|} \gt \frac{1}{\delta}$$
which is very good (the expression gets very big for small $\delta$), because now you only need to see that
$$\frac{|z-1|}{|z|+1} = \frac{|z-i-(1-i)|}{|z|+1} \overset{(\text{rev. triangle eq.})}{\geq} \frac{\lvert|z-i|-|1-i|\rvert}{|z|+1} = \frac{\lvert|z-i|-\sqrt2\rvert}{|z|+1}$$
doesn't get too small.
From here it should be not too hard to choose a $\delta$.


text:
Q: static listview check a checkbox on populating based on a values i want to ask how i can check a checkbox in a listview based on the values of a entry column.
Sadly after some hours of google i couldn't figure out a solution that fits the bill. Since most seem to be based on Windows Forms.
Here is the current code:
        SDVVersion.Text = SDVMMVersion;
        SMAPIVersion.Text = SDVMMSettings.SmapiVersion;
        // Createing  columns
        Gtk.TreeViewColumn CBColumn = new Gtk.TreeViewColumn();
        CBColumn.Title = "Active";

        Gtk.CellRendererText CBCell = new Gtk.CellRendererText();
        CBColumn.PackStart(CBCell, true);

        Gtk.TreeViewColumn NameColumn = new Gtk.TreeViewColumn();
        NameColumn.Title = "Name";

        Gtk.CellRendererText ModsNameCell = new Gtk.CellRendererText();
        NameColumn.PackStart(ModsNameCell, true);

        Gtk.TreeViewColumn AuthorColumn = new Gtk.TreeViewColumn();
        AuthorColumn.Title = "Author";

        Gtk.CellRendererText AuthorCell = new Gtk.CellRendererText();
        AuthorColumn.PackStart(AuthorCell, true);

        Gtk.TreeViewColumn VersionColumn = new Gtk.TreeViewColumn();
        VersionColumn.Title = "Version";

        Gtk.CellRendererText VersionCell = new Gtk.CellRendererText();
        VersionColumn.PackStart(VersionCell, true);

        Gtk.TreeViewColumn DescColumn = new Gtk.TreeViewColumn();
        DescColumn.Title = "Description";

        Gtk.CellRendererText DescCell = new Gtk.CellRendererText();
        DescColumn.PackStart(DescCell, true);

        // Add the columns to the TreeView
        activeMods.AppendColumn(CBColumn);
        activeMods.AppendColumn(NameColumn);
        activeMods.AppendColumn(AuthorColumn);
        activeMods.AppendColumn(VersionColumn);
        activeMods.AppendColumn(DescColumn);

        activeMods.Model = new ListStore(typeof(string), typeof(string), typeof(string), typeof(string), typeof(string));
        // the column checkbox is created
        Gtk.CellRendererToggle valueCb = new CellRendererToggle();
        CBColumn.PackStart(valueCb, true);

        CBColumn.AddAttribute(valueCb, "bool",0);
        NameColumn.AddAttribute(ModsNameCell, "text", 1);
        AuthorColumn.AddAttribute(AuthorCell, "text", 2);
        VersionColumn.AddAttribute(VersionCell, "text", 3);
        DescColumn.AddAttribute(DescCell, "text", 4);

    }

    internal void RefreshTreeView()
    {
        ModStore.Clear();

        foreach (ModInfo Mod in Mods) // Mods = the modstore, modInfo mod = the json tempalte from where it is read
        {
            ModStore.AppendValues(Mod.IsActive.ToString(), Mod.Name, Mod.Author, Mod.Version);
if(Mod.IsActive == true)
//checkbox = checked

        }
    }

i would appreciate any help offered from links to examples to code examples itself.
~yuuki


text:
Q: kubectl command to get list of pods running on k8s master node Is it possible to get a list of pods that are Running on matser from kubectl?
i have tried this
kubectl get pods -o wide --sort-by="{.spec.nodeName}"

but this doesnt say whether the node is master or worker

A: As mentioned in the overview:

A Pod always runs on a Node.
A Node is a worker machine in Kubernetes and may be either a virtual or a physical machine, depending on the cluster. Each Node is managed by the Master

So by definition (even if it runs on the same physical machine than the master), any node is on a "worker machine"

Only kubectl get node does display a ROLE:
vonc@voncvb:~/.kube$ kubectl get node -o wide
NAME           STATUS    ROLES     AGE       VERSION   EXTERNAL-IP   OS-IMAGE                 KERNEL-VERSION
serv0.server   Ready     <none>    18d       v1.9.7    <none>        SUSE CaaS Platform 3.0  docker://x.y.z.z
serv1.server   Ready     <none>    18d       v1.9.7    <none>        SUSE CaaS Platform 3.0   docker://x.y.z.z
serv2.server   Ready     <none>    18d       v1.9.7    <none>        SUSE CaaS Platform 3.0   docker://x.y.z.z
servm.server   Ready     master    18d       v1.9.7    <none>        SUSE CaaS Platform 3.0   docker://x.y.z.z
                         ^^^^^^^


text:
Q: I'm creating a calculator app by following the CS193p lectures just released for Swift. How can I implement Pi as both an operand & and operation? I'm trying to do the assignments that are issued in the lectures but of course... I'm stuck on the first assignment and I hate moving forward without being able to solve something.
I'm having issues implementing π as both an operation and and operand. I have it working as an operation(all it does is return the value of π). E.g. ' π Enter π Enter + ' results in 6.28... but if I say ' π Enter π Enter + π Enter ÷ ' it results in 1.0 when it should be 2.0
I've searched StackOverflow and found nothing aside from Objective-C solutions.
Any help is appreciated.
Here is the action fired in the ViewController when you tap an operation:
        @IBAction func operate(sender: UIButton) {
                let operand = sender.currentTitle!
                if (userIsInTheMiddleOfTypingANumber){
                    enter()
                }
                if let operation = sender.currentTitle{
                    if let result = brain.performOperation(operation){
                        displayValue = result
                    } else {
                        displayValue = 0
                    }
                }
            }

Here is the code from the model:
        private enum Op: Printable  {
    case Operand(Double)
    case UnaryOperator(String, Double -> Double)
    case BinaryOperator(String, (Double, Double) -> Double)
    case ConstantOperator (String, Double)

    var description: String {
        get {
            switch self {
            case .Operand(let operand):
                return "\(operand)"
            case .UnaryOperator(let symbol, _ ):
                return symbol
            case .BinaryOperator(let symbol, _ ):
                return symbol
            case .ConstantOperator(let symbol, _ ):
                return symbol
            }
        }
    }
}
func performOperation(symbol: String) -> Double?  {
    if let operation = knownOps[symbol]{
        opStack.append(operation)
    }
    return evaluate()
}

private var opStack = [Op]()
private var knownOps = [String:Op]()

init(){
    func learnOp(op: Op){
        knownOps[op.description] = op
    }

    learnOp(Op.BinaryOperator("✕", *))
    //knownOps["✕"] = Op.BinaryOperator("✕", *)
    knownOps["÷"] = Op.BinaryOperator("÷") {$1 / $0}
    knownOps["+"] = Op.BinaryOperator("+", +)
    knownOps["−"] = Op.BinaryOperator("−") {$1 - $0}
    knownOps["√"] = Op.UnaryOperator("√", sqrt)
    learnOp(Op.UnaryOperator("cos", cos))
    learnOp(Op.UnaryOperator("sin", sin))
    learnOp(Op.ConstantOperator("∏", M_PI))
}

private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]){
    if !ops.isEmpty {

        var remainingOps = ops
        let op = remainingOps.removeLast() //get the first op off the stack

        switch op {
        case .Operand(let operand):
            return (operand, remainingOps)

        case .UnaryOperator(_, let operation):
            let operationEvaluation = evaluate(remainingOps)
            if let operand = operationEvaluation.result {
                return(operation(operand), operationEvaluation.remainingOps)
            }

        case .BinaryOperator(_ , let operation):
            let op1Eval = evaluate(remainingOps)
            if let op1 = op1Eval.result{
                let op2Eval = evaluate(op1Eval.remainingOps)
                if let op2 = op2Eval.result {
                    return (operation(op1, op2), op2Eval.remainingOps)
                }
            }

        case .ConstantOperator(_, let value):
            return(value, remainingOps)

        }
    }
    return(nil, ops)
}
func evaluate() -> Double? {
    let (result, remainder) = evaluate(opStack)
    println("\(opStack) = \(result) with \(remainder) left over.")
    return result
}

Note: I'm trying to complete the assignment's required tasks given the structure the instructor wants us to follow. My attempt here (trying to add ∏ as an operator) works in certain situations but not all...
Here is what the assignment says about this task:
"The value of π is available via the expression M_PI. E.g. let x = M_PI. You can think of π as an operand or you can think of it as an operation (i.e. a new kind of operation that takes no arguments off the stack but returns a value). Up to you. But, either way, it'd be nice to be able to add other constants to your Calculator with a minimum of code."
I tried the operand approach but I was breaking the MVC paradigms so I stopped.

A: If you press  π and enter then you are effectively putting pi in the opStack twice.  So you are actually doing  π  π  π  π +  π  π ÷.  Does that make sense?  In order to add pi to itself, you'd push π π +.  If you wanted to add pi together and then divide by pi, it would be π π + π ÷.


text:
Q: Present vs Past in Cosmological time My question is in regard to "seeing back in time" when observing objects in space. I understand the concept that light takes a certain amount of time to reach the earth and we can determine the distance to a very distant object via red shift. Certainly this allows us to see and understand how objects were and the progression of the universe. However aren't we blind as to how the universe looks like at the present. If an object is a million light years away we have no idea what it's present state is. In fact we have no idea what it's state was 500,000 light years ago. If the universe presents nothing but the past how can we be sure what is really happening right now in the present?
Maybe this has a simple answer but it has me stumped.

A: We assume that the universe is the same everywhere. This assumption is known as the cosmological principle. If this assumption is correct then distant regions of the universe right now look like the near regions, and the differences that we see are only due to time.
The cosmological principle is just an assumption, but it is a reasonably well founded one. When we look out at the universe we see it is the same in all directions. The only way this can be true is if either the universe is the same everywhere or we just happen to be right at the centre. The latter seems unlikely as it would be a remarkable coincidence that the planet we live on just happened to be in the centre of the universe, so we assume the former is true i.e. the universe is the same everywhere.

A: Your worries about our knowledge of the Universe is quite common, and can be categorized under "How can we be sure that things are like this?".
In essence, it's the same question as "How can we be sure that this stone falls to the ground when I let go of it?".
We model the world
That answer to both questions is "We can't". But through experience we can convince ourselves that this is probably how it is, and through constant experimentation and challenging of our current understanding and perception of the world, we can verify our models and theories (or perhaps at some point falsify them, in which case our worries were justified, and we must start over).
In physics, one can never be sure about anything. But at some point, we can be so convinced that, for all practical purposes, it doesn't make sense to keep being suspicious. For instance, you shouldn't worry that the stone will fly upwards and hit your face when you let it go. But that doesn't mean that the law of gravity isn't questioned anymore; indeed it is (sometimes perhaps a bit too much, in my opinion).
So, to answer your question: We "know" what's going on in a galaxy far, far away today, even though we see it in the past, because we have constructed a model for the Universe which numerous observations over the past centuries have verified, and which allows us to make sensible predictions about things we cannot hold in our hands.

To address your specific concern about where an observed has moved since it emitted the light we see, consider first the Andromeda galaxy: Its distance is $d = 2.5$ million lightyears (Mlyr) and it approaches us at $v\sim100\,\mathrm{km}\,\mathrm{s}^{-1}$. In the $t = 2.5$ million years (Myr) that has passed since it emitted the light we see today, it has hence traveled $d = v t \simeq 900\,\mathrm{lyr}$, or 0.04% of its current distance, an insignificant amount.
More distant galaxies have traveled farther since they emitted the light we see (though away from us rather than toward us), and sufficiently distant galaxies are so far away that we will never be able to see the light they emit today. But that doesn't really matter, because by observing galaxies at various distances — and hence at various times throughout the history of the Universe — we can say something meaningful about the typical (as well as the less typical) fate of galaxies.
So I guess the anser to your question is this; we don't know, and don't really care, about what has happened to some particular distant galaxy, since the time it emitted the light we see. What we do care about, and actually know, it what happens "on average" to galaxies.

A: To observe the universe at the present time, we look not far away- just in our local neighborhood of galaxies that are no more than a few million light-years away. This furnishes us with a baseline against which we chart differences between what's near (and in our recent past) and what's far (and hence in our deep past).

A: Just to say you've got some good answers here, and it's mainly about lack of complete certainty but we make reasonable assumptions about what is likely to be going on. It's not so very different from everyday life. I don't know for sure what my cat is doing right now (it's not in the room with me at the moment) but I'm pretty sure it is not peeling a banana or riding on a bike. Very likely it is asleep.
However, when it comes to the universe at large there is an interesting observation to make, which is that we receive light from only a tiny fraction of the whole. We gather information arriving at Earth from our past light cone, and that's it: a tiny sliver from the whole history of the cosmos. You can often find statements referring to 'the observable universe' and then the speaker goes on to describe things way way out of our past light cone, sometimes without realising that they are doing so. It's a reasonable hypothesis that a galaxy we can see at a large red shift has, since then, evolved in a similar way to other galaxies of similar make up. But such a hypothesis is only good to the extent that there is uniformity as opposed to richness and variety in the universe. In practice the universe combines both. It is not a desert, but neither is it a jungle.


text:
Q: Same logic but have different result with JOptionPane and JFrame Code 1:
public static JFrame frame = null;
public myClass(JFrame frame1)
{
    initComponents();
    frame = frame1;
    String result = JOptionPane.showInternalInputDialog(
        frame.getContentPane(), "Sample");
}

Code 2:
public static JFrame frame = null;
public myClass(JFrame frame1)
{
    initComponents();
    frame = frame1;
    sampleMethod();
}

public static void sampleMethod()
{
    String result = JOptionPane.showInternalInputDialog(
        frame.getContentPane(), "Sample");
}

I wanted the result in Code 1 but the code must look like Code 2. Why do they have different results?

A: If both pieces of code are relevant, then it is impossible that results are different.
So, this means that the code you provided is not complete enough or you are not making clear what you mean with "different result".
And my guess is that you are creating multiple instances of myClass, at the same time? I would suggest to try this: (without all that static)
public JFrame frame = null; // static removed
public myClass(JFrame frame1)
{
    initComponents();
    frame = frame1;
    sampleMethod();
}

public void sampleMethod() // static removed
{
    String result = JOptionPane.showInternalInputDialog(
        frame.getContentPane(), "Sample");
}


text:
Q: How to compile kernel-module-imx-gpu-viv? I am not able to compile the following kernel module https://github.com/Freescale/kernel-module-imx-gpu-viv/tree/upstream/6.2.4.p1.2/kernel-module-imx-gpu-viv-src for my IMX6Q board.
What i have done so far is :

*

*Downloaded the sources from the git repo above in a separate directory

*Modified the Makefile to set the correct path to the kernel sources KERNEL_SRC i am building (3.14.52) with :

Makefile :
obj-m := galcore.o
SRC := $(shell pwd)
KERNEL_SRC := /path/to/kernel_imx/

all:
        $(MAKE) -C $(KERNEL_SRC) M=$(SRC)/kernel-module-imx-gpu-viv-src AQROOT=${PWD}/kernel-module-imx-gpu-viv-src
        cp $(SRC)/kernel-module-imx-gpu-viv-src/Module.symvers $(PWD)
        cp $(SRC)/kernel-module-imx-gpu-viv-src/modules.order $(PWD)

modules_install:
        $(MAKE) -C $(KERNEL_SRC) M=$(SRC)/kernel-module-imx-gpu-viv-src modules_install

clean:
         rm -f *.o *~ core .depend .*.cmd *.ko *.mod.c
         rm -f Module.markers Module.symvers modules.order
         rm -rf .tmp_versions Modules.symvers

*compiled with : make ARCH=arm CROSS_COMPILE=/path/to/buildroot/buildroot/output/host/usr/bin/arm-linux-gnueabihf-
As a result of the compilation, i have no galcore.ko at all, only those 3 files generated :
built-in.o
modules.order ( empty )
Module.symvers ( empty )

I have tried also using buildroot but in the end, i have the same files in the directory output/build/kernel-module-imx-gpu-viv-9bbacfe7753626956a449c6a4f7dffcf6285b4d7
Thanks.

A: There is already a Buildroot package for this kernel driver: https://git.buildroot.org/buildroot/tree/package/freescale-imx/kernel-module-imx-gpu-viv

A: Finally i forgot to set MXC_GPU_VIV=m in the kernel configuration, that means to compile this driver as a module.
Now i have the expected galcore.ko correctly built.


text:
Q: Permission error when using Boto3, but works via aws cli I'm stuck on a missing permissions issue trying to create a Lambda function.
The execution role I've configured has the following permissions:
$ aws --output=text iam get-role-policy --policy-name=MyRolePolicy --role-name=my-role
<snip>
POLICYDOCUMENT  2012-10-17
STATEMENT   Allow
ACTION  s3:Get*
ACTION  s3:List*
ACTION  logs:CreateLogGroup
ACTION  logs:CreateLogStream
ACTION  logs:PutLogEvents
ACTION  ec2:DescribeNetworkInterfaces
ACTION  ec2:CreateNetworkInterface
ACTION  ec2:DeleteNetworkInterface

And when I create a Lambda function with that role, creation succeeds:
$ aws lambda create-function \
  --function-name=my-test --runtime=java8 \
  --role='arn:aws:iam::1234567890:role/my-role' \
  --handler=MyHandler \
  --code=S3Bucket=my-bucket,S3Key=app.zip
<result successful>

However, when I create the function using the same arguments (esp. the same execution role) I get the following error:
Boto3 Usage
client.create_function(
  FunctionName=function_name,
  Runtime='java8',
  Role=getenv('execution_role_arn'),
  Handler='MyHandler',
  Code={
    "S3Bucket": bucket,
    "S3Key": artifact_name
  },
  Publish=True,
  VpcConfig={
    'SubnetIds': getenv('vpc_subnet_ids').split(','),
    'SecurityGroupIds': getenv('vpc_security_group_ids').split(',')
  }
)

Boto3 Result
{
   'Error':{
      'Message':'The provided execution role does not have permissions to call CreateNetworkInterface on EC2',
      'Code':'InvalidParameterValueException'
   },
   'ResponseMetadata':{
      'RequestId':'47b6640a-f3fe-4550-8ac3-38cfb2842461',
      'HTTPStatusCode':400,
      'HTTPHeaders':{
         'date':'Wed, 24 Jul 2019 10:55:44 GMT',
         'content-type':'application/json',
         'content-length':'119',
         'connection':'keep-alive',
         'x-amzn-requestid':'47b6640a-f3fe-4550-8ac3-38cfb2842461',
         'x-amzn-errortype':'InvalidParameterValueException'
      },
      'RetryAttempts':0
   }
}

Creating a function via the console with this execution role works as well, so I must be missing something in how I'm using Boto3, but I'm at a loss to explain.
Hopefully someone can catch a misapplication of Boto3 here, cause I'm at a loss!

A: Your boto3 code is specifying a VPC:
  VpcConfig={
    'SubnetIds': getenv('vpc_subnet_ids').split(','),
    'SecurityGroupIds': getenv('vpc_security_group_ids').split(',')

However, the CLI version is not specifying a VPC.
Therefore, the two requests are not identical. That's why one works and the other does not work.
From Configuring a Lambda Function to Access Resources in an Amazon VPC - AWS Lambda:

To connect to a VPC, your function's execution role must have the following permissions.

*

*ec2:CreateNetworkInterface

*ec2:DescribeNetworkInterfaces

*ec2:DeleteNetworkInterface

  These permissions are included in the AWSLambdaVPCAccessExecutionRole managed policy.

A: The lambda has a role that allows ec2:CreateNetworkInterface and not the account executing script.
The current role assigned to lambda function allows for the lambda to create VpcConfig.
Check that the account running the script to provision the lambda is allowed the ec2:CreateNetworkInterface action.


text:
Q: Can't remove repository i've tried to install wine-mono 4.7.1  on Lubuntu 17.10
wget http://dl.winehq.org/wine/wine-mono/4.7.1
sudo apt update

Result:
Hit:1 http://bg.archive.ubuntu.com/ubuntu artful InRelease
Get:2 http://bg.archive.ubuntu.com/ubuntu artful-updates InRelease [78,6 kB]
Get:3 http://bg.archive.ubuntu.com/ubuntu artful-backports InRelease [72,2 kB]
Get:4 http://security.ubuntu.com/ubuntu artful-security InRelease [78,6 kB]
Hit:5 http://download.mono-project.com/repo/ubuntu xenial InRelease
Hit:6 http://ppa.launchpad.net/cdemu/ppa/ubuntu artful InRelease
Ign:7 http://dl.winehq.org/wine/wine-mono/4.7.1 artful InRelease
Err:8 http://dl.winehq.org/wine/wine-mono/4.7.1 artful Release
404  Not Found
Hit:9 https://dl.winehq.org/wine-builds/ubuntu artful InRelease
Hit:10 http://deb.playonlinux.com trusty InRelease
Reading package lists... Done
E: The repository 'http://dl.winehq.org/wine/wine-mono/4.7.1 artful Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

I look This post
The "sudo add-apt-repository --remove ppa:" command didn't work for me.
Tried manually remove  from /etc/apt/sources.list but access is denied
Is there other way to remove the broken repository

A: The wget command does not add a ppa in the first place, it simply downloads files over http. The command you posted simply downloads Wine from the internet.
However, if you find you would like to remove a source manually, you can do so by opening /etc/apt/sources.list and removing the line that contains the source.
You can do this using the command sudo nano /etc/apt/sources.list. Sudo is used as you require root privileges to edit the file.

A: The command to download mono is:
wget https://dl.winehq.org/wine/wine-mono/4.7.1/wine-mono-4.7.1.msi

then you have to run it in the WINE prefix that you want to install mono in.
To correct the sources list, you need root privileges:
sudo nano /etc/apt/sources.list


text:
Q: Git push executes unwanter Gitlab runner I'm new to GitLab CI. Constructed very simple YAML just for test purposes. I configured runner with shell executor on my AWS machine and register it properly. In Settings/Pipelines I see activated runner. When I push something on my repository following YAML should be executed: docker-auto-scale
before_script:
  - npm install

cache:
  paths:
    - node_modules/

publish:
  stage: deploy
  script:
    - node app.js

Instead completly another runner is continouosly started (whatever I change - even when I turn off runner on my machine). It is runner with ID: Runner:  #40786. In logs I can read:
Running with gitlab-ci-multi-runner 9.5.0 (413da38)
  on docker-auto-scale (e11ae361)
Using Docker executor with image ruby:2.1 ...
I didn't even have Docker executor - I chose shell one. What is going on? Please support.

A: When you registered the new runner, did you give it a tag?
if so, and it would be e.g. my_tag modify your yaml file and append:
publish:
  stage: deploy
  script:
  - node app.js
  tags:
  - my_tag

otherwise the build will be picked up by a shared runner.


text:
Q: How to share on twitter using twitter API? for sharing on twitter using oath API my code is below:
NSURL* accessTokenUrl = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"];
OAMutableURLRequest* accessTokenRequest = [[OAMutableURLRequest alloc] initWithURL:accessTokenUrl consumer:consumer token:requestToken realm:nil signatureProvider:nil];
OARequestParameter* verifierParam = [[OARequestParameter alloc] initWithName:@"oauth_verifier" value:verifier];

[accessTokenRequest setHTTPMethod:@"POST"];

[accessTokenRequest setValue:@"Test"    forHTTPHeaderField:@"X-Twitter-Client"];
[accessTokenRequest setValue:@"1.0" forHTTPHeaderField:@"X-Twitter-Client-Version"];
[accessTokenRequest setValue:callback     forHTTPHeaderField:@"X-Twitter-Client-URL"];

[accessTokenRequest setParameters:[NSArray arrayWithObject:verifierParam]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init];
[dataFetcher fetchDataWithRequest:accessTokenRequest
                         delegate:self
                didFinishSelector:@selector(didReceiveRequestToken:data2:)
                  didFailSelector:@selector(didFailOAuth:error:)];

But I am getting response below:
 {"errors":[{"message":"Invalid or expired token","code":89}]}
But my token is valid and not expired as I am getting user's profile successfully from this.
So can anyone help me what I am missing in this code?

A: // plz try this code..
-(IBAction)ShareOnTwitter :(id)sender
{

UIButton *btn4=(UIButton *)sender;
int count = (int)btn4.tag;
NSLog(@"ShareOnTwitter count=%d",count);

UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.jpg",Pathforimage,[[Array_result objectAtIndex:count] objectForKey:@"img_File_Name"]]];

if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {

    SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];

    SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result)
    {
        if (result == SLComposeViewControllerResultCancelled)
        {
                    NSLog(@"Cancelled");
        }
        else
        {
            NSLog(@"Done");
        }
        [controller dismissViewControllerAnimated:YES completion:Nil];
    };
    controller.completionHandler =myBlock;

    //Adding the Text to the twitter post value from iOS
    [controller setInitialText:@""];

    //Adding the Image to the twitter post value from iOS
    [controller addImage:image];

    [self presentViewController:controller animated:YES completion:Nil];
}
else
{
    NSLog(@"UnAvailable");
}
}


text:
Q: Cleaning 'messy' markup rendered by ASP.NET Ive noticed when looking at the source of a page generated in ASP.NET, the actual markup is very messy - sort of a half-assed tabbed affair with bundles of whitespace thrown in (see pic).

Can anyone suggest a technique to remove/strip this whitespace?

A: Here is a good article on how to override the page render method:
https://madskristensen.net/blog/remove-whitespace-from-your-aspnet-page/

A: You can do it without incurring any runtime cost


text:
Q: Веб авторизация на С# В общим мусолил интернет, первоначальная задача была:
создать виндоус форм в которой будет загружаться определённый сайт и автологиниться, не получилось.
Сделал логин с использованием нажатия button, говорит что не верный логин и пароль. Проверял в эксплорере, все данные подходят.
Выкладываю тело программы, если кто знает как, выложите 2 примера - один по копке логин второй - автоматом после загрузки страницы.
вот мой код.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        WebBrowser web = new WebBrowser();
        public Form1()
        {
            InitializeComponent();
            web.Navigate("http://public.servicebox.peugeot.com");
            button1.Enabled = false;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            button1.Enabled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
 foreach (HtmlElement html in web.Document.GetElementsByTagName("input"))
            {
                if (html.GetAttribute("name") == "userid")
                {
                    html.SetAttribute("value", "AP34593969");
                }

                if (html.GetAttribute("name") == "password")
                {
                    html.SetAttribute("value", "mazdacx77");
                }

                web.Document.GetElementById("btsubmit").InvokeMember("click");
            }
        }
    }
}

A: Попробуйте вынести web.Document.GetElementById("btsubmit").InvokeMember("click"); за тело цикла.


text:
Q: Putty: 'Server unexpectedly closed network connection' Putty 'Server unexpectedly closed network connection'
I have been getting the 'Server unexpectedly closed network connection' (see https://superuser.com/questions/735824/putty-ends-to-an-unexpected-error-and-vnc-shows-terminal-with-error and Getting "Server unexpectedly closed network connection") but it is not associated with any reboot, the connection just fails unexpectedly and with it, the web server (Apache) running off the Linux server. I use Putty through Windows 7 to connect to a Raspberry Pi running Raspbian. Any ideas what might be going wrong?

A: A PuTTY session left idle will disconnect at a time determined by the host server. Try enabling keep-alives in PuTTY. This causes PuTTY to send null SSH packets to the remote host periodically, preventing the session from timing out.
The PuTTY client can be configured to always establish a connection which will not time out due to inactivity. To create and save a new keep-alive connection, follow these steps:

*

*Open the PuTTY application, and go to the Options panel (labeled "Category") on the left of the window.

*Select (click) the "Connection" item.

*In the "Sending of null packets to keep the session active" area on the right, change the default value of "Seconds between keepalives" from 0 (turn off) to 1800 (30 minutes).

*Select the "Enable TCP keepalives (SO_KEEPALIVE option)" check box.
Note: This option may not be available in older versions of the PuTTY client.

*On the topmost left side of the Options panel, select (click) "Session".

*In the "Host Name (or IP Address)" field, enter the destination host name or IP address (e.g., "destination.ipaddress.here.com" or "192.168.1.1").

*In the "Saved Sessions" text-entry box, provide a name for the session (e.g., "savedsession").

*Select "Save".

To use the modified session settings, select it from the "Saved sessions" list, then click the buttons marked "Load" and "Open".
If your connected sessions still time out, enter a lower number of seconds into the "Seconds between keepalives" value.

A: The server could have been hardened. The reason could be a) the client ip may be not configured in /etc/allowhosts and/or b) unix/linux firewall rule/selinux is not permitting.

A: I had the same problem for a long time, I use putty to connect to AWS linux instances (some remote cloud servers)
I read about fixing it with keepAlives in several pages several pages, tried it but to no avail.
And just yesterday, while looking for some color scheme settings I found this:
https://github.com/jblaine/solarized-and-modern-putty
Besides adjusting the colors of the terminal it does apply some sane defaults (Like the forementioned KeepAlives to 59 seconds plus others), and guess what? I havent had any closed connection for two whole days.

A: I tried everything above and nothing worked until this
vi /etc/ssh/sshd_config
ClientAliveInterval 60
restart deamon sshd

also switched to kitty an alternative putty clone which is much better

A: You were idle longer than the session timeout on the remote device, so it closed the session and PuTTy wasn't expecting it.


text:
Q: Selenium Run multiple browser instances parallely        if (platform != null) {
                        for (final String p : platform) {
                            log.info("Platform " + p);
                            executorService.submit(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    try {
                                        runService(p, config, url, title, report);
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                            });

                        }

                        executorService.shutdown();
                        executorService.awaitTermination(Long.MAX_VALUE,
                                TimeUnit.NANOSECONDS);

                        // for(final String p: platform){
                        // runUIService(p, config, url, title, report);
                        // }
                    }

    public void runService(){
              WebDriver driver = getDriver();
//some selenium operations performed
    }

I am trying to execute runService() in multiple threads parallelly. getDriver() method returns a new instance of selenium WebDriver. If I execute for a single platform all the selenium operations run successfully, but if the same code is fired for multiple platforms although a new browser instance is opened for each platform, I am getting a lot of errors on selenium elements not found. I am not able to figure what can be the reason for this ? Is there a problem associated with running multiple browser instances through selenium at the same time ?

A: I think this is a concurrency issue.
Have you tried using synchronized keyword for your method?
i.e
public synchronized void runService()
or in your getDriver() method.
Hope this can help.


text:
Q: Solution Explorer shows error in Visual Studio Instead of seeing solution explorer in the latest Visual Studio version (16.10.1) I see this error message:
An error occurred while initializing the frame's content
System.ArgumentNullException: Value cannot be null.
Parameter name: format
   at Microsoft.Requires.NotNull[T](T value, String parameterName)
   at Microsoft.VisualStudio.Platform.WindowManagement.FrameMoniker.ToString(String format, IFormatProvider formatProvider)
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.LogContentCreationException(Exception ex)
   at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.HandleContentCreationException(Exception ex)
   at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.ConstructContent()
   at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.EnsureContentConstructed()
   at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.PreloadOnScreenContent(View view)
   at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.set_FrameView(View value)
   at Microsoft.VisualStudio.Platform.WindowManagement.WindowManagerService.CreateContentPane(FrameMoniker frameMoniker, Boolean isDocument, String lpstrMkDoc, UInt32 eCreateWindowFlags, Object punkView, Object punkData, IServiceProvider pServiceProvider, IVsUIHierarchy pUIHierarchy, UInt32 vsid, Guid rguidCmdUI, ViewGroup parent, IVsWindowFrame& ppWindowFrame)

Don't know how to get rid of it, have been working around it.

A: Resetting all settings resolved the problem:
https://www.technipages.com/visual-studio-reset-all-settings


text:
Q: How to start an interactive bash with su I do not have sudo su over a username, however I have its password. I want to have an script that passes the password and gives me an interactive bash.
I have tried this:
echo mypassword | su - otherusr
Password: Last login: Wed Jul 25 12:09:38 COT 2018
[myuser@myserver ~]$

It returns me to myuser and I do not have an interactive bash with the other user.
I tried also:
echo mypassword | su -c "/bin/bash" - otherusr
echo mypassword | su -s "/bin/bash" - otherusr
echo mypassword | su -c "/bin/bash -i" - otherusr
Password: bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
bash-4.2$ exit

How can I do that? I want to create an script that returns me an interactive bash session with another user; not just execute a command with another user.

A: By default neither sudo nor su reads a password from stdin. They try to use a terminal device directly (some implementations may even complain when used in a pipe). There is sudo -S option to change this behavior, but as far as I know there is no similar option for su.
Solution: use expect.

expect is a program that "talks" to other interactive programs according to a script. Following the script, expect knows what can be expected from a program and what the correct response should be.
[…]
In general, expect is useful for running any program which requires interaction between the program and the user. All that is necessary is that the interaction can be characterized programmatically.

In your case the script may be:
#!/usr/bin/expect

log_user 0
spawn /bin/su - otherusr
expect "Password: "
send "mypassword\n"
interact

I advise to make this script accessible only to you (chmod go-rwx). Other users shouldn't be allowed to read it because it contains mypassword in plaintext; they shouldn't be allowed to run it, because it gives access to otherusr's shell.


text:
Q: Cannot open excel file on Sharepoint uploaded by Python I couldn't open excel file on sharepoint(wrong file extension-> screenshot on below). I created code base on Postman API and then translated it to Python-Requests by code snippet. It is interesting because I did the same for csv file and everything works fine. My current code is here:
import requests

url = "https://xxx.sharepoint.com/sites/RW-RUS-ControllingRUS-Budget-template/_api/web/GetFolderByServerRelativeUrl('Shared Documents/RockBI Alert')/Files/add(url='Chains2.xlsx',overwrite=true)"

payload="<file contents here>"
headers = {
  'Host': 'xxx.sharepoint.com',
  'Authorization': 'Bearer xxxxx',
  'Accept': 'application/json;odata=verbose',
  'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

My SP after code execution:

Error during openning uploaded file:


text:
Q: How to create percentage of loop(processing) [c#] example : doing something 9999 time (maybe more than)
for (int i = 1; i <= 9999; i++)
{
    // do something
    label1.content = 100*i/9999 + "%" ;
}

and I want to show percentage of loop on label1 when I compile I can't doing anything several a millisecond and my label show 100% only. someone have any idea sir? thank you.

A: You can't run a loop on and the update the UI on the same thread simultaneously. That's why you should always perform any long-running work on a background thread and update UI at regular intervals using the dispatcher.
The easiest way to run some code on a background thread is to use the task parallel library (TPL) to start a new task:
Task.Run(()=>
        {
            for (int i = 1; i <= 9999; i++)
            {
                System.Threading.Thread.Sleep(1500); //simulate long-running operation by sleeping for 1.5s seconds...
                label1.Dispatcher.BeginInvoke(new Action(() => label1.Content = 100 * i / 9999 + "%"));
            }
        });

my message box immediately show message after i run command while percentage is running

As mentioned the Task is being executed on another thread. So it will run in parallel with the UI thread. That's the reason why the UI can be updated while the loop is running.
You could use the Task.ContinueWith method to show the MessageBox after the task has completed:
int i = 1;
Task.Run(() =>
            {
                for (; i <= 9999; i++)
                {
                    System.Threading.Thread.Sleep(1500); //simulate long-running operation by sleeping for 1.5s seconds...
                    label1.Dispatcher.BeginInvoke(new Action(() => label1.Content = (i / 9999) * 100 + "%"));
                }
            }).ContinueWith(t =>
            {
              MessageBox.Show("done..." + i.ToString());
            }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

A: thats because you are blocking UI thread while calculating inside your loop. Such things should be made in different thread with callback method.
As a work around, you can import system.windows.forms.dll assembly and call System.Windows.Forms.Application.DoEvents();
    for (int i = 1; i <= 9999; i++)
    {
        System.Windows.Forms.Application.DoEvents();
        // do something
        label1.Content = 100 * i / 9999 + "%";
        Thread.Sleep(10);
    }

But this is a bad practice!

A: @mm8 solution is ok, but every concurrency round trip to the UI thread from the new one will delay your loop.
If you want the loop ends as early as possible without bloating the UI (and your targeting NET Framework 4.5 or above), you can use the asynchronous Task method equivalent to the old DoEvents: Task.Yield().
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < 10000; i++)
        {
            //Do something
            //Simulate work with Task.Delay(millisecondos)
            Label1.Content = (i * 100 / 10000) + "%";
            await Task.Yield(); //give opportunity to dispatch other events
        }
    }

This solution is simple and is an example of why asynchrony doesn't need multithrading always as stated in this answer and this
But there is a trade off between give a break with Task.Yield() and create a new Thread as in @mm8 solution:

*

*Give a break with Task.Yield() is better in case the work can be done in pieces and in each piece the UI must be updated.

*Create a new thread is better when UI updates are few (relatively to work done)

NOTE. By the way, in a 10000 loop, I believe is better to show a per thousand progress


text:
Q: How to make a row in color with activeadmin based on if else condition I'm new to Ruby on Rails. I'm using Active Admin for my application. I want to color a row if the condition is true and some other color is condition is false.
tr.odd, tr.even {
    &.test {
        td.col {
            background-color: red;
        }
    }
}

I want to apply this condition for test class. Is there any way possible to accomplish this task?

A: I would recommend to have two different CSS classes and then apply the different classes in your ERB views for instance like this:
<tr class="<%= condition ? 'test' : 'default' %>">
  1
  2
  3

Ideally you would move this to a helper like this
# application_helper.rb
def css_class_for(condition)
  if condition
    'test-css-class'
  else
    'other-css-class'
  end
end

# view
<tr class="<%= css_class_for(true) %>">
  1
  2
  3
</tr


text:
Q: Password toggle button on TextInputEditText disappears after click in Support Library 25.1.0 I have a TextInputEditText in conjunction with TextInputLayout with android:inputType="textPassword" using app:passwordToggleEnabled="true" to show password toggle button in the TextInputEditText like next image:

The problem is once I press the password toggle button, it disappears for ever.
It was working well in com.android.support:design:24.2.0 version.
am I missing something new? it's a bug?

Some gradle project's setup:
minSdkVersion 17
targetSdkVersion 25
compile 'com.android.support:support-v4:25.1.0'
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:cardview-v7:25.1.0'
compile 'com.android.support:design:25.1.0'

Running in 2 different Android 6.0 (Marshmallow) devices.
XML:
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/TextLabelGray"
    app:passwordToggleEnabled="true">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/profile_field_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/perfil_field_password"
        android:inputType="textPassword"
        android:maxLines="1"
        android:maxLength="100"
        android:imeOptions="actionNext"
        android:imeActionLabel="@string/perfil_field_tipo_documento"
        android:textColor="@color/colorAccent"
        android:textSize="@dimen/perfil_text_view_text_size"
        android:paddingStart="15dp"
        android:paddingEnd="5dp"/>
</android.support.design.widget.TextInputLayout>

If I use app:passwordToggleDrawable with a custom drawable in TextInputLayout it doesn't disappear.

The related style:
<style name="TextLabelGray" parent="TextAppearance.AppCompat">
    <!--//hint color And Label Color in False State-->
    <item name="android:textColorHint">@color/gray_text_color</item>
    <item name="android:textColorHighlight">@color/gray_text_color</item>
    <item name="android:textColorLink">@color/gray_text_color</item>
    <item name="colorAccent">@color/gray_text_color</item>
    <item name="colorControlNormal">@color/gray_text_color</item>
    <item name="colorControlActivated">@color/gray_text_color</item>
</style>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="colorControlNormal">@color/colorControlNormal</item>

    <item name="searchViewStyle">@style/AppTheme.MySearchViewStyle</item>
</style>

A: change gradle file by following dependency
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'

In xml file, add following lines for toggle button in password field
 <android.support.design.widget.TextInputLayout
 android:id="@+id/text_input_layout_password"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 app:passwordToggleEnabled="true">

          <android.support.design.widget.TextInputEditText
          android:id="@+id/text_input_edit_text_password"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="Enter Password"
          android:imeActionId="@+id/login"
          android:imeActionLabel="Login"
          android:imeOptions="actionUnspecified"
          android:inputType="textPassword"
          android:maxLines="1"
          tools:text="password" />

 </android.support.design.widget.TextInputLayout>

A: Add
<item name="passwordToggleDrawable">@drawable/design_password_eye</item>
<item name="passwordToggleTint">@color/design_tint_password_toggle</item>
<item name="passwordToggleContentDescription">@string/password_toggle_content_description</item>

on your TextLabelGray style and it will show toggle button again.

A: This code work fine:
  <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16sp"
            app:passwordToggleEnabled="true"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_password"
                android:imeActionId="6"
                android:inputType="textPassword"
                android:maxLines="1"
                android:fontFamily="@font/product_regular"
                android:singleLine="true" />

        </android.support.design.widget.TextInputLayout>

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com"
    minSdkVersion 24
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

buildToolsVersion '28.0.2'

}
implementation 'com.android.support:exifinterface:28.0.0-rc02'
implementation 'com.android.support:support-v4:28.0.0-rc02'
implementation 'com.android.support:support-v13:28.0.0-rc02'
implementation 'com.android.support:design:28.0.0-rc02'
implementation 'com.android.support:cardview-v7:28.0.0-rc02'
implementation 'com.android.support:recyclerview-v7:28.0.0-rc02'


text:
Q: Unable to share whatsapp videos on web whatsapp Recently web.whatsapp.com will not share new videos created by ffmpeg, using the same code to generate them.

However videos from the same code still work on whatsapp.
Does anybody know the correct ffmpeg settings to get the mp4s to work?
The video files were taken on a gopro 10 with the follow command:
ffmpeg  -i some.mp4 -s 1980x1080 -c:a copy sd.mp4
Broken file: 2mb https://drive.google.com/file/d/124Ha4wbKnmrIrHDQYXpWB_bZMECu03b6/view?usp=sharing
Working File: 31.5mb
https://drive.google.com/file/d/1SSfIa3xM0DDvO_o1hdeSO_Yj9OoEYvwX/view?usp=sharing


text:
Q: How to achieve Roll back using Jenkins I know this Forum is not to provide strategy's.
Using Jenkins I have set up CI and CD to my Dev,QA and Staging environments. I am stuck up with Rollback strategy for all my environments.
1- What happens if my build fails in Dev
2- What happens if my build fails in QA and passed in Dev.
3- What happens if my build fails in Staging and passed in Dev and QA.
How should I roll back and get things done considering DB in not in place. I have created sample workflow but not sure its an right process.

A: Generally you can achieve this in 2 ways:

*

*Setting up some sort of release management tool that tracks every execution of your pipeline and snapshots the variables, artifacts, etc... that was used on that exact execution, then you can just run an earlier release of it (check tools like octopus deploy)

*If you are using a branch strategy with tags you can parameterize your jobs, passing the tag you wanna build, and build the "earlier tag" if something fails. Check the rebuild option for older job executions.


text:
Q: jQuery change the text inside my  I have following html code:

    SIMPLE TEXT INSIDE SPAN

    SIMPLE TEXT INSIDE SPAN

now with jQuery I want to change the text inside  tag. But my code doesn't work:
$('[id^="change_user_status_account-"]').click(function () {
    var id = $(this).attr('id').split('-');
    alert(id[1]);
    $("change_user_status_account-" + id[1]).html('OK CHANGED');
});

alert() in this code return 1 or 2 and I don't get any error on FireBug

A: Use $(this). $(this) inside the event handler refers to the element on which the event has occurred.
$('[id^="change_user_status_account-"]').click(function () {
    $(this).text('changed');
});

I'd recommend to use a common class on both the elements and bind event using class.

$('.sample').on('click', function() {
  $(this).text(+new Date());
});

    SIMPLE TEXT INSIDE SPAN

    SIMPLE TEXT INSIDE SPAN

A: you are missing # in selector
it should be
$("#change_user_status_account-" + id[1]).html('OK CHANGED');

or try
$('[id^="change_user_status_account-"]').click(function () {
    $(this).html('OK CHANGED');
});

A: Put a # before your id
$('[id^="change_user_status_account-"]').click(function () {
    var id = $(this).attr('id').split('-');
    alert(id[1]);
    $("#change_user_status_account-"+id[1]).html('OK CHANGED');
});

Or Just Do
$('[id^="change_user_status_account-"]').click(function () {
    $(this).html('OK CHANGED');
});


text:
Q: Jenkins Build Folder I have a Jenkins Job which I execute using Build parameters. My Requirement is to have a single build Folder(i.e if I execute my job 'n' number of times today it should create a single build folder with date as postfix to the folder ) rather than separate build folder for each build.Is it possible? Is there any plugin that can help me to achieve this? Please Help

A: Create a variable to store today's date
set "day=%date:~4,2%%date:~7,2%%date:~10,4%"

Test the variable expansion
echo today's date is[dd/mm/yyyy]:%day%

Now create a folder with today's date :
mkdir %day%

The above command would create a folder with today's date and in second run you would have this directory already created so the command output would be message stating "directory already exists."
Now to use jenkins pre-defined variable to create another folder which will store your code inside today's folder
cd %day%
mkdir %BUILD_NUMBER%

Now change your directory to the path of newly created path to store your code :
cd %BUILD_NUMBER%
<<store your build code/artifacts Here..>>

Please Note that Build_number is a jenkins pre-defined variable which will hold the value of current build number.
Now you can store all builds done in a particular day under one path
if you face any issue , we can certainly make some tweaks to get it right ..


text:
Q: Problems with trackbar and Django I have a little problem. I use Django like a web-framework and when i try to include trackbar to the html-file this trackbar just not displayed. When I include trackbar to the simple html-file everything is ok. But when I run my application with Django, trackbar just not displayed. I don't know where is problem.

    <link rel="stylesheet" type="text/css" href="trackbar.css" />

{% block content %}{% endblock %}

A: Probably because 'two' isn't an object or a selector on that page.
See here:
trackbar.getObject('two').init({

If you're trying to reference a selector using a class or id, they need .two or #two, respectively.
If that's supposed to be an actual object, take it out of the quotes.
The way it is now, it's just a string that says 'two'.