text:
Q: Passing selected value of Dropdown into API in react Hi I need to populate list in dropdown when the page gets loaded so I put the same in componentDidMount().
 componentDidMount() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const countryData = res.data;
      this.setState({ countryData });
    });
  }

This data needs to be part of dropdownlist.
      <select id="dropdown">
        {this.state.countryData.map((countryData) => (
          <option key={countryData} value={countryData}>
            {countryData}
          </option>
        ))}
      </select>

list is getting displayed like below.

Myrequirement is if user select any value in dropdown list that value should be passed in API as parameter to backend.
what changes I need to do in Select or Option. I know how to write call API in reactjs using axios.that I will manage.
My updated code is below.
<select id="dropdown" onChange={this.downLoadFile(e)}>
                {this.state.countryData.map((countryData) => (
                  <option key={countryData} value={countryData}>
                    {countryData}
                  </option>
                ))}
</select>

downLoadFile(e) {
    this.setState({ selectValue: e.target.value });
    alert(selectValue);
  }

this.state = {
      countryData: [],
      selectValue: '',
    };
    this.handleChange = this.handleChange.bind(this);
    this.downLoadFile = this.downLoadFile.bind(this);
  }

Its not working. what wrong I am doing?
Edit1:-
 downLoadFile(e) {
    e.preventDefault();
    this.setState({ selectValue: e.target.value });
    alert(selectValue);
  }

   <select id="dropdown" onChange={this.downLoadFile}>
                {this.state.countryData.map((countryData) => (
                  <option key={countryData} value={countryData}>
                    {countryData}
                  </option>
                ))}
              </select>

it is giving below error.

in constrtor I have below code.
this.state = {
      selectValue: ''
    };

A: You should pass function to onChange event.
Like:
<select id="dropdown" onChange={(e) => {this.downLoadFile(e)}}>

or
<select id="dropdown" onChange={this.downLoadFile}>

The way you do is just pass the return value of this.downLoadFile

Update:
alert(selectValue)

must be
alert(this.state.selectValue);

A: You should fetch API after the update of the selected state.
downLoadFile(e) {
    this.setState({ selectValue: e.target.value }, () => {
      fetchSomeApi(this.state.selectValue).then((res) => {
         updateSomewhere(res);
      }).catch((error) => console.error(error));
    });
    alert(this.state.selectValue); // < --- changes this line
}

this.setState has second parameter as callback. So you could use that for after state update event.
Also, you can update the function call.
onChange={this.downloadFile)


text:
Q: How to get current datetime in unix timestramp in python I have a timestramp, 1559885284236 and a function to generate readable datetime format.
def tz_from_utc_ms_ts(utc_ms_ts, tz_info):
    """Given millisecond utc timestamp and a timezone return dateime

    :param utc_ms_ts: Unix UTC timestamp in milliseconds
    :param tz_info: timezone info
    :return: timezone aware datetime
    """
    # convert from time stamp to datetime
    utc_datetime = dt.datetime.utcfromtimestamp(utc_ms_ts / 1000.)

    # set the timezone to UTC, and then convert to desired timezone
    return utc_datetime.replace(tzinfo=pytz.timezone('UTC')).astimezone(tz_info)

import datetime as dt
import pytz

utc_ts = 1559885284236
utc_time = "Sat Sep 22 22:16:29 2018 UTC"
pdt_time = "Sat Sep 22 15:16:29 2018 PDT"

tz_dt = tz_from_utc_ms_ts(utc_ts, pytz.timezone('America/Los_Angeles'))

print(tz_dt)
print(tz_dt.strftime('%d-%m-%Y'))

which gives,
2019-06-06 22:28:04.236000-07:00
06-06-2019

as expected, but how can I convert a current datetime value to the unix ms with 13 length.
when I try,
dt.datetime.timestamp(dt.datetime.now())

which gives, 1560004646.952688 this is not my expected 13 digit value, pls help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I count the number of line in a FTP file without downloading it locally while using Python So I need to be able to read and count the number of lines from a FTP server WITHOUT downloading it to my local machine while using Python.
I know the code to connect to the server:
ftp = ftplib.FTP('example.com')  //Object ftp set as server address
ftp.login ('username' , 'password')  // Login info
ftp.retrlines('LIST')  // List file directories
ftp.cwd ('/parent folder/another folder/file/')  //Change file directory

I also know the basic code to count the number of line If it is already downloaded/stored locally :
with open('file') as f:
...     count = sum(1 for line in f)
...     print (count)

I just need to know how to connect these 2 pieces of code without having to download the file to my local system.
Any help is appreciated.
Thank You

A: As far as i know FTP doesn't provide any kind of functionality to read the file content without actually downloading it. However you could try using something like Is it possible to read FTP files without writing them using Python?
(You haven't specified what python you are using)
#!/usr/bin/env python
from ftplib import FTP

def countLines(s):
   print len(s.split('\n'))

ftp = FTP('ftp.kernel.org')
ftp.login()
ftp.retrbinary('RETR /pub/README_ABOUT_BZ2_FILES', countLines)

Please take this code as a reference only

A: There is a way: I adapted a piece of code that I created for processes csv files "on the fly".  Is implement by producer-consumer problem approach. Apply this pattern allows us to assign each task to a thread (or process) and show partial results for huge remote files. You can adapt it for ftp requests.
Download stream is saved in queue and is consumed "on the fly". No HDD extra space is needed and memory efficient. Tested in Python 3.5.2 (vanilla) on Fedora Core 25 x86_64.
This is the source adapted for ftp (over http) retrieve:
from threading import Thread, Event
from queue import Queue, Empty
import urllib.request,sys,csv,io,os,time;
import argparse

FILE_URL = 'http://cdiac.ornl.gov/ftp/ndp030/CSV-FILES/nation.1751_2010.csv'

def download_task(url,chunk_queue,event):

    CHUNK = 1*1024
    response = urllib.request.urlopen(url)
    event.clear()

    print('%% - Starting Download  - %%')
    print('%% - ------------------ - %%')
    '''VT100 control codes.'''
    CURSOR_UP_ONE = '\x1b[1A'
    ERASE_LINE = '\x1b[2K'
    while True:
        chunk = response.read(CHUNK)
        if not chunk:
            print('%% - Download completed - %%')
            event.set()
            break
        chunk_queue.put(chunk)

def count_task(chunk_queue, event):
    part = False
    time.sleep(5) #give some time to producer
    M=0
    contador = 0
    '''VT100 control codes.'''
    CURSOR_UP_ONE = '\x1b[1A'
    ERASE_LINE = '\x1b[2K'
    while True:
        try:
            #Default behavior of queue allows getting elements from it and block if queue is Empty.
            #In this case I set argument block=False. When queue.get() and queue Empty ocurrs not block and throws a
            #queue.Empty exception that I use for show partial result of process.
            chunk = chunk_queue.get(block=False)
            for line in chunk.splitlines(True):
                if line.endswith(b'\n'):
                    if part: ##for treat last line of chunk (normally is a part of line)
                        line = linepart + line
                        part = False
                    M += 1
                else:
                ##if line not contains '\n' is last line of chunk.
                ##a part of line which is completed in next interation over next chunk
                    part = True
                    linepart = line
        except Empty:
            # QUEUE EMPTY
            print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE)
            print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE)
            print('Downloading records ...')
            if M>0:
                print('Partial result:  Lines: %d ' % M) #M-1 because M contains header
            if (event.is_set()): #'THE END: no elements in queue and download finished (even is set)'
                print(CURSOR_UP_ONE + ERASE_LINE+ CURSOR_UP_ONE)
                print(CURSOR_UP_ONE + ERASE_LINE+ CURSOR_UP_ONE)
                print(CURSOR_UP_ONE + ERASE_LINE+ CURSOR_UP_ONE)
                print('The consumer has waited %s times' % str(contador))
                print('RECORDS = ', M)
                break
            contador += 1
            time.sleep(1) #(give some time for loading more records)

def main():

    chunk_queue = Queue()
    event = Event()
    args = parse_args()
    url = args.url

    p1 = Thread(target=download_task, args=(url,chunk_queue,event,))
    p1.start()
    p2 = Thread(target=count_task, args=(chunk_queue,event,))
    p2.start()
    p1.join()
    p2.join()

# The user of this module can customized one parameter:
#   + URL where the remote file can be found.

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--url', default=FILE_URL,
                        help='remote-csv-file URL')
    return parser.parse_args()

if __name__ == '__main__':
    main()

Usage
$ python ftp-data.py -u <ftp-file>

Example:
python ftp-data-ol.py -u 'http://cdiac.ornl.gov/ftp/ndp030/CSV-FILES/nation.1751_2010.csv'
The consumer has waited 0 times
RECORDS =  16327

Csv version on Github: https://github.com/AALVAREZG/csv-data-onthefly


text:
Q: Gradually add react elements to a Django project using Create React App and yarn build I have a project using Django as backend and raw HTML, CSS and JS. I have tons of templates and I want to start migrating some parts of the frontend website to React.
I started creating one single landing page in react using the official tutorial
and until here everything went well, just a bit tedious having to build and manually move static js and css created to django templates:

*

*yarn build

*go to django static folder and replace minified js and css files by the new ones

*go to django templates (html) and replace new reference to new files

But then I wanted to create a new independent component not related to the landingpage I created and i culdn't find the best approach to do it without duplicating react create app folder.
The goal is to do yarn build and have one single js and css file per independent element.
For example, if I have:
index.js
Element1.js
Element2.js
...
After doing yarn build, I have:
build/
     static/
            css/
                elem1.54aa3f3f.css
                elem2.jsby6syb.css
            js/
                elem1.54aa3f3f.js
                elem2.jsby6syb.js

The colser I've been to this, is having in my index.js file one render per independent element, but then it creates only one single js and css file and it requires to have both div ids (elem1 and elem2) in the django template, causing error if one of them is not present:
ReactDOM.render(
  <React.StrictMode>
    <elem1 />
  </React.StrictMode>,
  document.getElementById("elem1")
);
ReactDOM.render(
  <React.StrictMode>
    <elem2 />
  </React.StrictMode>,
  document.getElementById("elem2")
);

The only single way I could achieve the desired result is duplicating the folder project for each element, meaning duplicating all node modules, src files ... and going in each folder doing yarn build:

Could you please be so kind indicating the best approach? Maybe modifying build command and creating some bash scripts?


text:
Q: How to get total audio duration from multiple audio files I am trying to get the total duration of audio from an array of audio paths.
Here is what the array would look like:
var sound_paths = ["1.mp3","2.mp3",...]

I have looked at this post, which helped:
how to get audio.duration value by a function
However, I do not know how to implement this over an array. The idea is that I want to loop over each audio file, get its duration, and add it to a "sum_duration" variable.
I cannot seem to figure out a way to do this over a for loop. I have tried Promises (which I am admittedly new at): (Note the functions come from a class)
getDuration(src,cb){
    // takes a source audio file and a callback function
    var audio = new Audio();
    audio.addEventListener("loadedmetadata",()=>{
        cb(audio.duration);
    });
    audio.src = src;
}

getAudioArrayDuration(aud_path_arr){
    // takes in an array of audio paths, finds the total audio duration
    // in seconds

    return new Promise((resolve)=>{
        var duration = 0;

        for(const aud_path in aud_path_arr){
            var audio = new Audio();
            audio.src = aud_path;
            audio.onloadedmetadata = ()=>{
                console.log(audio.duration);
                duration += audio.duration;
            }
            resolve(duration);
        }

    });

}

However, this obviously does not work, and will just return the duration value of 0.
How can I loop over audio files and return the total audio duration of each file summed?

A: I think, in this case, working with promises is the right approach, time to get used to them ;) Try to remember, a promise will fullfil your wish in the near future. What makes your problem harder is that you have an array of files to check, each will need to separately be covered by it's own Promise, just so that your program can know when all of them have been fullfilled.
I always call my 'promised' getters 'fetch...', that way I know it'll return a promise instead of a direct value.
function fetchDuration(path) {
  return new Promise((resolve) => {
    const audio = new Audio();
    audio.src = path;
    audio.addEventListener(
      'loadedmetadata',
      () => {
        // To keep a promise maintainable, only do 1
        // asynchronous activity for each promise you make
        resolve(audio.duration)
      },
    );
  })
}

function fetchTotalDuration(paths) {
  // Create an array of promises and wait until all have completed
  return Promise.all(paths.map((path) => fetchDuration(path)))
    // Reduce the results back to a single value
    .then((durations) => durations.reduce(
      (acc, duration) => acc + duration,
      0,
    ))
  ;
}

At some point, your code is going to have to deal with this asynchronous stuff, I honestly believe that Promises are the easiest way to do this. It takes a little getting used to, but it'll be worth it in the end. The above could be used in your code something along the lines of:
window.addEventListener('DOMContentLoaded', () => {
  fetchTotalDuration(["1.mp3","2.mp3",...])
    .then((totalDuration) => {
      document.querySelector('.player__total-duration').innerHTML = totalDuration;
    })
  ;
});

A: I hacked this together real quick, so you'll have to adapt it to your function structure, but it's a working code snippet that should send you in the right direction.
Simply keep track of which audio files have been loaded, and if that matches the number of audio files queried, you call the callback with the total duration.
You should also take failing requests into account, so that if the loadedmetadata event never fires, you can react accordingly (by either falling back to 0 duration for that file, or throwing an Exception, etc.).

const cb = function(duration) {
    console.log(`Total duration: ${duration}`);
};

let sound_paths = ["https://rawcdn.githack.com/anars/blank-audio/92f06aaa1f1f4cae365af4a256b04cf9014de564/5-seconds-of-silence.mp3","https://rawcdn.githack.com/anars/blank-audio/92f06aaa1f1f4cae365af4a256b04cf9014de564/2-seconds-of-silence.mp3"];
let totalDuration = 0;
let loadedSounds = [];
sound_paths.map(src => {
    const audio = new Audio();
    audio.addEventListener("loadedmetadata", ()=>{
        totalDuration += audio.duration;
        loadedSounds.push(audio);
        if ( loadedSounds.length === sound_paths.length ) {
            cb( totalDuration );
        }
    });
    audio.src = src;
});


text:
Q: RestFB : Retrieving Attachments present in private messages I need to retrieve the attachments present as a part of private messgaes posted to my account in Facebook. I am using restfb api to do the same but am getting only the text message as a response, no link to the attachments. Is there a way to get the links or retrieve the attachments?
I am using restfb version 1.6.9.
Steps to reproduce this are

*

*Create a private message in Facebook with photo attached.

*Access Inbox of the account using graph API.

*web service response returns just content and sender details


text:
Q: "Incorrect syntax" error when running SQL query I am trying to insert into database using this class, I am able to access this class in My Customer page, but getting error

Incorrect syntax near '@ZipCode'.

Meanwhile I don't have any stored procedure or trigger in my SQL Server database.
public class CustomerDLL
{
    SqlConnection cn;
    SqlCommand cmd;
    SqlDataAdapter da;
    DataSet ds;

    public CustomerDLL()
    {
       cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
    }

    public void Insert_Customer(string name, string address, string city, string state, int ZipCode)
    {
        cmd = new SqlCommand("Insert into Customer values (@name, @address, @city, @state, @ZipCode", cn);
        cmd.Parameters.AddWithValue("@name", name);
        cmd.Parameters.AddWithValue("@address", address);
        cmd.Parameters.AddWithValue("@city", city);
        cmd.Parameters.AddWithValue("@state", state);
        cmd.Parameters.AddWithValue("@ZipCode", Convert.ToInt32(ZipCode) ); // Line 34

        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

I am accessing this class in Customer page using this method
protected void btnAdd_Click(object sender, EventArgs e)
{
       // Create an instance of CustomerDll
       CustomerDLL cusdll = new CustomerDLL();

       //int zip = Convert.ToInt32(txtZip.Text);
       cusdll.Insert_Customer
            (
            txtName.Text,
            txtAddress.Text,
            txtCity.Text,
            txtState.Text,
            Convert.ToInt32(txtZip.Text)
            );

        lblMsg.Text = "Rec is inserted successfully";
        cusdll = null;
    }

I keep getting error

Incorrect syntax near '@ZipCode' on line 34.

A: I think you missed closing parenthesis after @ZipCode.


text:
Q: Media player fast forward I have spent a great deal of time searching, and with all different key phrases. I am working on a Media Player and have a menu strip with an option to fast forward and reverse. Here is what I have currently:
private void increaseRateToolStripMenuItem_Click(object sender, System.EventArgs e)
{
    if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsPlaying)
    {
        WMPLib.IWMPControls3 controls = (WMPLib.IWMPControls3)axWindowsMediaPlayer1.Ctlcontrols;
        if (controls.get_isAvailable("fastForward"))
        {
            controls.fastForward();
        }
    }
}

Which essentially is the circle that I have been going around. I started here, tinkered, and then ended up back here. It is driving me crazy. In theory it sounds so simple, but I am getting nothing.
The example I used above was off of the MSDN example here: http://msdn.microsoft.com/en-us/library/windows/desktop/dd564741(v=vs.85).aspx
So I am here asking, how can I fast forward (and reverse) the video when the menu item is clicked in C#?

A: This is an extension from my answer on this related question.
According to the OP over there (see comments on my answer) this would work if you're playing an MP4 file, but if you're trying to play an AVI it won't work as they're not indexed. He instead suggested that you increment the currentPosition property (MSDN documentation) to achieve this effect.
So to summarise, instead of controls.fastForward(), try controls.currentPosition += someIncrement in a loop of some sort (perhaps this question might help you achieve this: C# how to loop while mouse button is held down)


text:
Q: How can I use Twilio for "pass-through" SMS exchanges? For some reason, I'm having a very tough time understanding how the Twilio model works; as a result, I'm trying to code a solution by guessing (something I hate doing.) I hope someone can help with the confusion.
I've already set up a forwarder so that when someone sends a text to my Twilio number, I receive it on my phone. The problem is, when I reply to that text, it goes to Twilio instead of back to the original sender.
I've tried passing my number as a 'from' string in the  tag, but this gets rejected by Twilio as not being a valid Twilio number.
<?php header('Content-Type: text/html'); ?>
<Response>

  <!-- ****** This gets rejected: ****** -->
  <!-- Message to="<?=$_REQUEST['PhoneNumber']?>" from="<?=$_REQUEST['From']?>" -->

  <Message to="<?=$_REQUEST['PhoneNumber']?>">
    <?=htmlspecialchars(substr($_REQUEST['From'] . $_REQUEST['Body'], 0, 1600))?>
  </Message>
</Response>

A: When a message is forwarded to you from Twilio you need to know the phone number which originated the message.
When you send a message you need to tell Twilio where to send your message.
So, with a convention like: the messages start with a phone number, then a /, then the actual message, you can use this code for the webhook.
<?php
    header("content-type: text/xml");
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>

<?php

$myPhoneNumber = "+15557779999";

if ($_REQUEST['From'] == $myPhoneNumber) {
    $message = explode("/", htmlspecialchars(substr($_REQUEST['Body'], 0, 1600)));
    $theOtherPhoneNumber = $message[0];
    $theOtherMessage = $message[1];
    echo(
        "<Response>
          <Message to=\"{$theOtherPhoneNumber}\">
            {$theOtherMessage}
          </Message>
        </Response>"
    );

} else {
    $message = htmlspecialchars(substr($_REQUEST['From'] ."/ " .$_REQUEST['Body'], 0, 1600));
    echo(
        "<Response>
          <Message to=\"{$myPhoneNumber}\">
            {$message}
          </Message>
        </Response>"
    );

}

?>

As you can see, the code checks for your phone number. If the message that is received by Twilio is from your number then the code will send it to a number that you put at the start of your message. Your message should be something like this:
+15553331111/ Hey, how is going?

Twilio has some tutorials for masked phone numbers if you need something more elaborated. https://www.twilio.com/docs/tutorials


text:
Q: Calculating $AB$ Here is my diagram

I want to calculate $AB$ and don't have any idea about where to start. Might I get any help for this question?
Regards!

A: Hint : First use the fact that the angles of a triangle always add up to 180º (you know two angles already).
Once you know all the angles, use the Law of Sines:
$$\dfrac{a}{sin \  A}=\dfrac{b}{sin \  B} = \dfrac{c}{sin \  C}$$

A: In this right triangle, by definition$$sin37^o=\frac{AB}{AC}$$So$$AB=ACsin 37^o$$Look up $sin 37^o$, and then take the product $ACsin 37^o$.  When $BC$ rather than $AC$ is given along with $\angle C$, you use $tanC$ to find $AB$, which is a good way to compute the height of things you'd rather not--or can't--measure by climbing them.


text:
Q: How can I filter documents that don't have a list of keys? Say I have a table with documents having keys like:
name, created_at, [likes_to_eat], [likes_to_drink]

The keys between brackets are optional (may or may not be in the document).
I would like to fetch all documents from this table that don't have likes_to_eat and likes_to_drink keys. I've found in the docs that I could do this:
r.table('users').filter(
    lambda user: not user.has_fields('likes_to_eat', 'likes_to_drink')
).run(conn)

But has_fields puts an AND between the keys, whilst I need an OR (so filter a user whether he hasn't got likes_to_eat OR likes_to_drink OR both).
How can I do this?

A: r.table('users').filter(
    lambda user: ~user.has_fields('likes_to_eat', 'likes_to_drink')
).run(conn)

Edit: Made a mistake and used contains intead of has_fields.

A: Seems that I was closer than I thought. I was negating using not instead of ~ (like @neumino suggested). So here's the working snippet:
r.table('users').filter(
    lambda user: ~user.has_fields('likes_to_eat', 'likes_to_drink')
).run(conn)

has_fields actually puts an OR between the given arguments.


text:
Q: Sender address rejected error while sending emails I am developing a ruby on rails application which sends out emails. When I try to send emails from mailer is says 553 : Sender address rejected: not owned by user X.
But I try to send an email manually using Net::SMTP it goes well. I am kind of stuck for the release. Please help!!!

A: Your mail server is configured to check if the client is allowed to send mail with the supplied sender address. Your application does not authenticate itself as a user who is allowed to use the email address ("x" in your question) as a sender.
See this forum post. Likely when you try it manually you are logging in under a different name than your application.


text:
Q: No of Days between two dates in advanced PDF template netsuite Can anybody help in getting difference between two dates in advanced pdf template in netsuite?

A:         <!-- Function -->
        <!-- Calculate Days from a Specific Date --><#function dateDiff date days>
        <#assign timeInMillisecond = (1000 * 60 * 60 *  24 * days) />
        <#assign aDate = date?long + timeInMillisecond?long /><#return aDate?number_to_date>undefined</#function>undefined<!-- Date

        Vars -->undefined<#assign date_today = .now />undefined<#assign date_ten_days_from_today = dateDiff(date_today, 10) />


text:
Q: Powershell object attribute not showing Any idea why the $result.PathName doesn't work?
$results = Get-WMIObject -query "select * from Win32_Service where Name LIKE '%sql%'" | Select Name, PathName | Format-List
ForEach ($result in $results) {
    Write-Output "Test = " + $result.PathName
}
Write-Output "done"

Expected output:
Test = C:\blah\blah.sqlserver.exe
Test = C:\blah\blah.sqlserver.exe

Actual output
Test =
+
Test =
+

A: Format-* cmdlets produce formatting instructions as output. This instructions not useful for anything except displaying result to user or for Out-* cmdlets. Remove Format-List from your code. And put expression after Write-Output in parentheses: Write-Output ("Test = " + $result.PathName), to it be interpreted as single expression but not three different arguments to Write-Output. Or you can remove Write-Output entirely as it implied by default.


text:
Q: js If you add numbers with Math.ceil, they are +1 We added two values using Math.ceil.
One became 50 when I used Math.ceil, and the other became 80 when I used Math.ceil.
For some reason, when I add 50 and 80, the result is 131.
console.log(Math.ceil(e.currentTarget.clientHeight)  // 50
console.log(Math.ceil(e.currentTarget.scrollTop)) // 80
console.log(Math.ceil(e.currentTarget.clientHeight) + Math.ceil(e.currentTarget.scrollTop)); // 131

status of implementation
e.currentTarget.clientHeight // 50
e.currentTarget.scrollTop  // 80.1111145019531

A: Math.ceil(80.1111145019531) = 81
Thus the sum is 131. Math.ceil always rounds up.


text:
Q: Can I use Groovy scripts in SoapUI to enable/disable assertions? I'm using SoapUI Pro and a DataSource/DataSink loop to test a web service.
To make life more fun, I need to pull from four distinct source files, all of which will cause different expected results.
I'd really like to do this in a single test loop, because having scripts with multiple loops tends to crash SoapUI more often than not, but the sticking point is assertions.
How can I enable or disable assertions in a Groovy script in SoapUI? GetData doesn't give me anything to hook onto, and a documentation dive did not reveal the proper syntax. I'd assume something like testCase.assertion, but there's no such property as "assertion" on testCase.
Alternately, can I use a Groovy script to change the assertion's content? In other words, if I want phrase X with file 1, phrase Y with file 2, I'm just as happy using the same assertion, so long as I can change the content it's trying to match.

A: You could use your Groovy script to set some kind of property testCase.setPropertyValue('expected', 'value'), based on which file you are reading. You could then use property expansion ${testCase#expected#} in the assertion content.


text:
Q: Azure Devop TestThe active test run was aborted. Reason: Test host process crashed : Unhandled Exception We have one PR that fails due to our tests sets. They only fail with this PR, with the following error:
The active test run was aborted. Reason: Test host process crashed : Unhandled Exception: System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain.

It always crashes with this error while other branches work fine. It's always the same exception but not everytime at the same position. We tried to enable diagnostic, but it gives absolutely no additional informations:
##[debug]ProxyRunRequest: HandleLogMessage Entered
##[error]RunMessage : The active test run was aborted. Reason: Test host process crashed : Unhandled Exception: System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain.
##[debug]Processed: ##vso[task.logissue type=error;]RunMessage : The active test run was aborted. Reason: Test host process crashed : Unhandled Exception: System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain.

We use Nunit, and the testing part of our YML is the following:
  - task: VSTest@2
    timeoutInMinutes: 180
    inputs:
      testSelector: 'testAssemblies'
      testAssemblyVer2: '*.Test*.dll'
      searchFolder: '$(System.DefaultWorkingDirectory)/$(buildConfiguration)'
      codeCoverageEnabled: false
      platform: 'Any CPU'
      uiTests: false
      configuration: '$(buildConfiguration)'
      runInParallel: true
      resultsFolder: 'testResults'
      runSettingsFile: '$(Build.SourcesDirectory)\azure-tests.runsettings'
      rerunFailedTests: true

The PR is like 200 files and we can't find what could cause the issue, especially since we spent a lot of time testing as its a critical feature for us.
Any idea what we can do to have a better idea of what the problem is? Or what could causes this exception?


text:
Q: scanf char* word in struct shows only the last input I am only allowed to use following headers
#include <stdio.h>
#include <stdlib.h>

and I defined my struct student as following:
struct dict
{
    char* word;
    struct dict* link;
};

There are many functions, but only one function that I have problem right now.
This function inserts a struct dict with certain name at the end of the link.
struct student *Linsert(struct dict *list, char *name)
{
    struct student *pnew;
    struct student *pn;
    int exist = 1;

    pnew = (struct dict *)malloc(sizeof(struct dict));
    pnew -> next = NULL;
    pnew -> name = name;

    if (list != NULL)
    {
        for (pn = list; pn -> next != NULL; pn = pn -> next) ;
        pn -> next = pnew;
    }
    else
        list = pnew;

    return list;
}

Using the following function,

//print all the values in the list
void printList(struct dict* list);

I did this:
int main(void)
{

    struct dict *list = NULL;

    char *name;

    while (1) {
        scanf("%s", name);
        if (name == 'Q')
            break;

        list = Linsert(list, name);
        printList(list);
    }
    return 0;
}

Lets say for input, I typed three
apple banana and orange, my result shows three of my last input.
What is the issue here?

A: I see two problems with your code:

*

*You need to pass scanf a char array of size sufficient to store the input string, not simply a char pointer.

*You need to copy strings passed into Linsert (use strdup).

A: Your main snippet alone has a whole bunch of problems:

*

*name is an uninitialized pointer; it's pointing to some unknown location in memory that you haven't allocated and are allowed to use, therefore causing undefined behaviour. Perhaps you want char name[20] to allocate an array of 20 chars on the stack, and have scanf store the input in this buffer.

*You're comparing a char* (a pointer to the start of a string) to a single char 'Q' - you're comparing a pointer and an integer value as your compiler warnings will tell you. You're not comparing the contents of the string for the value 'Q', you're comparing the memory address of name and the integer value for 'Q'. If you want to compare the string name with the string "Q", use strcmp and check for a return value of 0.
You also want to be making a copy of the variable passed to Linsert otherwise, as you've noticed, you'll be passing a pointer to the same location in memory every time, and a change to this block of memory will change each of your items.
If you turn your compiler warnings up you'll get even more warnings.

A: You are not allocating any memory for the name, so scanf is writing to some random location, and overwriting that every time through the loop.

A: One issue is that you've not allocated storage for the word member to point to.  You have also not allocated space for name to point at.  That is a principle cause of trouble.
You need to allocate space for name; the easiest way is:
char name[128];

You need to allocate space to store the word, and you need to copy the contents of name into the word so that when the next line overwrites name, it does not destroy the saved word.
Adapting your code, you might use:
struct student *Linsert(struct dict *list, char *name)
{
    struct student *pnew;
    struct student *pn;

    pnew = (struct dict *)malloc(sizeof(struct dict));
    if (pnew == 0)
        ...error...
    pnew->next = NULL;
    pnew->word = malloc(strlen(name) + 1);
    if (pnew->word == 0)
        ...error...
    strcpy(pnew->word, name);

    if (list != NULL)
    {
        for (pn = list; pn->next != NULL; pn = pn->next)
            ;
        pn->next = pnew;
    }
    else
        list = pnew;

    return list;
}

Do not omit the error checks on memory allocation - painful though it be.  It will bite you when you forget.
Stylistically, do not use spaces around either -> or .; they are operators that bind very tightly, and they should not be spaced out like other binary operators.
There's a convenient function, strdup(), the duplicates a string, but it is not standard C (it is standard POSIX).

A: Since name is a char pointer, your assignment to the field of each dict struct will use the latest value it points to.


text:
Q: Why doesn't the try catch block catch the promise exception? I'm confused about error handling with promises. The answer might be obvious, but I'm not getting it.
I have the following example code:
var test = async function(){
  throw new Error('Just another error')
}

try {
  test().then()
}
catch(err){
  alert('error: ' + err.toString())
}

In my browser I don't get an alert and Uncaught (in promise) Error in the console. Why is that? Shouldn't the try..catch block handle the error?

A: I can see two possible aspects to your question:

*

*The error being thrown in test is in the synchronous (not asynchronous) part of test. Why is it a promise rejection rather than a synchronous exception?

*The promise from test() is being rejected, why doesn't catch catch that rejection?
#1 - Why is it a rejection?
Because even if an async function throws during the synchronous portion of its work, that just rejects the promise it returns, it doesn't raise a synchronous error. It's just a design decision made during the design of async functions, and a smart one — if it were a synchronous error when throwing in the synchronous part of the function but a promise rejection after that, it would be chaotic and hard to understand. So it's simple: throwing in an async function always rejects its promise.
(This is consistent with how the promise constructor treats the executor callback you pass into it. When you do new Promise((resolve, reject) => /*...*/}), the promise constructor calls your function synchronously, but if you throw during the call, it uses what you throw to reject the promise rather than allowing it to continue as a synchronous exception.)
#2 - Why isn't rejection caught by the catch block?
Because you're not using await. Promise rejections are only exceptions when you are awaiting the promise. If you use the promise methods then/catch/finally to attach handlers, rejection is handled by calling the rejection handler, not by the exception mechanism.
So either use promise methods to attach fulfillment and rejection handlers:
test()
.then(result => {
    // ...use `result` here...
})
.catch(error => {
    // ...handle/report error here...
});

Or use await in an async function (or at the top level of a module if you have top-level await in your enviroment):
// In an `async` function (or the top level of a module in cutting-edge environments)
try {
    const result = await test();
    // ...use `result` here...
}
catch(err){
    // ...handle/report error here...
}


text:
Q: How can I get a client id I would like to develop using Sound Cloud API or SDK.
However, it is currently not possible to create a new app in'Sign up for a new app'.
We would appreciate it if you can tell us how to create an app or get a client ID.

A: Have you tried to log into your soundcloud account and go to your browser console, look for a GET request to the API-V2? It should have a client ID there.
Here's a screenshot.
Soundcloud Clien ID in Browser Console


text:
Q: Does amazon ec2, sqs, or rds has network bandwidth limit? My ingestion pipeline is the following
queue -> ec2 -> rds
I have observe the following, when I have first turn on my ec2 to ingest from sqs the write/second on rds is really fast. But after 4 hours the sql write time starts to increase.
Here is a graph for illustration
Write per second
https://imgur.com/a/X2p6e0D
Queue Depth
https://imgur.com/a/6lewIVD
There is still alot of message in the queue so I verify that not enough data from sqs is not the problem source. I try logging the sql write time. From update to commit, and found out the latency for writing has increase 10 fold so its probably not the cpu credit issue from ec2.  But if I turn the ec2 ingestion off and turn it on a day later I see great performance again.
Here is what I verify

*

*rds cpu credit did not drop too much, barely drop any

*ec2 cpu credit did drop from 150 to 6, but the latency increase in rds starts around 2am and ec2 exhaust its cpu credit around 9am and the bottleneck is still the sqsl write time which increase from 0.002 to 0.04

I am using 2 ec2 t2.micro and 1 t2.medium rds.
I am suspecting there is some network bandwidth limit that I need to change. Or maybe cpu credit on ec2 somehow increase latency on sql write?
Can someone point me the right direction?


text:
Q: proving that a function is homomorphism of rings
I am stuck with this problem.. Can someone please help me? I know the definition of isomorphism, homomorphism, injective, and surjective but that's pretty much it. :(
so part a) it satisfies the first condition f(a+b)=f(a)+f(b) (of being homomorphism) by definition but how would i show the second condition f(ab) = f(a)f(b) ?

A: Since you've proved $\bar h$ is compatible with addition and multiplication in a ring is distributive with respect to addition, all one has to do is checking compatibility with multiplication for monomials:
\begin{align*}\bar h(aX^m\cdot bX^n)&=\bar h(abX^{m+n})=h(ab)X^{m+n}=h(a) h(b) X^m X^n\\&=h(a) X^m \cdot h(b) X^n=\bar h(aX^m)\cdot\bar h(bX^n).\end{align*}


text:
Q: How to replace left_column with center_column just on mobile in Prestashop-1.6 I'd like to replace left_column with center_column just on mobile. It works well on tablet and laptop.
As you can see in attachment I have tried to replace left_column -which is marked with red rectangle- with center_column -which is marked with blue rectangle- just on mobile device.
http://i.imgur.com/9z8XHvI.png

                        {if isset($left_column_size) && !empty($left_column_size)}
                        {$HOOK_LEFT_COLUMN}
                        {/if}
                        {if isset($left_column_size) && isset($right_column_size)}{assign var='cols' value=(12 - $left_column_size - $right_column_size)}{else}{assign var='cols' value=12}{/if}

                        {/if}


text:
Q: Save custom value in sales_shipment_item i have custom attribute ("current_seller_id") in sales_shipment_item table and want to save custom value in it when click on submit invoice
Can any one tell me which event or use plugin method for saving value when data save in sales_shipment_item table.
And also find to know same value save in sales_shipment table. current_seller_id attribute also in sales_shipment table.
Please guide me little bit which event use or plugin ?
Thanks in advance

A: VendorName/ModuleName/etc/event.xml
Past this code
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
 <event name="sales_order_shipment_save_before">
        <observer name="set_attribute_in_order" instance="VendorName/ModuleName\Observer\Shipment" />
    </event>
</config>

make class that define in instance in VendorName/ModuleName\Observer\Shipment
and Past this code
my custom attribute is current_seller_id
<?php
namespace Codility\VendorOrder\Observer;

use Magento\Framework\Event\ObserverInterface;

class Shipment implements ObserverInterface
{
    protected $authSession;
    public function __construct( \Magento\Backend\Model\Auth\Session $authSession,
                                 \Magento\Catalog\Model\Product $product)
    {
        $this->authSession=$authSession;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $current_user_id=$this->authSession->getUser()->getUserId();
        $shipment = $observer->getEvent()->getShipment();
        foreach ($shipment->getItemsCollection() as $item) {
            $item->setCurrentSellerId($current_user_id);
        }
        return $this;
    }
}

This code save value in sales_Shipment_items now as same i want to save value in sales_shippment table.
which method i can make plugin or event ?


text:
Q: Removing columns that contain values for only 1 row I have a dataframe with many columns that give compound values for sample IDs. I'm looking to remove any columns that only appear in one sample ID, therefore keeping columns in which compounds are present in at least 2 sample IDs. Here is a mock dataframe:
df1 <- data.frame(ID = c("A","B","C","D","E","F","G","H","I"),
                  Cmpd_1 = c(5.7,0,0,0,2.5,2.1,0,6.2,1.5),
                  Cmpd_2 = c(0,0,1,0,2.8,0,0,0,0),
                  Cmpd_3 = c(0,0,3.5,0,0,0,0,0,0))

In this example, Cmpd_3 only appears for sample C and I would therefore like the entire column to be removed. Here's what the ideal output would be:
 ID Cmpd_1 Cmpd_2
  A    5.7    0.0
  B    0.0    0.0
  C    0.0    1.0
  D    0.0    0.0
  E    2.5    2.8
  F    2.1    0.0
  G    0.0    0.0
  H    6.2    0.0
  I    1.5    0.0

A: This should work if IDs are unique :
df2 <- df1[,colSums(df1!=0)>1]

A: Using dplyr
library(dplyr)
df1 %>%
    select(where(~ sum(.x != 0, na.rm = TRUE) > 1))


text:
Q: CPU Affinity in Boost::Thread API Is it possible to set CPU affinity in boost threads ((i.e. setting each thread to run on a different CPU)? Is there any tutorial/documentation you can suggest on this? Googling does not return much info except the following thread where the specified example (boost-bind_processor.v1.tar.gz) is no longer present in the file server. Thanks.
http://lists.boost.org/boost-users/2009/02/45172.php

A: In case of .NET apps, you probably need to look into something called ProcessorAffinity.
MSDN 1
MSDN 2
Wiki

A: Just don't. Most of the time when you think this will help things, it just makes them worse.
Every restriction you place on the system has a cost. The scheduler is very smart and the more restrictions you force on it, the worse it will perform. The scheduler will not move a thread from one core to another unless it has a good reason.


text:
Q: Passing a blank value using javascript of jquery Is there a way to pass a "blank" value to a hidden input type?  And when I say blank, I mean an actual whitespace character or something?
For example, I have this select:
    <select name="Sample">
    <option value="BB515_Hu_CD3" >BB515, Human CD3</option>
    </select>

On one form, it's a drop down where a user selects the option. Upon submission, the value of the option gets written to the "Sample" database field.
On another web form that writes to the same database and doesn't have Sample select, I would like to pass a blank value so that the current value in the database field is deleted and empty.
    <input type="hidden" value="" name="Sample" />

I can add a dash '-' in the value and then it will overwrite the BB515_Hu_CD3 value with a dash, but I would rather have a blank field then a dash in it.  Keeping value="" will just keep the original data which I don't want.
Each form has contact matching enabled on it via email address.  So if I use the same email for both forms, the original form submission data will be updated with the second form submission data.
Any ideas on how I can accomplish this?
Thanks in advance.

A: That hidden field should be in the post array as an empty variable.
On the server side you can just insert into the database whatever value is given for Sample.
For example if you have this:
<select name="Sample">
    <option value="" >Choose Sample</option>
    <option value="BB515_Hu_CD3" >BB515, Human CD3</option>
    </select>

or this
<input type="hidden" value="" name="Sample" />

Then server side:
 $data['Sample'] = $_POST['Sample'];//if it is empty it will update the database with an empty string if not then it will update with the value

You can also use a value like - if so, then do this:
if(!empty($_POST['Sample']) && $_POST['Sample'] == '-')
{
$data['Sample'] = "";
}

For the javascript/jquery portion:
// this is the id of the form
$("#idForm").submit(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements automatically
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

alert(data); is where you would handle the response from the server
If it does not work like this in your current code we may need to see the code.  Validation libraries or javascript may do some strange things.


text:
Q: css file cache dot being cleared after new version uploaded to server hi i have a little problem
i uploaded a new version of my website.
and some users complained that they see some page i changed very very wrong.
anyway after a refresh they see it fine.
i think its because my css file got cached by them on an earlier time...
why isnt the browser downloading the css file by himself on first load?..
he should know the css file changed dosnt he?
thanks in advance

A: @UpTheCreek's method will work fine. But you can save some trouble by just changing the call and not changing the filename.
screen.css?v=12

This will also force a reload but will only require you to change the call.

A:
he should know the css file changed
  dosnt he?

Not necessarily. If your css files have been sent from the server with a max-age directive and/or an expiring date far in the future, browser are instructed to not make conditional requests to your resource (see http://developer.yahoo.com/blogs/ydn/posts/2007/05/high_performanc_2/) so they consider the resource in cache still valid.
In this case in order to force a new request you may need to rename the file or append a random querystring like file.css?848372034 or, even better, a version note like file.css?v=1

A: If you install the web developer toolbar (for Firefox or IE) you can disable cache.  I use this when developing websites.  It saves you having to rename your CSS every time you make a minor edit.

A: If you're on Apache try adding this in your root .htaccess:
<FilesMatch ".(css|jpg|gif|ico|jpeg|png|html)$">
ExpiresActive On
Header set Expires "Mon, 22 Nov 2010 06:00:00 GMT"
</FilesMatch> [L]

Include only file types you don't want cached , eg:
<FilesMatch ".(css|js)$">

If you know when you want to change files, set a future date - your site will be faster if these files are not regularly refreshed.
If you don't set an expiry date, browsers cache these files in proportion to their age.


text:
Q: Power Query not Showing Date Properly After Transposed I have the following query table as shown on the first image. But I want that query transposed to horizontal as I want. So I transposed that query table by transposing like on the second image. It is looks good on the power query editor, but the problem is when it appear on the excel sheet, it becomes number like as shown on the third picture. And I don't like it, I want to that date is on the date format, not on the number format.
I actually can select all the second row and change the format to date, but i don't want to do that, I want the formatting automatically changed by the power query itself.

A: You have to add resp. change the M-Code of the query. Either you add a step or you take the following M-Code as an example how to change the data type of all columns to date
let
    src = Excel.CurrentWorkbook(){[Name="table1"]}[Content],
    transTbl = Table.Transpose(src),
    chTypeAll = Table.TransformColumnTypes(transTbl,List.Transform(Table.ColumnNames(transTbl),each {_,type date}))
in
    chTypeAll

The last step named chTypeAll will change the data type of all columns to date. You can add this as a step by pasting the corresponding line into the formula bar.

The yellow marked text should correspondend to the name of the previous step

In case you do not see the formula bar go to View and mark formula bar


text:
Q: percent sign in params to session.get() In Python, I want to execute session.get(url,params={...},). Among my params is a base64 string. Except that the + characters have been converted to %2B and the / characters to %2F. The web server will decode the base64 string into text and run with it before providing a response. Example below, if that is helpful.
I'm finding that the base64 back-translation breaks on the server when it reaches the first percent sign in the base64 string. (In the sample output below, the point where the corruption starts is right where the first % sign is in the base64 string.)
Now, I don't think anything is wrong with the server's base64 translation, because I can manually enter the url into a web browser, with its parameters, and all comes back well. (In fact, here is that url. The result may look like garbage to you, but check out the page source if you are comparing to the garbage below.) So I think that it's Python that is not handling the % the way I'd like it to.
How can I get Python to handle these % characters right? I've tried using %% and that doesn't help.
Here is a live MWE, so it has a really long base64 string in it.
response = session.get('https://webwork/webwork2/html2xml', params={'outputformat': 'simple', 'problemSource': 'IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMjIyBHZW5lcmF0ZWQgZnJvbSBNYXRoQm9vayBYTUwgc291cmNlIAojIyMgICAgb24gMjAxNS0xMC0yNlQxNTo1MDo0OS0wNzowMCAgICAKIyMjICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiMjIyAgIGh0dHA6Ly9tYXRoYm9vay5wdWdldHNvdW5kLmVkdSAgIAojIyMgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMjIERCc3ViamVjdCgpCiMjIERCY2hhcHRlcigpCiMjIERCc2VjdGlvbigpCiMjIExldmVsKCkKIyMgS0VZV09SRFMoKQojIyBUaXRsZVRleHQxKEludGVncmF0aW5nIFdlQldvcksgaW50byBUZXh0Ym9va3MpCiMjIEVkaXRpb25UZXh0MSgpCiMjIEF1dGhvclRleHQxKFJvYmVydCBCZWV6ZXIsIEFsZXggSm9yZGFuKQojIyBTZWN0aW9uMSg4LikKIyMgUHJvYmxlbTEoMSkKIyMgQXV0aG9yKCkKIyMgSW5zdGl0dXRpb24oKQojIyBMYW5ndWFnZShlbi1VUykKCkRPQ1VNRU5UKCk7CgojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyBMb2FkIE1hY3JvcwojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKbG9hZE1hY3JvcygKICAgICJQR3N0YW5kYXJkLnBsIiwKICAgICJNYXRoT2JqZWN0cy5wbCIsCiAgICAiUEdNTC5wbCIsCiAgICAiQW5zd2VyRm9ybWF0SGVscC5wbCIsCiAgICAiUEdncmFwaG1hY3Jvcy5wbCIsCiAgICAiUEdjb3Vyc2UucGwiLAopOwoKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMgSGVhZGVyCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwpDT01NRU5UKCdBdXRob3JlZCBpbiBNYXRoQm9vayBYTUwnKTsKVEVYVChiZWdpbnByb2JsZW0oKSk7CgojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyBQRyBTZXR1cAojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKQ29udGV4dCgnTnVtZXJpYycpOwokYW5zd2VyID0gcmFuZG9tKDEsMywxKTsKJGdyID0gaW5pdF9ncmFwaCgtMSwtMSw0LDQsCmF4ZXM9PlswLDBdLApncmlkPT5bNSw1XSwKc2l6ZT0%2BWzQwMCw0MDBdCik7CmFkZF9mdW5jdGlvbnMoJGdyLCAieF4zLyRhbnN3ZXJeMyBmb3IgeCBpbiA8LTEsND4gdXNpbmcgY29sb3I6Ymx1ZSBhbmQgd2VpZ2h0OjIiKTsKJHNlY29uZF94ID0gUmVhbCgkYW5zd2VyKjIqKigxLzMpKTsKCiRzb2xnciA9IGluaXRfZ3JhcGgoLTEsLTEsNCw0LApheGVzPT5bMCwwXSwKZ3JpZD0%2BWzUsNV0sCnNpemU9Pls0MDAsNDAwXQopOwphZGRfZnVuY3Rpb25zKCRzb2xnciwgInheMy8kYW5zd2VyXjMgZm9yIHggaW4gPC0xLDQ%2BIHVzaW5nIGNvbG9yOmJsdWUgYW5kIHdlaWdodDoyIik7CiRzb2xnci0%2BbW92ZVRvKDAsMSk7CiRzb2xnci0%2BbGluZVRvKCRhbnN3ZXIsMSwnYmxhY2snLDMpOwokc29sZ3ItPmFycm93VG8oJGFuc3dlciwwLCdibGFjaycsMyk7CgojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyBCb2R5CiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwpCRUdJTl9QR01MClRoZSBncmFwaCBiZWxvdyBpcyBhIGdyYXBoIG9mIFtgeT1mKHgpYF0uIFVzZSB0aGUgZ3JhcGggdG8gc29sdmUgdGhlIGVxdWF0aW9uIFtgZih4KT0xYF0uCgo%2BPiBbQCBpbWFnZShpbnNlcnRHcmFwaCgkZ3IpLCB3aWR0aD0%2BNDAwLCBoZWlnaHQ9PjQwMCwgdGV4X3NpemU9PjgwMCwgZXh0cmFfaHRtbF90YWdzPT5xcSFhbHQ9IiIhKUBdKiA8PAoKPj4gW2B4PWBdIFtfX19fX117JGFuc3dlcn0gW0BBbnN3ZXJGb3JtYXRIZWxwKCdudW1iZXJzJylAXSogPDwKCgpFTkRfUEdNTAoKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMgU29sdXRpb24KIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCkJFR0lOX1BHTUxfU09MVVRJT04KVGhlIGdyYXBoIHJldmVhbHMgdGhhdCB0aGUgb25seSBzb2x1dGlvbiB0byBbYGYoeCk9MWBdIGlzIFtgeD1bJGFuc3dlcl1gXS4KCj4%2BIFtAIGltYWdlKGluc2VydEdyYXBoKCRzb2xnciksIHdpZHRoPT40MDAsIGhlaWdodD0%2BNDAwLCB0ZXhfc2l6ZT0%2BODAwLCBleHRyYV9odG1sX3RhZ3M9PnFxIWFsdD0iIiEpQF0qIDw8CgoKRU5EX1BHTUxfU09MVVRJT04KCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwojIEVuZCBQcm9ibGVtCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwpFTkRET0NVTUVOVCgpOwo=', 'courseID': 'anonymous', 'userID': 'anonymous', 'displayMode': 'tex', 'problemSeed': '123567890', 'password': 'anonymous', 'answersSubmitted': '0'}, verify=False)

And then when I look at response.text I see the following. You can ignore all of the html wrapper. The text that was being back-translated breaks down where it counts lines, at line 50, and I've discovered that is precisely where the first % sign is in the original base64 string.
<!DOCTYPE html>

<link rel="shortcut icon" href="/webwork2_files/images/favicon.ico"/>

<link rel="stylesheet" type="text/css" href="/webwork2_files/js/vendor/bootstrap/css/bootstrap.css"/>
<link href="/webwork2_files/js/vendor/bootstrap/css/bootstrap-responsive.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="/webwork2_files/css/jquery-ui-1.8.18.custom.css"/>
<link rel="stylesheet" type="text/css" href="/webwork2_files/css/vendor/font-awesome/css/font-awesome.min.css"/>
<link rel="stylesheet" type="text/css" href="/webwork2_files/themes/math4/math4.css"/>
<link href="/webwork2_files/css/knowlstyle.css" rel="stylesheet" type="text/css" />

<base href="https://webwork.pcc.edu/mod_xmlrpc">
<title>https://webwork.pcc.edu/mod_xmlrpc WeBWorK Editor using host: https://webwork.pcc.edu/mod_xmlrpc, format: simple seed: 123567890</title>

            <form action="https://webwork.pcc.edu/webwork2/html2xml" method="post">

        Problem13
1. ERROR caught by Translator while processing problem file:WebworkClient.pm:: define fileName in environment
****************
ERRORS from evaluating PG file:
 Unrecognized character \x05; marked by <-- HERE after 5],
size=6<-- HERE near column 562 at line 50 of (eval 1135)

****************

------Input Read
1       #######################################
2       ### Generated from MathBook XML source
3       ###    on 2015-10-26T15:50:49-07:00
4       ###
5       ###   http://mathbook.pugetsound.edu
6       ###
7       #######################################
8       ## DBsubject()
9       ## DBchapter()
10      ## DBsection()
11      ## Level()
12      ## KEYWORDS()
13      ## TitleText1(Integrating WeBWorK into Textbooks)
14      ## EditionText1()
15      ## AuthorText1(Robert Beezer, Alex Jordan)
16      ## Section1(8.)
17      ## Problem1(1)
18      ## Author()
19      ## Institution()
20      ## Language(en-US)
21
22      DOCUMENT();
23
24      ############################################################
25      # Load Macros
26      ############################################################
27      loadMacros(
28          "PGstandard.pl",
29          "MathObjects.pl",
30          "PGML.pl",
31          "AnswerFormatHelp.pl",
32          "PGgraphmacros.pl",
33          "PGcourse.pl",
34      );
35
36      ############################################################
37      # Header
38      ############################################################
39      COMMENT('Authored in MathBook XML');
40      TEXT(beginproblem());
41
42      ############################################################
43      # PG Setup
44      ############################################################
45      Context('Numeric');
46      $answer = random(1,3,1);
47      $gr = init_graph(-1,-1,4,4,
48      axes=>[0,0],
49      grid=>[5,5],
50      size=6l�������t(��)���}�չ�ѥ��̠��Ȱ���x̼����ݕ�x́��ȁ�����İ����ͥ��������鉱Ք�����ݕ�����Ȉ��(�͕����}��I��������ݕȨȨ��ļ̤��((�ͽ��Ȁ��}�Ʌ����İ�İаа)�����l���t�)�ɥ����R�U���6��S��C�CТ���FE�gV�7F���2�G6��w"�'��2�F�7vW%�2f�"������C`H\�[����܎��H[�ZY����N��܋M�moveTo(0,1);
51      $solgr-6����Q������ݕȰİ��������̤�(�ͽ��ȴ���ɽ�Q������ݕȰ����������̤�((������������������������������������������������������������(��   ���(������������������������������������������������������������)   %9}A50)Q����Ʌ�������܁�́���Ʌ������m�����ुt��U͔�ѡ���Ʌ���Ѽ�ͽ�ٔ�ѡ����Յѥ���m�����Łt�((�����vR���6W'Dw&��Fw"��v�GF��`M

                    ZY�O�

                        ^��^�OO�

                               ^�W����O�\HX[H��JPJ������XH������^�[���\�H�[���\��ܛX][
52          ۝[X�\���PJ����S���S����������������������������������������������������������������][ۂ�������������������������������������������������������������Q�S���S���USӂ�Hܘ�]�X[�Hۛ��][ۈ���
3       OLXH\��V�[���\�XK����� [@ image(insertGraph($solgr), width=>400, height=6�����ѕ�}ͥ�����W�G&��F���Fw3���C�""�Ң�����T�E�t���4��UD��ࠢ222222222222222222222222222222222222222222222222222222222220�2V�B&�&�VТ222222222222222222222222222222222222222222222222222222222220�T�DD�5T�T�B���

-----

           <input type="hidden" name="answersSubmitted" value="1">
           <input type="hidden" name="sourceFilePath" value = "">
           <input type="hidden" name="problemSource" value="IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMjIyBHZW5lcmF0ZWQgZnJvbSBNYXRoQm9vayBYTUwgc291cmNlIAojIyMgICAgb24gMjAxNS0xMC0yNlQxNTo1MDo0OS0wNzowMCAgICAKIyMjICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiMjIyAgIGh0dHA6Ly9tYXRoYm9vay5wdWdldHNvdW5kLmVkdSAgIAojIyMgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMjIERCc3ViamVjdCgpCiMjIERCY2hhcHRlcigpCiMjIERCc2VjdGlvbigpCiMjIExldmVsKCkKIyMgS0VZV09SRFMoKQojIyBUaXRsZVRleHQxKEludGVncmF0aW5nIFdlQldvcksgaW50byBUZXh0Ym9va3MpCiMjIEVkaXRpb25UZXh0MSgpCiMjIEF1dGhvclRleHQxKFJvYmVydCBCZWV6ZXIsIEFsZXggSm9yZGFuKQojIyBTZWN0aW9uMSg4LikKIyMgUHJvYmxlbTEoMSkKIyMgQXV0aG9yKCkKIyMgSW5zdGl0dXRpb24oKQojIyBMYW5ndWFnZShlbi1VUykKCkRPQ1VNRU5UKCk7CgojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyBMb2FkIE1hY3JvcwojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKbG9hZE1hY3JvcygKICAgICJQR3N0YW5kYXJkLnBsIiwKICAgICJNYXRoT2JqZWN0cy5wbCIsCiAgICAiUEdNTC5wbCIsCiAgICAiQW5zd2VyRm9ybWF0SGVscC5wbCIsCiAgICAiUEdncmFwaG1hY3Jvcy5wbCIsCiAgICAiUEdjb3Vyc2UucGwiLAopOwoKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMgSGVhZGVyCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwpDT01NRU5UKCdBdXRob3JlZCBpbiBNYXRoQm9vayBYTUwnKTsKVEVYVChiZWdpbnByb2JsZW0oKSk7CgojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyBQRyBTZXR1cAojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKQ29udGV4dCgnTnVtZXJpYycpOwokYW5zd2VyID0gcmFuZG9tKDEsMywxKTsKJGdyID0gaW5pdF9ncmFwaCgtMSwtMSw0LDQsCmF4ZXM9PlswLDBdLApncmlkPT5bNSw1XSwKc2l6ZT0%2BWzQwMCw0MDBdCik7CmFkZF9mdW5jdGlvbnMoJGdyLCAieF4zLyRhbnN3ZXJeMyBmb3IgeCBpbiA8LTEsND4gdXNpbmcgY29sb3I6Ymx1ZSBhbmQgd2VpZ2h0OjIiKTsKJHNlY29uZF94ID0gUmVhbCgkYW5zd2VyKjIqKigxLzMpKTsKCiRzb2xnciA9IGluaXRfZ3JhcGgoLTEsLTEsNCw0LApheGVzPT5bMCwwXSwKZ3JpZD0%2BWzUsNV0sCnNpemU9Pls0MDAsNDAwXQopOwphZGRfZnVuY3Rpb25zKCRzb2xnciwgInheMy8kYW5zd2VyXjMgZm9yIHggaW4gPC0xLDQ%2BIHVzaW5nIGNvbG9yOmJsdWUgYW5kIHdlaWdodDoyIik7CiRzb2xnci0%2BbW92ZVRvKDAsMSk7CiRzb2xnci0%2BbGluZVRvKCRhbnN3ZXIsMSwnYmxhY2snLDMpOwokc29sZ3ItPmFycm93VG8oJGFuc3dlciwwLCdibGFjaycsMyk7CgojIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyBCb2R5CiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwpCRUdJTl9QR01MClRoZSBncmFwaCBiZWxvdyBpcyBhIGdyYXBoIG9mIFtgeT1mKHgpYF0uIFVzZSB0aGUgZ3JhcGggdG8gc29sdmUgdGhlIGVxdWF0aW9uIFtgZih4KT0xYF0uCgo%2BPiBbQCBpbWFnZShpbnNlcnRHcmFwaCgkZ3IpLCB3aWR0aD0%2BNDAwLCBoZWlnaHQ9PjQwMCwgdGV4X3NpemU9PjgwMCwgZXh0cmFfaHRtbF90YWdzPT5xcSFhbHQ9IiIhKUBdKiA8PAoKPj4gW2B4PWBdIFtfX19fX117JGFuc3dlcn0gW0BBbnN3ZXJGb3JtYXRIZWxwKCdudW1iZXJzJylAXSogPDwKCgpFTkRfUEdNTAoKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCiMgU29sdXRpb24KIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjCkJFR0lOX1BHTUxfU09MVVRJT04KVGhlIGdyYXBoIHJldmVhbHMgdGhhdCB0aGUgb25seSBzb2x1dGlvbiB0byBbYGYoeCk9MWBdIGlzIFtgeD1bJGFuc3dlcl1gXS4KCj4%2BIFtAIGltYWdlKGluc2VydEdyYXBoKCRzb2xnciksIHdpZHRoPT40MDAsIGhlaWdodD0%2BNDAwLCB0ZXhfc2l6ZT0%2BODAwLCBleHRyYV9odG1sX3RhZ3M9PnFxIWFsdD0iIiEpQF0qIDw8CgoKRU5EX1BHTUxfU09MVVRJT04KCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwojIEVuZCBQcm9ibGVtCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIwpFTkRET0NVTUVOVCgpOwo=">
           <input type="hidden" name="problemSeed" value="123567890">
           <input type="hidden" name="pathToProblemFile" value="">
           <input type="hidden" name=courseName value="anonymous">
           <input type="hidden" name=courseID value="anonymous">
           <input type="hidden" name="userID" value="anonymous">
           <input type="hidden" name="password" value="anonymous">
           <input type="hidden" name="passwd" value="anonymous">
           <input type="hidden" name="displayMode" value="tex">
           <input type="hidden" name="session_key" value="Y8EvKT3YOawEPFVA7XH3MepsK63uAkED">
           <input type="hidden" name="outputformat" value="simple">

                      <input type="submit" name="WWcheck" value="Check answer(s)"/>
              <input type="submit" name="WWgrade" value="Show correct answer(s)"/>

           </form>

Complicating the mystery, you can see in the HTML input tags that the server has at some level received the base64 string with no trouble. It matches the original one, percent signs and all.


text:
Q: 18.04 LTS Machine hangs after a while, syslog full of gdm-x-session commands Lately my 18.04 machine has been hanging after being unattended for a while. The mouse can be moved but everything else is unresponsive, requiring a hard powercycle. /var/log/syslog is full of this, repeating every minute or so:
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): EDID vendor "SAM", prod id 3148
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Using hsync ranges from config file
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Using vrefresh ranges from config file
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Printing DDC gathered Modelines:
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "3840x2160"x0.0  594.00  3840 4016 4104 4400  2160 2168 2178 2250 +hsync +vsync (135.0 kHz eP)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1920x1080"x0.0  148.50  1920 2008 2052 2200  1080 1084 1089 1125 +hsync +vsync (67.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1920x1080"x0.0  148.50  1920 2448 2492 2640  1080 1084 1089 1125 +hsync +vsync (56.2 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1280x720"x0.0   74.25  1280 1390 1430 1650  720 725 730 750 +hsync +vsync (45.0 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "2560x1440"x0.0  241.50  2560 2608 2640 2720  1440 1443 1448 1481 +hsync -vsync (88.8 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "720x576"x0.0   27.00  720 732 796 864  576 581 586 625 -hsync -vsync (31.2 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "720x480"x0.0   27.00  720 736 798 858  480 489 495 525 -hsync -vsync (31.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1280x720"x0.0   74.25  1280 1720 1760 1980  720 725 730 750 +hsync +vsync (37.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1920x1080"x0.0   74.25  1920 2558 2602 2750  1080 1084 1089 1125 +hsync +vsync (27.0 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1920x1080"x0.0   74.25  1920 2008 2052 2200  1080 1084 1089 1125 +hsync +vsync (33.8 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "800x600"x0.0   40.00  800 840 968 1056  600 601 605 628 +hsync +vsync (37.9 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "800x600"x0.0   36.00  800 824 896 1024  600 601 603 625 +hsync +vsync (35.2 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "640x480"x0.0   31.50  640 656 720 840  480 481 484 500 -hsync -vsync (37.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "640x480"x0.0   31.50  640 664 704 832  480 489 492 520 -hsync -vsync (37.9 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "640x480"x0.0   30.24  640 704 768 864  480 483 486 525 -hsync -vsync (35.0 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "640x480"x0.0   25.18  640 656 752 800  480 490 492 525 -hsync -vsync (31.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "720x400"x0.0   28.32  720 738 846 900  400 412 414 449 -hsync +vsync (31.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1280x1024"x0.0  135.00  1280 1296 1440 1688  1024 1025 1028 1066 +hsync +vsync (80.0 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1024x768"x0.0   78.75  1024 1040 1136 1312  768 769 772 800 +hsync +vsync (60.0 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1024x768"x0.0   75.00  1024 1048 1184 1328  768 771 777 806 -hsync -vsync (56.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1024x768"x0.0   65.00  1024 1048 1184 1344  768 771 777 806 -hsync -vsync (48.4 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "832x624"x0.0   57.28  832 864 928 1152  624 625 628 667 -hsync -vsync (49.7 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "800x600"x0.0   49.50  800 816 896 1056  600 601 604 625 +hsync +vsync (46.9 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "800x600"x0.0   50.00  800 856 976 1040  600 637 643 666 +hsync +vsync (48.1 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1152x864"x0.0  108.00  1152 1216 1344 1600  864 865 868 900 +hsync +vsync (67.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1280x800"x0.0   71.00  1280 1328 1360 1440  800 803 809 823 +hsync -vsync (49.3 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1280x1024"x0.0  108.00  1280 1328 1440 1688  1024 1025 1028 1066 +hsync +vsync (64.0 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1440x900"x0.0   88.75  1440 1488 1520 1600  900 903 909 926 +hsync -vsync (55.5 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1600x900"x60.0  119.00  1600 1696 1864 2128  900 901 904 932 -hsync +vsync (55.9 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (II) modeset(0): Modeline "1680x1050"x0.0  119.00  1680 1728 1760 1840  1050 1053 1059 1080 +hsync -vsync (64.7 kHz e)
Jul 14 01:25:16 dev01 /usr/lib/gdm3/gdm-x-session[1403]: (--) modeset(0): HDMI max TMDS frequency 300000KHz
Jul 14 01:25:16 dev01 gsd-color[1161]: failed to set screen _ICC_PROFILE: Failed to open file "/home/pieter/.local/share/icc/edid-ba82e4a836c294b5db9fe75f7f5dcd3b.icc": Permission denied

A: I found out that the package read-edid causes this. No more issues after uninstalling.


text:
Q: What's behind Excel Solver Evolutionary? I have an optimization problem on Excel, using Evolutionary algorithm.
Works fine, but i'd like to understand how it gets to the solution, ie what is or are the exact method(s) used.
Is that available anywhere ?
The final purpose being to move this project from Excel to a Java program, because it gets more and more complex.
Thank you

A: Do the same optimization in LibreOffice Calc. Algorithms done in LibreOffice Calc are available as part of the open-source project.


text:
Q: Make sure that activity starts after execution of async task I want to make sure that my activity starts after execution of async task. As of now it gets started before the async task completes in background
This is where new activity is called. Before calling the new activity i am calling PagerAsyncTask. I want to make sure that new activity is called only after successful completion of PagerAsyncTask.
 protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        new PagerAsyncTask().execute();
            sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
            SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putBoolean("hasadd", false);
            editor.commit();
            Log.e("hi", "dsscdds");
            startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));

PagerAsyncTask
   class PagerAsyncTask extends AsyncTask<String,Void,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            StringBuilder sb=null;
            BufferedReader reader=null;
            String serverResponse=null;
            try {

                URL url = new URL("https://enigmatic-woodland-35608.herokuapp.com/pager.json");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                connection.connect();
                int statusCode = connection.getResponseCode();
                //Log.e("statusCode", "" + statusCode);
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                }

                connection.disconnect();
                if (sb!=null)
                    serverResponse=sb.toString();
                Log.e("haha", serverResponse);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return serverResponse;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //All your UI operation can be performed here
            //Response string can be converted to JSONObject/JSONArray like
            try {
//String mr[] = new String[5];
                JSONObject response=new JSONObject(s);
                Iterator<?> keys = response.keys();
                int i=0;

                while( keys.hasNext() ) {

                    String key = (String)keys.next();
                    Log.e("hi",key);
                    Log.e("hey",response.getString(key));
//                    mr[i]=response.getString(key);
//                    Log.e("e=",mr[i]);
                    i++;

                }
                Log.e("I", String.valueOf(i));
                Iterator<?> keys1 = response.keys();
                mr = new String[i];
                int k=0;
                while ( keys1.hasNext() )
                {
                    String key = (String)keys1.next();
                    mr[k++]=response.getString(key);
                    Log.e("fdvfd",mr[k-1]);
                }
                for (int j=0;j<mr.length;j++)
                {
                    Log.e("dsd",mr[j]);
                }
                isComplete=true;
                setMr(mr);
                setSet(1);
                new RestaurantFragment().setmResources(mr);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

A: You need to move the startActivity to the postExecute of the AsyncTask.
Your onCreate without the startActivity:
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    new PagerAsyncTask().execute();
    sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
    SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
    editor.putBoolean("hasadd", false);
    editor.commit();
    Log.e("hi", "dsscdds");

The PagerAsyncTask onPostExecute:
@Override
protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //All your UI operation can be performed here
        //Response string can be converted to JSONObject/JSONArray like
        try {
            JSONObject response=new JSONObject(s);
            Iterator<?> keys = response.keys();
            int i=0;

            while( keys.hasNext() ) {

                String key = (String)keys.next();
                Log.e("hi",key);
                Log.e("hey",response.getString(key));|
                i++;

            }
            Log.e("I", String.valueOf(i));
            Iterator<?> keys1 = response.keys();
            mr = new String[i];
            int k=0;
            while ( keys1.hasNext() )
            {
                String key = (String)keys1.next();
                mr[k++]=response.getString(key);
                Log.e("fdvfd",mr[k-1]);
            }
            for (int j=0;j<mr.length;j++)
            {
                Log.e("dsd",mr[j]);
            }
            isComplete=true;
            setMr(mr);
            setSet(1);
            new RestaurantFragment().setmResources(mr);
            startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));
        } catch (JSONException e) {
            e.printStackTrace();
        }

Also, the code new RestaurantFragment().setmResources(mr); probably does nothing, since you are not attaching the fragment to anywhere

A: There are a couple of ways to do this
1) use startActivity inside onPostExecute()
2)Pass activity reference to Async task and call some function in the activity from onPostExecute as show here
3)pass a function callback to AsyncTask as shown here. Though this is unnecessarily complicated for your task


text:
Q: Is assigning a type to an enum standard C? I have seen enum declarations like this:
enum ProgrammingLanguage: unsigned char {
    C = 0,
    CPlusPlus,
    Rust,
    Java,
    Javascript,
    Python
};

This only allocates one byte for this type. My question is, is this standard C or a GCC extension? Do I need to worry about portability if I decide to do this?

A:
is this standard C

No, this is not a part of C language.

a GCC extension?

No, this is not a GCC extension in C language.

Do I need to worry about portability if I decide to do this?

You need to worry about compiling such code at all with any C compiler.
This is solely C++ feature.

Then it is a macOS feature. Compiling it in Xcode in a C file works

It is a clang extension.

A: Appendix A 6.7.2.2 defines an enum as:
(6.7.2.2) enum-specifier:
  enum identifier-opt { enumerator-list }
  enum identifier-opt { enumerator-list,}
  enum identifier


text:
Q: When did this post go CW? Looking at the revision history here it isn't apparent that the question is CW. It was not initially created as CW so when did it get converted to it? Did 4 edits trip the Auto-CW rule? (3 by Author, 1 by other user)

A: When a question gets 30 answers it automatically becomes CW.
See the FAQ for Community Wiki posts for more info about them than you can shake a waffle at.


text:
Q: How to move one element to the left of a fixed array int array[10] = {1,2,3,4,5}

from my understanding, the rest of the indexes that haven't been assign a value will be 0. If I want to move every element to the left (I am wanting to remove the first value i.e. index 0). How do I do this without causing duplicate values for the last index with a integer assigned?
For example:
current array
output: 1234500000

+1 to the left:
output: 2345500000

I tried the following code:
void order_array(int size, int array[])
{
    for (int i = 0; i < size-1; i++)
    {
        if (array[i] == 0)
        {
            array[i-1] = 0;
        }
        array[i] = array[i+1];
    }
}

expected output after method execution:
output: 2345000000

Also before someone says this is a duplicate, I have looked around and no thread explains with fixed arrays, i.e. with 0's as default values.
Appreciate your response.

A:     if (array[i] == 0)
    {
        array[i-1] = 0;
    }

I don't understand why this block is there. It's not possible to get inside the if statement.
With your expected output and given this is an array of ints, I suspect the solution is to only output four values in your print statement, but if the last element of the array should be zero, you can just do this after your for loop:
array[size-1] = 0;

A: #include <stdio.h>

#define ARRAY_SIZE 10

void order_array(int size, int* array) {
    for (int i = 0; i < size; i++) {

        if (!array[i]) {
            continue;
        }

        if (i + 1 < size)
            array[i] = array[i + 1];
    }
}

int main() {
    int array[ARRAY_SIZE] = {1, 2, 3, 4, 5};
    printf("intput: ");
    for (int i = 0; i < ARRAY_SIZE; i++) {
        printf("%d", array[i]);
    }
    printf("\n");

    order_array(ARRAY_SIZE, array);

    printf("output: ");
    for (int i = 0; i < ARRAY_SIZE; i++) {
        printf("%d", array[i]);
    }
    printf("\n");

    return 0;
}

Maybe you should consider the last value that not equal to default value 0.
Execute in shell:
gcc -o a.out a.c && ./a.out
intput: 1234500000
output: 2345000000

A: If you don't want rotation then:
int arr[];  //initialize it
int siz=sizeof(arr)/sizeof(arr[0]);
int index=0;

while(index<siz-1)
{
    arr[index]=arr[index+1];
    index++;
}

arr[index]=0;  //0 default value at the end of the array

This will work fine

A: You just need to manually set the last value to zero at the end.  I'd also consider using the built-in memmove function which is designed for moving around data where the source and destination overlap.
void order_array(int size, int array[]){
    memmove(array, array+1, (size-1) * sizeof(array[0]));
    array[size-1] = 0;
}


text:
Q: Pros and Cons of loading content for a welcome stream from a Data Extension This may get flagged as it's opinion based, but I want to see what the experts think.
We are about to build a Welcome Stream and I can do it one of two ways.
The first way is to build it all as HTML and set up my Journey in Journey Builder. Pretty straightforward.
The second is to build my emails with HTML and AMPScript that calls data extensions to load the content. It should be fairly simple because 10 emails could likely call one data extension, look for it's own filename, and grab the content it needs. I see the pros in this. Easy to update and I don't have to restart the triggered send if we want to update the content. But does anyone see cons with this approach?


text:
Q: Getting different error in different browsers while use "AND" and "normalize-space" in a Xpath I have following simple button in my webpage -
<button type="button" class=" m-form-btn" onclick="myFunction()">Save</button>

As class name having one white space So I'm Using normalize-space() -
driver.findElement(By.xpath("//button[@type='button'][normalize-space(@class='m-form-btn')]")).click();

Which is Working fine in right way but while I do use AND in this way-
driver.findElement(By.xpath("//button[@type='button' AND normalize-space(@class='m-form-btn')]")).click();

//or

driver.findElement(By.xpath("//button[normalize-space(@class)='m-form-btn' AND @type='button']")).click();

Getting Error in Firefox -

Exception in thread "main"
  org.openqa.selenium.remote.UnreachableBrowserException: Error
  communicating with the remote browser. It may have died. Build info:
  version: 'unknown', revision: '1969d75', time: '2016-10-18 09:43:45
  -0700' System info: host: 'TSS167', ip: '192.168.1.167', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version:
  '1.8.0_91' Driver info: driver.version: RemoteWebDriver Capabilities
  [{rotatable=false, raisesAccessibilityExceptions=false,
  marionette=true, firefoxOptions={args=[], prefs={}},
  appBuildId=20161208153507, version=, platform=XP, proxy={},
  command_id=1, specificationLevel=0, acceptSslCerts=false,
  processId=7824, browserVersion=50.1.0, platformVersion=6.3,
  XULappId={ec8030f7-c20a-464f-9b0e-13a3a9e97384}, browserName=firefox,
  takesScreenshot=true, takesElementScreenshot=true,
  platformName=windows_nt}] Session ID:
  30ed9c92-2d49-4c7b-83bc-c1638e24b3e8  at
  org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:622)
    at
  org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:368)
    at
  org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:473)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:361)  at
  org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
    at ClassEight.main(ClassEight.java:28) Caused by:
  java.lang.IllegalArgumentException: expected one element but was:
    at
  com.google.common.collect.Iterators.getOnlyElement(Iterators.java:322)
    at
  com.google.common.collect.Iterables.getOnlyElement(Iterables.java:284)
    at
  org.openqa.selenium.remote.ErrorCodes.toStatus(ErrorCodes.java:138)
    at
  org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:92)
    at
  org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:42)
    at
  org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:163)
    at
  org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    at
  org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    ... 5 more

And Following error for the same in Chrome -

Exception in thread "main"
  org.openqa.selenium.InvalidSelectorException: invalid selector: Unable
  to locate an element with the xpath expression
  //button[normalize-space(@class)='m-form-btn' AND @type='button']
  because of the following error: SyntaxError: Failed to execute
  'evaluate' on 'Document': The string
  '//button[normalize-space(@class)='m-form-btn' AND @type='button']' is
  not a valid XPath expression.

I did evaluate both xpath using firepath where I'm Getting the expected output.
I don't know what causing the problem, I'm using AND with normalize-space Is it so ? or anything I'm doing wrong ?
Using selenium 3.0.1

A: Using OR or AND in uppercase in XPath is wrong way (at least in Selenium). You should use or/and instead. So try
driver.findElement(By.xpath("//button[normalize-space(@class)='m-form-btn' and @type='button']")).click();


text:
Q: Pytorch Exception in Thread: ValueError: signal number 32 out of range I'm getting this error:
Exception in Thread: ValueError: signal number 32 out of range

The specific tutorial that raises an issue for me is the training a classifier (https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html), the specific line is:
dataiter = iter(trainloader)

and the full error traceback is:
Exception in thread Thread-5:
Traceback (most recent call last):
File "/home/chenchen/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/home/chenchen/anaconda3/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/chenchen/anaconda3/lib/python3.6/multiprocessing/resource_sharer.py", line 139, in _serve
signal.pthread_sigmask(signal.SIG_BLOCK, range(1, signal.NSIG))
File "/home/chenchen/anaconda3/lib/python3.6/signal.py", line 60, in pthread_sigmask
sigs_set = _signal.pthread_sigmask(how, mask)
ValueError: signal number 32 out of range

My operation system is Ubuntu 18.10 and my python env is Anaconda3 for python 3.6. I installed pytorch from the latest source. My cuda version is 10.0.

A: Looks like this was a bug in Python (https://bugs.python.org/issue33329).
For Python 3.6, it got fixed in 3.6.6, released around July 2019 (see the release notes mentioning it). (You can check which version you have by running python3 --version.)
For Python 3.5, you'd want at least 3.5.7 (... release notes).
Meanwhile... I haven't tried this personally, but Ubuntu 18.10 seems to have Python 3.6.7 available, so a simple sudo apt install python3.6 might solve this?

A: I have faced a similar issue and it got resolved when I set:
num_workers=0

A: I updated the python version from 3.5 to 3.6.1 by using pip install python==3.6.1 and that resolved the problem.


text:
Q: AngularJS Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin I'm developing a web app with AngularJS. It consists in an admin interface that rely on an json-rpc API that resides on another domain.
In my local enviroment, if I make a Request (with AngularJS) to API server I get the error "Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin" in my console Browser".
I've read the limit of modern browsers to blocking the request to another domain, but.... if there is no solution...  Do I need to create my web service (with one backend language: es: PHP or Python) that make requests to API web server and then make the AngularJS request to this?
Why I need another "web server" in the middle of my application infrastructure?
Thanks in advance.
F.
Update: I've read about crossdomain.xml file here: http://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
Does it could be, in someway,  the solution of my problem?

A: Because server must send headers with CORS enabled when responding to ajax requests. Something like:
'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Credentials', true
'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
'Access-Control-Allow-Headers', 'Content-Type'
But read more about CORS to protect your server.
Current internet browsers checks for these headers when You are sending ajax communication. It is for security reasons.

A: Having a web server is always an option, but if you want to stay on the client, consider using JSONP. Read about it here: What is JSONP all about?


text:
Q: Indicate y-Axis does not start at 0 in matplotlib without multiple subgraphs I am aware of the broken axis example from matplotlib but am wondering if there is a purely optical solution to this problem if you do not want to actually plot two different areas of the scale but just optically indicate that the graph is not starting at 0.
How to just add to // to the axis as is? Ugly solutions welcome (i.e. having the axis go through as in ---/-/--- instead of ---/ /---)

A: One way to do what you want from the broken axis code example you provided in your question is to use the second axis ax2 as a placeholder axis with an height_ratio of 0. The only thing you would be plotting onto this axis is the bottom horizontal line that shows that the axis is not starting at 0. Due to the height ratio of your ax2 being equal to 0, only horizontal lines can be plotted onto the ax2 axis which means that you should also modify the diagonal plotted on your ax axis to horizontal lines:
See code below for more details:
import matplotlib.pyplot as plt
import numpy as np

pts = np.array([
    0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018,
    0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075,
    0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008])

pts[[3, 14]] += .8

f, (ax, ax2) = plt.subplots(2, 1, sharex=True,gridspec_kw={'height_ratios': [1, 0]})

ax.plot(pts)
ax.set_ylim(.78, 1.)  # outliers only

ax.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)

ax.xaxis.tick_top()
ax.tick_params(labeltop=False)  # don't put tick labels at the top
ax2.xaxis.tick_bottom()

d = .015
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((-d, +d), (-d, -d), **kwargs)
ax.plot((1 - d, 1 + d), (-d, -d), **kwargs)

kwargs.update(transform=ax2.transAxes)
ax2.plot((-d, +d), (1 + d, 1 + d), **kwargs)
ax2.plot((1 - d, 1 + d), (1 + d, 1 + d), **kwargs)
ax2.set_yticks([])

plt.show()

And the output gives:


text:
Q: Clarification of "distinct" for Combinatorics and counting This may be a trivial question but I am quite stuck on interpreting combinatorics vs permutation in some cases. For example, suppose the following question:
"Seven different gifts are to be distributed among 10 children. How many distinct results are possible if no child is to receive more than one gift?"
For this one, I interpreted it as being a combinatorics question here as I had thought that order does not matter here, so in that case, we have 7 spots and it does not matter in what type of arrangement we put them in, as long as child 1 receives the gift 1-10, then that would be it. I know that generally we use combinatorics when we don't want to double count but I am not sure why the answer had that it is $10*9*8*7*6*5*4$.

A: The key difference is that the gifts are different, so it matters who gets what gift and not just who gets gifts.
Consider this similar, simplified case. Say we have 7 identical gifts and 7 girls and each girl gets one. Clearly there's only one way to do this.
However, what if instead we have 7 different gifts, like we do in this problem? Then it's not just a question of who gets gifts (indeed, every girl in this situation gets exactly one gift), but who gets what gift -- who gets the lego set, who gets the video games, etc.

A: There are two fundamental questions you should always ask yourself in solving a problem where multiple choices have to be made from a set.  In this case there are $10$ children and you are choosing $7$ of them to receive gift 1, gift 2 and so on, and you must ask:

*

*can the same child be chosen more than once?

*does the order of choosing the children matter?

For this question:

*

*can the same child be chosen more than once? - NO, because it is stated that "no child is to receive more than one gift" - a child can be chosen once, or not at all, but not more than once;

*does the order of choosing the children matter? - YES, because the gifts are all different.  So choosing Anna to get gift 1 and Billy to get gift 2 is clearly a different outcome from choosing Billy first to get gift 1 and then Anna to get gift 2.

The case where repetition is not possible and order matters is called a permutation.  So you want the number of permutations of $7$ children from $10$, which is
$$P(10,7)={}^{10}P_7=10\times9\times8\times7\times6\times5\times4\ .$$

A: If we think about it in a "combinational" way, we will have it like this:
7! * (10C7)
7! Is the gifts distributed.
And 10C7 is the group of 7 kids from those 10.
And 7! * (10C7)= 7! * [10!/(7! * 3!)]= 10!/3!= 10 * 9 * 8 * 7 * 6 * 5 * 4. The result you had.


text:
Q: Parse PFUser Subclass Sign Up using Swift Best Practice I have just downloaded and experimented with Parse.
Everything works as expected, but I have a question regarding a good subclassing design.
The standard PFUser has THREE fields by default.

*

*username

*emailAddress

*password

I would like to add a few more "column" to the User table. Those are:

*

*firstName

*lastName

*phone (Optional)

*profilePicture

Below is my subclass design, but I am not sure if this is the way one might want to subclass their PFUser.
import UIKit

class GPUser: PFUser, PFSubclassing {
    var firstName: String? {
        didSet {
            self["firstName"] = firstName;
        }
    }
    var lastName: String? {
        didSet {
            self["lastName"] = lastName;
        }
    }
    var phone: String? {
        didSet {
            self["phone"] = phone;
        }
    }
    var profilePicture: PFFile? {
        didSet {
            self["profilePicture"] = profilePicture;
        }
    }
}

Questions:

*

*I am wondering what is the best approach to subclass a PFUser (in order to add columns to it) and of course the best design possible. Do you have any design in mind?

*should we override the init method and instantiate all of the variables (firstName, lastName, phone, etc) so that the optional fields column get created on signUp?

*Should I get rid of those didSets blocks? If yes, could you suggest on a better design?

A: In my opinion, the easiest way to achieve what you want is to use stored @NSManaged properties:
class GPUser: PFUser, PFSubclassing {
    @NSManaged var firstName: String
    @NSManaged var lastName: String
    @NSManaged var phone: String
    @NSManaged var profilePicture: PFFile

    class func parseClassName() -> String! {
        return "YourParseClassName"
    }
}

Don't forget to register for your custom PFUser class in the AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    GPUser.registerSubclass()
}

A: What about writing an extension?
Something like:
extension PFUser {

    var picture:PFFile? {
        get {
            return self["picture"] as? PFFile
        }
        set {
            self["picture"] = newValue
        }
    }

    var name:String?{
        get {
            return self["name"] as? String
        }
        set {
            self["name"] = newValue
        }
    }

    var score:Int? {
        return self["score"] as? Int
    }
}


text:
Q: How to save a viewer specific option A minimal example of my problem would be

*

*default background colour is white

*a custom sidebar widget offers to switch background colour to green

*when switched to green, background shall stay green while exploring the blog

Is there a standard interface in Wordpress for saving a global PHP variable $bgcolor to the viewer and read it from him anytime he browses to another blog page.
(I'd like to avoid setting a cookie "by hand")

A:
Is there a standard interface in Wordpress for saving a global PHP
  variable $bgcolor to the user and read it from him anytime he browses
  to another blog page.

There is nothing that will automagically do it for you but it sounds like you just need to save a little bit of user meta, and of course retrieve it.
Since you asked about saving the variable, I am going to assume that the custom sidebar widget that switches the background color already works. Just add code, based on the two Codex entries above, that checks the user meta and saves changes.
If you post your code, I may be able to give a more elaborate answer.
If you are talking about generic visitors, and not WordPress users, setting a cookie is your best choice. There are no built in generic "cookie setter" functions that I am aware of. WordPress itself uses PHP's setcookie in a fair few places, for example in wp_set_auth_cookie, and I don't know why that function would need a "helper". It is fairly straighforward.