text:
Q: YouTube embed that scales up when played - how did Google do this? See this Google support page for reference. They have an embedded YouTube video that is responsive and when you click it it expands to a comfortable viewing size (704x396?). But in its default state it is nice and compact (400x230px), not hogging real estate for viewers who are focused on the text content. In its expanded state there is an X button to exit the expanded state and pause the video.
This is an awesome way to present embedded video content for obvious reasons, but no such configuration options are offered by YouTube when you generate an embed link. This is something unique to Google's support pages. I want to do the same for a page I have with an embedded video, but I don't really understand which div(s) are responsible for this or how they're doing it.
The relevant HTML is somewhere in here:

<video class="video-stream html5-main-video" style="width: 400px; height: 230px; left: 0px; top: -230px; transform: none;"></video>

<svg width="60" height="60"><g><circle class="countdowntimer-background-circle" cx="30" cy="30" r="15"></circle><path class="countdowntimer-diminishing-pieslice" d="M30,30 z"></path><circle class="countdowntimer-middle-dot" cx="30" cy="30" r="4"></circle></g></svg>

<canvas width="60" height="60" class="html5-video-loader html5-center-overlay ytp-scalable-icon-grow" style="display: none; transform: scale(0.5);" aria-hidden="true"></canvas>

<svg><path fill-rule="evenodd" clip-rule="evenodd" fill="#1F1F1F" class="ytp-large-play-button-svg" d="M84.15,26.4v6.35c0,2.833-0.15,5.967-0.45,9.4c-0.133,1.7-0.267,3.117-0.4,4.25l-0.15,0.95c-0.167,0.767-0.367,1.517-0.6,2.25c-0.667,2.367-1.533,4.083-2.6,5.15c-1.367,1.4-2.967,2.383-4.8,2.95c-0.633,0.2-1.316,0.333-2.05,0.4c-0.767,0.1-1.3,0.167-1.6,0.2c-4.9,0.367-11.283,0.617-19.15,0.75c-2.434,0.034-4.883,0.067-7.35,0.1h-2.95C38.417,59.117,34.5,59.067,30.3,59c-8.433-0.167-14.05-0.383-16.85-0.65c-0.067-0.033-0.667-0.117-1.8-0.25c-0.9-0.133-1.683-0.283-2.35-0.45c-2.066-0.533-3.783-1.5-5.15-2.9c-1.033-1.067-1.9-2.783-2.6-5.15C1.317,48.867,1.133,48.117,1,47.35L0.8,46.4c-0.133-1.133-0.267-2.55-0.4-4.25C0.133,38.717,0,35.583,0,32.75V26.4c0-2.833,0.133-5.95,0.4-9.35l0.4-4.25c0.167-0.966,0.417-2.05,0.75-3.25c0.7-2.333,1.567-4.033,2.6-5.1c1.367-1.434,2.967-2.434,4.8-3c0.633-0.167,1.333-0.3,2.1-0.4c0.4-0.066,0.917-0.133,1.55-0.2c4.9-0.333,11.283-0.567,19.15-0.7C35.65,0.05,39.083,0,42.05,0L45,0.05c2.467,0,4.933,0.034,7.4,0.1c7.833,0.133,14.2,0.367,19.1,0.7c0.3,0.033,0.833,0.1,1.6,0.2c0.733,0.1,1.417,0.233,2.05,0.4c1.833,0.566,3.434,1.566,4.8,3c1.066,1.066,1.933,2.767,2.6,5.1c0.367,1.2,0.617,2.284,0.75,3.25l0.4,4.25C84,20.45,84.15,23.567,84.15,26.4z M33.3,41.4L56,29.6L33.3,17.75V41.4z"></path><polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon></svg>

The CSS and javascript I'm not sure about.

A: None of the HTML you posted really does what you think. YouTube's HTML that is inside the embedded iframe is designed to proportionally fit inside the iframe node.
To answer your question though, they simply just use JavaScript to change embedded iframe's height and width. Inside the reference link you posted, inspect the youtube player, and find the iframe node, and watch the inline styling as you play/close the youtube player.


text:
Q: c++ deleting object do not free memory I have following code which I created to check how memory can allocate and free using using qt and c++
Platform:  Linux, Ubunut 16.04
testmemeory.h
#include <QObject>

class testMemeory : public QObject
{
    Q_OBJECT
public:
    explicit testMemeory(QObject *parent = nullptr);
    void freeMEm();
    char* str;

};

testmemeory.cpp
testMemeory::testMemeory(QObject *parent) : QObject(parent)
{
        str = new char [30000];
}

void testMemeory::freeMEm(){
    delete [] str;
}

This is the array I used to store the object.
std::vector<testMemeory*> testList;

And I am allocating the memory using
void MainWindow::allocateMemory()
{
    for(int i=0;i<50000;i++){
        testMemeory *t = new testMemeory();
        testList.push_back(t);
    }

    qDebug()<<"Memory allocated..";
}

And releasing memory using
void MainWindow::relaseMemory()
{
    for(int i=0;i<testList.size();i++)
        testList.at(i)->freeMEm();

    qDeleteAll(testList);
    testList.clear();

    qDebug()<<"Memory freed..";

}

When I excute allocate memory the RAM used for the application increased from 150MB to about 350MB where as if call relaseMemory() function the RAM is still 350 MB and it not reducing to 150 MB
What could be the reason.

A: Typically, when an application needs memory, it requests it from an in-process memory arena and, if there's not enough, the arena will get more from the host environment. Then it's handed out from the arena as needed by individual allocations.
When the application is finished with a bit of memory, it hands it back to the arena for later allocations. It typically doesn't get handed back from the arena to the host.
So, if you're measuring how much memory is allocated to the application from the point of view of the host, it will tend to go up but not down, at least until the application exits, at which point all process memory will be given back.
In other words, something like this:
+-------------+               +-------+
|             | <- allocate - |       |             +------+
| application |               | arena | <- obtain - | host |
|             | --- free ---> |       |             +------+
+-------------+               +-------+                 ^
\_____________________________________/                 |
                   |                                    |
                   +------ all handed back on exit -----+

redpajama_set_name: RedPajamaStackExchange


text:
Q: commit to single table and roll back to others I have to create records in multiple tables one after another serially and if there is some exception in data I need to log it into some exception table.
The problem is in case of exception (which is a data related issue, nothing to do with DB) I need to rollback all the Inserts but the entry into the exception table shouldn't be rolled back.
What should I do as as per my understanding a COMMIT statement will commit all the Inserts along with the exception table Insert?

A: You may use an AUTONOMOUS routine for logging.
Check the CREATE PROCEDURE statement description.

AUTONOMOUS
  Indicates the procedure should execute in its own autonomous transaction scope.


text:
Q: If I am a leader of a squad in Star Wars Commander and I leave the squad what happens? Who becomes the leader if I leave?
I don't want to play this game any more but I don't want to leave my squad leaderless.

A: According to a recent thread on swcommander.com, you can't choose your successor. One will be assigned the role automatically:

The squad member with the most medals inherits the leader role. I just did this last week and I had customer support confirm that's how it works before doing it

A: Actually I accidentally left the squad I started with my son this week (2/9/2015). I was in first place with medals, he was in third. When I left, he was automatically the new leader. When I rejoined, I went back to the top in medals, and he's in third,but is still the leader. I think it sets the new leader based on the order you joined.


text:
Q: SQL Server Understanding transaction log space used I am an Novice SQL server user and by boss has asked me to record transaction log growth.I am testing transaction log behavior on a dummy database for my production server and do not understand certain things.
The production server will have only bulk inserts on the database(around 250 - 400 bulk inserts a day). The methods tested are

*

*Separate bulk inserts for each file.Begin /Commit/Rollback transaction for each files.

*All the files under a single bulk insert.Single Begin /Commit/Rollback transaction for all files.(What i don't want to do but my boss wants it done this way :D)

The database is in bulk log mode as all the inserts are in bulk.
The log file was initially set to 3 GB and in the first scenario the log file size remained the same only the Log space used increased.
DBCC SQLPERF(Logspace)
While in the second case when the bulk insert was performed the log file size increase to a whooping 27 GB but the space used remained minimal 0.5%.
I am not understanding the sudden increase in the log size while the space used is still minimal.
Does Begin /Commit/Rollback transaction have any effect on transaction logs?
Data is being inserted only once in the day, So is keeping a production database in simple recovery mode really stupid?

A:
Does Begin /Commit/Rollback transaction have any effect on transaction logs?

All log data since the oldest active transaction must be kept active. Now why is only 0,5% of that space in the log used? SQL Server reserves log space for active transactions to support rollback operations. A rollback uses log space. SQL Server is conservative when it reserves space. The 27GB are probably its estimate for how much log is needed in the worst case to rollback all the bulk inserts you made.
You are probably getting minimally logged bulk inserts here. These cause minimal log writes. But the surprise comes later when you back up the log: All bulk-changed pages are copied into the backup so that the log will actually be able to roll-forward the writes you made.
Can you use the simple logging model? That might make these concerns go away. The simple log model does not cause data safety issues by itself. It just means that you can no longer do log backups (which might imply a higher risk for data not backed up yet in case the server explodes).
Whether you should use a single transactions or multiple smaller ones depends on:

*

*Do you need the atomicity guarantee? Note, that a rollback of huge bulk inserts might be extremely slow. I have never tested that. Be sure to test it.

*Test, which variant is faster. There are reasons for both to be possibly faster. Try it.


text:
Q: how do you build nested defaultdicts in Python with objects of a different type I'm trying to rewrite the following code
dct = {}
x = 'x'
y = 'y'
z = 'z'
if x not in dct:
    dct[x] = defaultdict(dict)
if y not in dct[x]:
    dct[x][y] = defaultdict(dict)
if z not in dct[x][y]:
    dct[x][y][z] = defaultdict(list)
dct[x][y][z]['b'].append(defaultdict(int))
dct[x][y][z]['b'][0]['g']+=1

Without the following lines:
if x not in dct:
    dct[x] = defaultdict(dict)
if y not in dct[x]:
    dct[x][y] = defaultdict(dict)
if z not in dct[x][y]:
    dct[x][y][z] = defaultdict(list)
dct[x][y][z]['b'].append(defaultdict(int))

Ideally I would like to have syntax such as
dct = 'state what it is'
dct[x][y][z]['b'][0]['g']+=1

A: I wrote a customised implementation of defaultdict which can do this to an arbitrary depth, unlike the fixed depth from previous answers.
class DefaultDict(dict):
    def __missing__(self, name):
        rval=type(self)()
        self.__setitem__(name, rval)
        return rval

Here's some example usage:
>>> dct=DefaultDict()
>>> dct[0][1]['bees'][('any','hashable','object')]=2
>>> dct[0][1]['bees'][('any','hashable','object')]
2
>>> 0 in dct
True
>>> 1 in dct
False
>>> dct
{0: {1: {'bees': {('any', 'hashable', 'object'): 2}}}}

A: Use lambdas.
from collections import defaultdict as dd

dct = dd(lambda: dd(lambda: dd(int)))

dct["foo"][1][("a", 7)] += 1


text:
Q: How do I achieve a performant object isolation solution in concurrent transactions I'm creating this method issueTransfer to achieve a transfer from one account to another.
My solution is:
public void issueTransfer(final int amount, final Account src,
        final Account dst) {
    /*
     * TODO implement issueTransfer using object-based isolation instead of
     * global isolation, based on the reference code provided in
     * BankTransactionsUsingGlobalIsolation. Keep in mind that isolation
     * must be applied to both src and dst.
     */

    isolated(src, dst, () -> {
        if (src.withdraw(amount)) {
            dst.deposit(amount);
        }
    });
}

The solution for global isolation is:
public void issueTransfer(final int amount, final Account src,
        final Account dst) {
    isolated(() -> {
        src.performTransfer(amount, dst);
    });
}

The global and object isolated methods applied are defined like this:
public static void isolated(Runnable runnable) {
    isolatedManager.acquireAllLocks();

    try {
        runnable.run();
    } finally {
        isolatedManager.releaseAllLocks();
    }
}

public static void isolated(Object obj1, Object obj2, Runnable runnable) {
    Object[] objArr = new Object[]{obj1, obj2};
    isolatedManager.acquireLocksFor(objArr);

    try {
        runnable.run();
    } finally {
        isolatedManager.releaseLocksFor(objArr);
    }
}

Helper methods (acquire and release) are:
public void acquireAllLocks() {
    for(int i = 0; i < this.locks.length; ++i) {
        this.locks[i].lock();
    }
}

public void releaseAllLocks() {
    for(int i = this.locks.length - 1; i >= 0; --i) {
        this.locks[i].unlock();
    }
}

public void acquireLocksFor(Object[] objects) {
    TreeSet<Object> sorted = this.createSortedObjects(objects);
    Iterator var3 = sorted.iterator();

    while(var3.hasNext()) {
        Object obj = var3.next();
        int lockIndex = this.lockIndexFor(obj);
        this.locks[lockIndex].lock();
    }
}

public void releaseLocksFor(Object[] objects) {
    TreeSet<Object> sorted = this.createSortedObjects(objects);
    Iterator var3 = sorted.iterator();

    while(var3.hasNext()) {
        Object obj = var3.next();
        int lockIndex = this.lockIndexFor(obj);
        this.locks[lockIndex].unlock();
    }
}

private int lockIndexFor(Object obj) {
    return Math.abs(obj.hashCode()) % 64;
}

private TreeSet<Object> createSortedObjects(Object[] objects) {
    TreeSet<Object> sorted = new TreeSet(new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            return IsolatedManager.this.lockIndexFor(o1) - IsolatedManager.this.lockIndexFor(o2);
        }
    });
    Object[] var3 = objects;
    int var4 = objects.length;

    for(int var5 = 0; var5 < var4; ++var5) {
        Object obj = var3[var5];
        sorted.add(obj);
    }

    return sorted;
}

As you can see, I'm supposedly applying the 2nd method (object isolation) as required by the documentation.
The test is passing without problems:
public void testObjectIsolation() {
    testDriver(new BankTransactionsUsingGlobalIsolation());
    final long globalTime = testDriver(
            new BankTransactionsUsingGlobalIsolation());

    testDriver(new BankTransactionsUsingObjectIsolation());
    final long objectTime = testDriver(
            new BankTransactionsUsingObjectIsolation());
    final double improvement = (double)globalTime / (double)objectTime;

    final int ncores = getNCores();
    final double expected = (double)ncores * 0.75;
    final String msg = String.format("Expected an improvement of at " +
            "least %fx with object-based isolation, but saw %fx", expected,
            improvement);
    assertTrue(msg, improvement >= expected);
}

However the platform used for evaluation says I'm not passing the test either with 2 or 4 cores. Depending on when I do it, sometimes I pass 1 of the tests (I assume, the 2 cores test.
As you can see from the test that I pass, my object isolation solution is faster (in a 1:0.75 ratio per core) than my global isolation. Is it a platform failure or can my code be improved? I've tried using lock, unlock, and trylock, but my solution seems to work faster but not enough yet.

A: You could  try this approach by Brian Goetz and Tim Pierels from the book, "Java Concurrency in Practice"
http://jcip.net/listings/InduceLockOrder.java

A: You can use Taooka distributed lock manager with some SQL-database to write code like this:
if taooka.Lock(srcUser.ID, time.Minute) {

    if srcUser.Balance < transferSum {
        taooka.Unlock(srcUser.ID)
        return "Not enough money"
    }

    if taooka.Lock(dstUser.ID, time.Minute) {

        srcSQLServer = GetSQLServerFor(srcUser)
        dstSQLServer = GetSQLServerFor(dstUser)

        transferID = journalSQLServer.do("INSERT INTO money_transfer SET start_time=NOW()")

        srcSQLServer.do("INSERT INTO money_log SET transfer_id=", transferID, ", user_id=", srcUser.ID, ", sum=", -transferSum)
        dstSQLServer.do("INSERT INTO money_log SET transfer_id=", transferID, ", user_id=", dstUser.ID, ", sum=", transferSum)

        journalSQLServer.do("DELETE FROM money_transfer WHERE id=", transferID)

        taooka.Unlock(dstUser.ID)
        taooka.Unlock(srcUser.ID)

        return "Ok"
    }

    taooka.Unlock(srcUser.ID)
    return "wait please..."

}
else {
    return "wait please..."
}

and run in background this code:
for {
    partialTransferID = journalSQLServer.do("SELECT id FROM money_transfer WHERE start_time < DATE_SUB(NOW(), INTERVAL 1 MINUTE) LIMIT 1")

    if partialTransferID > 0 {
        foreach sql in SQLServers {
            sql.do("DELETE FROM money_log WHERE transfer_id=", partialTransferID)
        }
        journalSQLServer.do("DELETE FROM money_transfer WHERE id=", partialTransferID)
        continue
    }

    Sleep(time.Second)
}

But unfortunately Taooka still hasn`t Java bindings.


text:
Q: Adding characters to $config[permitted_uri_chars] I think I need to add several characters to the $config[permitted_uri_chars] but I don't know which one is causing the issue and how to place the character. This is what I get when I access the page:
An Error Was Encountered

The URI you submitted has disallowed characters.

This is the address:
http://localhost/ci_bootstrap/index.php/home/edit_user/1'%7D

And this is my $config:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

Can you help a noob? Thank you.

A: You did not allow ' in $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
So you have to include it:
$config['permitted_uri_chars'] = "a-z 0-9~%.:_'\-";


text:
Q: How to achieve the below sequence? How to achieve result sequence with the given 2 sequences ?
val seq1 = Seq("A","B","C")
val seq2 = Seq(1,2,3)

val Result = Seq("A1","A2","A3","B1", "B2", "B3", "C1", "C2", "C3")

A: You can just use for comprehensions to find all combinations and concat the result into string:
val seq1 = Seq("A", "B", "C")
val seq2 = Seq(1, 2, 3)

val Result = for {
  s1 <- seq1
  s2 <- seq2
} yield s1 + s2


text:
Q: Why cant I copy a string from a file and register it to an object? I have to make a program to create a credit card and save values in a csv file. I also need to retrieve the data saved in order to use them in further program usage so I need to copy values like customerID, pin, amount of money from a cvs file. The values get copied as strings and I am using Integer.parseInt to convert them but it's giving me NULLPointerException
import java.io.*;
import java.lang.Math;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CreditCard {
    private static final double FEERATE = 0.03;
    private int Overdraft=500;
    private int initialValue;
    private int customerID;
    private int pin;

    public CreditCard(final int customerID,int initialValue) {
        this.customerID = customerID;
        this.initialValue = initialValue;
        this.pin = (int)(Math.random() * (99999 - 100)+100);
    }

    public int getCustomerID() {
        return this.customerID;
    }

    public int getInitialValue() {
        return this.initialValue;
    }

    public int getPin() {
        return this.pin;
    }

    public int getOverdraft() {
        return this.Overdraft;
    }

    public void debitAmount(int amount) {
        if(amount > getInitialValue()) {
            this.initialValue = 0;
            amount = getInitialValue() - amount;
            this.Overdraft = getOverdraft() - amount;
        }
        else {
            this.initialValue = this.initialValue - amount;
        }
    }

    public String showData() {
        return "Your PIN: "+getPin()+
                " Your amount: "+getInitialValue();
    }
}

public static CreditCard[] createArrayFromFile(CreditCard[] creditCard) throws IOException {
        String fileName="file.txt";
        File file=new File(fileName);

        BufferedReader csvReader = new BufferedReader(new FileReader(fileName));
        String row;
        int i=0;
        while ((row = csvReader.readLine()) != null) {
            String[] data = row.split(",");
            creditCard[i].customerID = Integer.parseInt(data[0]);
            creditCard[i].initialValue = Integer.parseInt(data[1]);
            creditCard[i].pin = Integer.parseInt(data[2]);
            i++;
        }
        csvReader.close();

        return creditCard;
    }

    public static void main(String[] args) throws IOException {
        CreditCard[] creditCard = new CreditCard[50];
        createArrayFromFile(creditCard);
    }
}

A: Inside your parsing logic be sure to check that you are getting the correct data format. Never assume the data you parse will be correct. Protect your program from invalid input. Be sure to parse the input before creating your object to ensure you only create an object when parsing valid data.
while ((row = csvReader.readLine()) != null) {
    String[] data = row.split(",");
    if(data.length == 3)
    {
       try
       {
          int customerID = Integer.parseInt(data[0]);
          int initialValue = Integer.parseInt(data[1]);
          int pin = Integer.parseInt(data[2]); //<-- create setter for pin
          creditCard[i] = new CreditCard(customerID, initialValue);
          i++;
       }
       catch (Exception e)
       {
          System.out.println("Something went wrong parsing " + row);
       }
    }
    else
        System.out.println("Size of split array returned invalid size of " + data.length);
}

Also be sure to add a setter for pin, otherwise you'll only be able to save the object to the file but when it comes time to retrieve the information from the file the pin will be reset by the constructor. Customers will be unable to get their money :(

A: What you have to do is to initialize your object so that will not store your values to null. Change your code in while loop to this:
String[] data = row.split(",");
creditCard[i] = new CreditCard(Integer.parseInt(data[0]), Integer.parseInt(data[1]));

// creditCard[i].customerID = Integer.parseInt(data[0]);
// creditCard[i].initialValue = Integer.parseInt(data[1]);
creditCard[i].pin = Integer.parseInt(data[2]);
System.out.println(creditCard[i].customerID + " " + creditCard[i].initialValue + " " + creditCard[i].pin);
i++;


text:
Q: Calculate the time difference if values are not equal I am able to calculate the difference (in hours) using:
pdf["hours_used"] = (
    pdf["_source_eventTime_right"] - pdf["_source_eventTime_left"]
).astype("timedelta64[h]")

This is working as expected. But I want to return NULL for the rows where left and right times are exactly the same. How do I add "if" clause in the hours calculation?

A: As suggested in the comment, np.where worked as expected...
pdf["hours_used"] = np.where(
    (pdf["_source_eventTime_right"] - pdf["_source_eventTime_left"])
    .astype("int")
    .gt(0),
    (pdf["_source_eventTime_right"] - pdf["_source_eventTime_left"]).astype(
        "timedelta64[h]"
    ),
    np.nan,
)


text:
Q: ObjectMapper cannot properly deserialize json received as AMQP message body I created converter for deserializing messages to some custom message type.
This is the message I send in queue:
{
  "id":"851e04e5-356f-49a6-b6e2-93102dc7a642",
  "exportStatus": "EXPORTED"
}
This is the code of converter
public class MergePatchAMQPMessageConverter implements MessageConverter {

    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        throw new UnsupportedOperationException();
    }

    @Override
    public UpdateConfigurationCommand fromMessage(Message message) throws MessageConversionException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(message.getBody());
        } catch (IOException e) {
            // TODO
        }

        JsonNode id = jsonNode.get("id");
        if (id == null) {
            throw new IllegalStateException();
        }

        JsonMergePatch patch = null;
        try (JsonReader reader = Json.createReader(new ByteArrayInputStream(message.getBody()))) {
            patch = Json.createMergePatch(reader.readValue());
        } catch (Exception e) {
            throw new MessageConversionException(e.getMessage(), e);
        }

        return new UpdateConfigurationCommand(UUID.fromString(id.asText()), patch);
    }
}

When converter receives this message in message body ObjectMapper cannot deserialize it. The size of result JsonNode is 0. When I feet this message to ObjectMapper as regular String value it works properly.
What can be a reason?


text:
Q: TypeError TypeError: 'dict' object is not callable , post request I am trying to call my own Post API from python function ,  there is no issue in api side , it's working fine , but when i am trying to call POST API from Python function
below is my code
@app.route('/dhiru_post', methods=['GET'])
def dhiru_post():
    url = "https://www.mydomainamehere.com/api_new/"

    payload = {"number": 12524,
               "api_type": "news_listing",
               "slug": "life-mantra",
               "start": 0,
               "end": 10}
    response_decoded_json = requests.post(url, data=payload)
    response_json = response_decoded_json.json()
    return response_json

Note: https://www.mydomainamehere.com/api_new/ this is not the exact
  url, please ignore .

Error :
open this url :
https://dhiru-ai-quantomsoftech.herokuapp.com/webhook_dhiru
TypeError
TypeError: 'dict' object is not callable

Traceback (most recent call last)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/app/.heroku/python/lib/python3.6/site-packages/werkzeug/wrappers/base_response.py", line 269, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/app/.heroku/python/lib/python3.6/site-packages/werkzeug/test.py", line 1119, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

A: You can modify your handler as follow:
from flask import jsonify

@app.route('/dhiru_post', methods=['GET'])
def dhiru_post():
    url = "https://www.mydomainamehere.com/api_new/"
    payload = {
        "number": 12524,
        "api_type": "news_listing",
        "slug": "life-mantra",
        "start": 0,
        "end": 10
    }
    response = requests.post(url, data=payload)
    return jsonify(response.json())

So basically you need to return a response instead of a dict, jsonify will do that for you: set the correct content-type and convert the response.json() dict to string and use that as content.


text:
Q: Argument pass through php into bash file not working In my script I pass two argument into Bash file through PHP file.
PHP File:
$number_server = 7;
$server_name = "dbfs";
exec("/bin/bash drun.sh $number_server $server_name",$db_uptime);
foreach($db_uptime as $dbm_load){
echo $dbm_load."<br />";
 }

Bash File:
#!/bin/sh
for i in seq $1; do ssh $2$i 'uptime;free -m;mpstat;cat /tmp/db2.info'; done &
pid=$!
sleep 2
kill -9 $pid

According to this it will show 7 records,but actually it shows only one record.Means FOR loop in Bash script runs only one time and second argument pass into bash is not working.

A: You BASH script seems to be wrong. Replace that with:
#!/bin/bash

for ((i=0; i<$1; i++)); do
    ssh "$2$i" 'uptime;free -m;mpstat;cat /tmp/db2.info'
done &
pid=$!
sleep 2
kill -9 $pid


text:
Q: javascript selectiong checkboxes to order options dynamically I want to  implement a form that has checkboxes to select options and comboboxes to order the selections. I have done this,http://jsbin.com/AmeWahI/1/
It works until I click the third checkbox. So, what i want is to when I click a checkbox, I want to order this selection among the current selected ones . For example, if I click all checkboxes, all the comboboxes should display 1,2,3 for ordering.
if I click first and third checkboxes, both comboboxes should display 1 and 2 since only two elements are clicked.

A: I modified, see here
http://jsbin.com/AmeWahI/8/
You need to replace your second for loop with this
for (var n=0; n<3; n++) {
      var select = document.getElementById("slct"+n);
            var length = select.options.length;
            select.remove(0);
            for (var m = 0; m < length; m++) {
                select.options[m] = null;
            }
      }

A: You can get the number of check boxes checked inside the form and based on that you can set the value of select options..
say if i have checked two check boxes 1 and 3..my order of learning is two and you can set the value of select box option to two..

A: well, when ever any checkbox is checked or unchecked find all the checked checkbox count, clear all the dropdowns item list and add item to the dropdown from 1 to total checked checkbox count only if respective check box is checked.
hope this will help you...

A: Try this,
function enableDisable(bEnable, checkboxID) {

            var id = checkboxID.replace("checkbox", "");
            var checkedItems = new Array();
            var inputElems = document.getElementsByTagName("input");
            count = 0;
            for (var i = 0; i < inputElems.length; i++) {
                if (inputElems[i].type === "checkbox" && inputElems[i].checked === true) {
                    count++;
                    checkedItems.push(inputElems[i].id);
                }

            }

            for (var k = 0; k < checkedItems.length; k++) {

                var idk = checkedItems[k].replace("checkbox", "");
                var select = document.getElementById("slct" + idk);
                var length = select.options.length;

                for (i = 0; i < length; i++) {
                    select.options[i] = null;
                }
            }

            for (var j = 0; j < checkedItems.length; j++) {

                for (var k = 0; k < checkedItems.length; k++) {
                    var id = checkedItems[j].replace("checkbox", "");
                    var combo = document.getElementById("slct" + id);
                    var option = document.createElement("option");
                    combo.remove(0);
                    option.text = "" + (k + 1);
                    option.value = "" + (k + 1);

                    try {
                        combo.add(option, null); //Standard
                    } catch (error) {
                        combo.add(option); // IE only
                    }
                }
            }
        }

let me know if any concern


text:
Q: Type error: Error parsing XML: junk after document element about_window.xml? This is my code. All I did is that I changed the texts in the about window in all layouts file and I find this error in the xml file.

Multiple annotations found at this line:

*

*error: Error parsing XML: junk after document element

*The markup in the document following the root element must be well-

also in the src files the error is "R cannot be resolved to a variable". This is my the XML code:
version="1.0" encoding="utf-8"?>
<ScrollView android:orientation="vertical"
android:scrollbars="none"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
 xmlns:android="http://schemas.android.com/apk/res/android"/>
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
          android:xmlns:android="http://schemas.android.com/apk/res/android"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6.0dip"
        android:layout_marginTop="6.0dip"
        android:text="xxxxxx"
        android:textColor="#ffffffff"
        android:textSize="14.0dip"
        android:textStyle="bold" />

    <TextView android:textSize="14.0dip" android:textStyle="bold" android:textColor="#ffffffff" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="6.0dip" android:layout_marginTop="10.0dip" android:text="@string/app_version_name" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6.0dip"
        android:text="xxxxx"
        android:textColor="#ffffffff"
        android:textSize="14.0dip"
        android:textStyle="bold" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6.0dip"
        android:layout_marginTop="10.0dip"
        android:text="xxxxxxx"
        android:textColor="#ffffffff"
        android:textSize="14.0dip" />

    <TextView
        android:id="@id/dev_email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6.0dip"
        android:layout_marginTop="20.0dip"
        android:gravity="center_horizontal"
        android:text="youss.boss1dev@gmail.com"
        android:textColor="#2704fc"
        android:textSize="14.0dip"
        android:textStyle="bold" />

    <LinearLayout android:gravity="center" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10.0dip"
                      android:xmlns:android="http://schemas.android.com/apk/res/android"/>

        <Button
            android:id="@id/close_btn"
            android:layout_width="110.0dip"
            android:layout_height="44.0dip"
            android:layout_marginBottom="4.0dip"
            android:layout_marginTop="4.0dip"
            android:text="xxxx" />

    </LinearLayout>
</LinearLayout>
</ScrollView>

A: Your scroll view ends with a /> finishing the object, I think childrem will not have access to the tags android.
All your views are closed by itself (with "/>"). So your document doesnt have a root, only a list.
Also: Childs doesnt needs to declare xmlns again, such the second object:
    android:xmlns:android="http://schemas.android.com/apk/res/android"
That also has a typo with android twice.
Also:
Do any text contains > or < ? It should be added into the strings.xml so those characters can appear

A: You have an error in LinearLayout:
android:xmlns:android="http://schemas.android.com/apk/res/android"
it should be:
xmlns:android="http://schemas.android.com/apk/res/android"
you typed twice android. Instead removing just android remove whole line you don't need it because you already have declaration in ScrollView Actually the problem is ScrollView can contain only one direct child and you have multiple. So you have to put all your xml code below ScrollView in one container either LinearLayout, RelativeLayout etc.

A: This is the perfect Layout.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:scrollbars="none">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:xmlns="http://schemas.android.com/apk/res/android">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6.0dip"
            android:layout_marginTop="6.0dip"
            android:text="xxxxxx"
            android:textColor="#ffffffff"
            android:textSize="14.0dip"
            android:textStyle="bold"/>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6.0dip"
            android:layout_marginTop="10.0dip"
            android:text="app_version_name"
            android:textColor="#ffffffff"
            android:textSize="14.0dip"
            android:textStyle="bold"/>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6.0dip"
            android:text="xxxxx"
            android:textColor="#ffffffff"
            android:textSize="14.0dip"
            android:textStyle="bold"/>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6.0dip"
            android:layout_marginTop="10.0dip"
            android:text="xxxxxxx"
            android:textColor="#ffffffff"
            android:textSize="14.0dip"/>

        <TextView
            android:id="@+id/dev_email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6.0dip"
            android:layout_marginTop="20.0dip"
            android:gravity="center_horizontal"
            android:text="youss.boss1dev@gmail.com"
            android:textColor="#2704fc"
            android:textSize="14.0dip"
            android:textStyle="bold"/>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10.0dip"
            android:gravity="center"
            android:orientation="vertical"
            android:xmlns="http://schemas.android.com/apk/res/android">

            <Button
                android:id="@+id/close_btn"
                android:layout_width="110.0dip"
                android:layout_height="44.0dip"
                android:layout_marginBottom="4.0dip"
                android:layout_marginTop="4.0dip"
                android:text="xxxx"/>

        </LinearLayout>
    </LinearLayout>
</ScrollView>


text:
Q: How to get rid of the date and time that appears before every NSLog statement in the console I use NSLog in my application. And I'd like to get rid of the annoying beginning of each string: "2009-07-01 21:11:06.508 MyApp[1191:207]".
Is there a way to do so? Probably another logging function?
Thanks.

A: This preprocessor macro is easy to implement and you don't have to change any of your current NSLog statements:
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);

It works completely like NSLog without all the extra things before the message.
I original found this on another SO question, but I can't find it now.

A: Read these:

*

*https://github.com/davislg/QuietLog

*https://web.archive.org/web/20140924195139/http://cocoaheads.byu.edu/wiki/different-nslog
It's a Github project called "QuietLog", originally from our CocoaHeads site, that explains how to create a QuietLog function that does what you're describing.  It also shows how to wrap QuietLog into a macro called LocationLog so that it'll print out the file name and line number where you've got the log statement.  I use it in all of my projects, and I don't lose stray "NSLog" statements anymore.

A: I like being able to use objective-C objects for format strings and arguments, so I re-wrote NSLog() and added it to my utilities.

+ (void)myLog:(NSString *)formatString, ...
{
    va_list args;
    va_start(args, formatString);
    NSString* output = [[NSString alloc] initWithFormat:formatString arguments:args];
    fprintf(stderr, "%s\n", [output UTF8String]);
    [output release];
    va_end(args);
}

A: Have you tried CFShow()?

A: You could print to sdterr:
fprintf(stderr, "%s", "Your message");

Edit: Check out this implementation by Karl Kraft


text:
Q: Passing value from activity to view class I have an activity in which there are 3 checkboxes in different views. These checkboxes are to pick up a color.
In the DrawingView class, I have to draw on my canvas with the color that is checked. What I want is to pass an integer value from the activity to the view class and set the color of paint accordingly.  itried using getter and setters, but I get black color. I suppose this is because the color is being set in the constructor itself, and it does not change when I check any box.
Please refer this for updates in the below code
Code:
MainActivity: the color/checkbox is selected here. And the drawing is to be done in the layout of this activity itself.
        carImageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            drawingView=new DrawingView(carImageView.getContext());
            drawingView=new DrawingView(carImageView.getContext(),null);
            drawingView.setColor(color);
            return false;
        }
    });

  scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
          if(b)
          {
              color=1;
              chipsCb.setChecked(false);
              dentsCb.setChecked(false);
          }
      }
  });
    chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                color=2;
                scratchesCb.setChecked(false);
                dentsCb.setChecked(false);
            }
        }
    });
    dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                color=3;
                chipsCb.setChecked(false);
                scratchesCb.setChecked(false);
            }
        }
    });
}

View Class:
   public DrawingView(Context context, @Nullable AttributeSet attrs) {
   super(context, attrs);
    mPaint=new Paint();
    if(color==1)
        mPaint.setColor(Color.RED);
    else if(color==2)
        mPaint.setColor(Color.BLUE);
    else if(color==3)
        mPaint.setColor(Color.GREEN);
    this.context=context;
    mPath=new Path();
    mPaint.setAntiAlias(true);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.MITER);
    mPaint.setStrokeWidth(5f);
}
     public void setColor(int color){
    this.color=color;
}
public int getColor(){
    return this.color;
}

Edit
I don't necessarily want to use the exact same code. All I want is to change paint color when a checkbox is selected to be able to draw on an image view. Any other approach is welcome.

A: In the MainActivity, you are creating a DrawingView that has no relationship to your image view that is displayed. So, when you change the color, you are not changing the color of the displayed image view but of the unconnected DrawingView. The image view never has a new color defined and always defaults to black.
Here is a video of a small working app based upon your most recently supplied code. Maybe all the colors shouldn't change when a new check box is clicked, but you will be able to address that issue separately.
Changes I have made to the Java code are commented as such. Changes were also made to the XML to allow your code to run in my environment, but those changes were not commented.

MainActivity.java (Updated)
public class MainActivity extends AppCompatActivity {
    ImageView caricon;
    int itemSelected = 0;
    private DrawingView carImageView;
    Bitmap bitmap;
    ImageView backarrow;
    TextView nextcheckinAB2;
    Bitmap bmp;
    public static int color;
    CheckBox scratchesCb, chipsCb, dentsCb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        carImageView = (DrawingView) findViewById(R.id.carImageView);
        scratchesCb = (CheckBox) findViewById(R.id.scratchesCheckBox);
        chipsCb = (CheckBox) findViewById(R.id.ChipCheckbx);
        dentsCb = (CheckBox) findViewById(R.id.DentsCheckBox);

        // Change: Make sure to initialize the color
        color = 1;
        carImageView.setColor(color);

        carImageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // drawingView = new DrawingView(carImageView.getContext(),null);
                carImageView.setColor(color);
                return false;
            }
        });

        scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    color = 1;
                    carImageView.clearCanvas();
                    carImageView.setColor(1); //
                    chipsCb.setChecked(false);
                    dentsCb.setChecked(false);
                }
            }
        });
        chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    color = 2;
                    carImageView.setColor(2);
                    scratchesCb.setChecked(false);
                    dentsCb.setChecked(false);

                }
            }
        });
        dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    color = 3;
                    // Change: Do like the other check boxes althogh not really needed.
                    carImageView.setColor(3);
                    chipsCb.setChecked(false);
                    scratchesCb.setChecked(false);

                }
            }
        });
    }
}

DrawingView.java (Updated)
public class DrawingView extends android.support.v7.widget.AppCompatImageView {
    private Path mPath;
    private Paint mPaint;
    private float mX, mY;
    private static final float TOLERANCE = 5;
    int color;
    Context context;

    public DrawingView(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public DrawingView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();

    }

    public void init() {
        mPath = new Path();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.MITER);
        mPaint.setStrokeWidth(5f);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPath(mPath, mPaint);
    }

    public void setColor(int color) {
        if (color == 1) {
            mPaint.setColor(Color.RED);
            this.color = color;
            invalidate();
        } else if (color == 2) {
            mPaint.setColor(Color.BLUE);
            this.color = color;
            invalidate();
        } else if (color == 3) {
            mPaint.setColor(Color.GREEN);
            this.color = color;
            invalidate();
        }

    }

    public int getColor() {
        return this.color;
    }

    private void onStartTouch(float x, float y) {
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }

    private void moveTouch(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOLERANCE || dy >= TOLERANCE) {
            mPath.quadTo(mX, mY, (mX + x) / 2, (mY + y) / 2);
            mX = x;
            mY = y;
        }
    }

    public void clearCanvas() {
        mPath.reset();
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        invalidate();
    }

    private void upTouch() {
        mPath.lineTo(mX, mY);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                onStartTouch(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                moveTouch(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                upTouch();
                invalidate();
                break;
        }

        return true;

    }
}

activity_main.xml (Updated)

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:orientation="horizontal"
        android:weightSum="3">

        <HorizontalScrollView
            android:id="@+id/horizontalSrollView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_weight="1">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"

                        android:orientation="vertical">

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal"
                            android:paddingLeft="15dp"
                            android:paddingRight="15dp"
                            android:paddingTop="5dp"
                            android:weightSum="2">

                            <ImageView
                                android:layout_width="20dp"
                                android:layout_height="20dp"
                                android:layout_marginRight="2dp"
                                android:layout_weight="0.5"
                                android:background="@android:color/holo_red_light" />

                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="2dp"
                                android:layout_weight="1.5"
                                android:text="Scratches"
                                android:textColor="#000" />
                        </LinearLayout>

                        <CheckBox
                            android:id="@+id/scratchesCheckBox"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:checked="true" />
                    </LinearLayout>

                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:orientation="vertical">

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal"
                            android:paddingLeft="15dp"
                            android:paddingRight="15dp"
                            android:paddingTop="5dp"
                            android:weightSum="2">

                            <ImageView
                                android:layout_width="20dp"
                                android:layout_height="20dp"
                                android:layout_marginRight="2dp"
                                android:layout_weight="0.5"
                                android:background="@android:color/holo_blue_light" />

                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="2dp"
                                android:layout_weight="1.5"
                                android:text="Chips"
                                android:textColor="#000" />
                        </LinearLayout>

                        <CheckBox
                            android:id="@+id/ChipCheckbx"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center" />
                    </LinearLayout>

                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:orientation="vertical">

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal"
                            android:paddingLeft="15dp"
                            android:paddingRight="15dp"
                            android:paddingTop="5dp"
                            android:weightSum="2">

                            <ImageView
                                android:layout_width="20dp"
                                android:layout_height="20dp"
                                android:layout_marginRight="2dp"
                                android:layout_weight="0.5"
                                android:background="@android:color/holo_green_light" />

                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginLeft="2dp"
                                android:layout_weight="1.5"
                                android:text="Dings/Dents"
                                android:textColor="#000" />
                        </LinearLayout>

                        <CheckBox
                            android:id="@+id/DentsCheckBox"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center" />
                    </LinearLayout>

                </RelativeLayout>
            </LinearLayout>

        </HorizontalScrollView>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="8.7">

        <[your package name].DrawingView
            android:id="@+id/carImageView"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:src="@mipmap/ic_launcher"
            android:layout_gravity="center_vertical" />
        <!--<ImageView
            android:id="@+id/carImageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"/>-->
    </LinearLayout>

</LinearLayout>

A: you need change function setColor.
1.change mPaint color.
2.add invalidate() for redraw view.
public void setColor(int color){
    this.color=color;
     mPaint.setColor(color);
    invalidate();
}

A: You need to call invalidate() on the View to make it update.
Try this,
final DrawingView drawingView = new DrawingView(carImageView.getContext());

carImageView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        drawingView.setColor(color);
        return false;
    }
});

scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  @Override
  public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
      if(b)
      {
          color = 1;
          drawingView.setColor(color);

          chipsCb.setChecked(false);
          dentsCb.setChecked(false);
      }
  }
});

chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if(b)
        {
            color = 2;
            drawingView.setColor(color);

            scratchesCb.setChecked(false);
            dentsCb.setChecked(false);
        }
    }
});

dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if(b)
        {
            color = 3;
            drawingView.setColor(color);

            chipsCb.setChecked(false);
            scratchesCb.setChecked(false);
        }
    }
});

DrawingView.java
public DrawingView(Context context) {
    super(context);
    this.context = context;
    init();
}

public DrawingView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    this.context=context;
    init();
}

private void init() {
    mPath=new Path();

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.MITER);
    mPaint.setStrokeWidth(5f);
    setColor(color);
}

public void setColor(int color){
    this.color=color;
    if(color==1)
        mPaint.setColor(Color.RED);
    else if(color==2)
        mPaint.setColor(Color.BLUE);
    else if(color==3)
        mPaint.setColor(Color.GREEN);

    // Call invalidate
    invalidate();
}

A: "even if I pass a static value, say 3 in main activity in drawingview.setColor(int) it gives black. This means the setColor function in Drawingview isn't working. "
Does this mean it will call paint.setColor(3) ?
If yes, this will of course turn your color black. Try passing Color.GREEN instead

A: Define static data member in your DrawingView
static int color = 1; //default
Then, from your activity simply call
DrawingView.color = someValue;
Static Keyword before variable color will make sure there is only one variable reference for all objects of your DrawingView class.


text:
Q: What does coming-out mean in this context? In a movie I watched there was a scene where there was a couch delivered to a house. The owner of the house is telling some workers where to place it. She says "We were thinking in here" while pointing to a room which they were entering and after they are inside she points to a wall and says "with the coming-out part along the wall". The couch is basically a corner settee but two-piece not one, with a little table in-between. What is the coming-out part of a couch?

A: It means "the part that comes out". The descriptive clause ("that comes out") has been transformed into an adjective phrase ("coming-out"). Some similar constructions are:

The rubbed-out part said something interesting. (There is a part of the writing that was rubbed out.)
The combed-over part doesn't hide much. (There is a part of their hair that is combed over the top of their head.)
The tidied-up part looks as good as new. (There is a part of the area that has been tidied up.)

Exactly what part of the couch this is must depend on context. It likely means one side of the corner piece—the speaker considers one side (the longer one?) to be the "main" one, and in their mind, the other side "comes out" from there. They want that other side to lie along the wall.
It could equally mean other things for different furniture. A sofa bed has a part that "comes out" in the sense of folding out when needed. I personally might use "comes out" to describe the part of a corner piece that does not follow the wall (it "comes out" towards the middle of the room), but that's clearly not the case here!

A: Thé 'coming out part' would more than likely be the part that unfolds into a bed.


text:
Q: Copy all directories, with additional intermediate directory I have the following resources structure:
resources
    v1
        foo
        bar
    v2
        baz

and I want to copy these resources to another directory, but each version nested into another directory specified by a maven property, say module-1, e.g.
destination
    v1
        module-1
            foo
            bar
    v2
        module-1
            baz

This is so another module can add its own versioned files. In source control the directory structure is module > versions, but the destination requires them to be version > modules.
My current solution is to put the current into another maven property and use that in a normal resource plugin:
<properties>
    <patch>v3</patch>
    <module>module-1</module>
</properties>
<!-- ... further down below in the build-region ... -->
<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-versioned-files</id>
            <phase>process-resources</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>${somedir}/destination/${patch}/${module}</outputDirectory>
                <resources>
                    <resource>
                        <directory>src/main/resources/patches/${patch}</directory>
                        <filtering>false</filtering>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>

but this requires the property to be adjusted for each version, which is cumbersome and error-prone.
I just want the files for all versions to be properly copied.


text:
Q: 'wait $COPROC_PID' doesn't wait The following test script:
#!/bin/bash
f() { :; }

while :; do
    coproc f par1
    wait $COPROC_PID
done

floods the console with:
./debug.sh: line 7: warning: execute_coproc: coproc [8740:COPROC] still exists
./debug.sh: line 7: warning: execute_coproc: coproc [8741:COPROC] still exists

That is, wait doesn't wait for the coprocess to terminate.
Bash version is 4.2.0(5)-release.
This does not happen with 4.1.5(1)-release.
Do you think it is a bug?

A: This isn't a bug. You named your coproc "f" so it would be under $f_PID.


text:
Q: Update data WHERE I have a table called client and I am trying to update the contact number, but for only the id that is typed in. I have a form that creates two textfields for the data to be changed. My problem is im unsure on how i can only update data for only the id that is entered.
Code:
<form method="post" name="update" >
Client ID:

<input type="text" name="clientid">

Contact Number:

<input type="text" name="contactno">

<input type="submit" name="submit" value="Update">

</form>
<?php
if(isset($_POST['submit'])){
$client = $_POST['clientid'];
$contact = $_POST['contactno'];

$result= $pdo->prepare ("UPDATE client SET client_contact_number='$contact' WHERE client_id='$client'");
$result->execute;
}
?>

A: your syntax should be:
mysqli_query($connection, $sql_query)

you're missing the $connection object in your method.
PHP docs: http://php.net/manual/en/mysqli.query.php
*Original version of this question used procedural syntax - hence my answer.


text:
Q: QODBC connecting to Python I am using QODBC Driver to connect to my Quickbooks Data. Until now, I was the QODBC directly in Power BI/Excel and QODBC works perfectly fine there. But today, I tried to connect to QODBC using python and it is giving me the following error

The python code I am using is this
import pyodbc

cn = pyodbc.connect('DSN=QuickBooks Data 64-Bit QRemote;')
cursor = cn.cursor()
cursor.execute("SELECT Top 10 Name FROM Customer")

for row in cursor.fetchall():
    print (row)

cursor.close()

cn.close()

Can anyone see what's the reason for this error?

A: After a lot of googling, I found the answer. I don't know why but the pyodbc.connect statement requires one more parameter i.e. "autocommit=True". So, the updated code now looks like this and it is working perfectly fine.
import pyodbc

# pyodbc.pooling = False
cn = pyodbc.connect('DSN=QuickBooks Data 64-Bit QRemote',autocommit=True)
cursor = cn.cursor()
cursor.execute("SELECT Top 10 Name FROM Customer")

for row in cursor.fetchall():
    print (row)

cursor.close()

cn.close()


text:
Q: _csrf always NULL and isAnonymous() always FALSE (after deployment) I'm having a strange issue (Spring 5.0.8, Spring Boot 2.0.5) with our project. When I run it locally in my Eclipse env it works perfectly. With "it", I mean the expression
<security:authorize access="isAnonymous()">

        <spring:message code="menu.signin" />

</security:authorize>

is evaluated fine, as long the user is not logged in, he/she is Anonymous. This code is in our app for 6 months now and worked perfectly.
As I made a quite a lot of changes to our logging mechanisms and started to switch part of the project to Thymeleaf (everything works fine) I built finally a new WAR with Maven and deployed it to EBS.
Now, it seems that not only
<security:authorize ...>

is not working anymore, the _csrf-Tags, which are evaluated using
<meta th:name="_csrf" th:content="${_csrf.token}" />
<meta th:name="_csrf_header" th:content="${_csrf.headerName}" />

cannot be evaluated (only on the EBS environment - locally everything is fine).
I started to trace the problem in the logs and discovered that the expression above lead to an exception
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'token' cannot be found on null

which might be obivous when _csrf is null.
Question: Has anyone ever had kind of similar problem? I am not expecting an answer to my problem here, but I am wondering why everything might work perfectly on my local setup and not working anymore when published on EBS?
Might there be an issue with my configuration (annotation based) and the variables/beans in Spring cannot be evaluated when published?
As the JSP example from above is not working (and the Thymeleaf code as well), I am expecting this is a Spring backend issue and not a Thymeleaf problem.
Thank you for any suggestions on this.

A: As so often, after posting the question to Stackoverflow I found the reason for the erratic behaviour of the app. I had declared @EnableAutoConfiguration in another @Controller class which might have led to some confusion. After removing the declaration everything works perfect.
Actually I figured out (again) what the reason for the behaviour is. After eliminating the second EnableAutoConfiguration and building a WAR (we still have some JSP inside the app) everything was working fine. I then made some fixes, redeployed the WAR and the problem was the same again.
After finding some indication that the included spring-boot-starter-tomcat might interfere with the deployment, adding
<dependencies>
..
..
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

did the job.


text:
Q: Dynamically generated NSTimers in same UITableview? I'm trying to implement a timer into a new application. One use case that is likely is to have more than one timer running at a time in the same view updating a UILabel or UIButton title text.
Does anyone have experience of doing this? what approach would you suggest.
The difficulty is when the timers fire off the same selector in short succession.
many thanks in advance
Nick

A: In .h file declare object:
NSTimer *myTimer1,myTimer2;

In .m file:
myTimer1 = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextPhoto) userInfo:nil repeats:YES];
myTimer2 = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextPhoto) userInfo:nil repeats:YES];

After the above invalidate the timers like this:
[myTimer1 invalidate];
[myTimer2 invalidate];

Try it like this.

A: If you do create repeating timers dynamically, you can run into problems with timer invalidation. I'd suggest you use performSelector:withObject:afterDelay: or performSelectorOnMainThread:withObject:waitUntilDone: methods instead.


text:
Q: Login and password for multipass instance I am new to ubunto and want to run it in a VM so have installed multipass successfully and have an ubunto VM running in Hyper V. Connecting to the VM I am asked for a login and password is ther a default? or can I set them up from the multipass command line? I can' find any information in the documentation.
I have also tried using shell on a named running instance but connection failed with message "ssh connection failed: 'Failed to resolve hostname primary.mshome.net (No such host is known.)" I then tried creating an instance with just  "multipass shell" command. which created a running primary with same result.
Any suggestions welcome

A: This might be a bit late but you can login to the instance from multipass without being asked for username and password. From there, you can set the password so that you can login using Hyper V.
First find the name of your instance
multipass list

then login to the instance in multipass
multipass shell <instance name>

Next you can set your password for the default ubuntu user
sudo passwd ubuntu

Now when you try to login using hyper v, just use ubuntu as the username and whatever password you set as the password.

A: TLDR
If somehow multipass shell doesn't work, you can connect it via ssh.
ssh ubuntu@vm-ip-address -i /var/snap/multipass/common/data/multipassd/ssh-keys/id_rsa

Multipass instance, by default doesn't have usable password.
$ passwd --status ubuntu
ubuntu L 04/03/2021 0 99999 7 -1

The L means Locked password.
This is on purpose
If you somehow lose access to the vm (e.g messing up with the network configuration, it happens to me :D).
You can login using the default ssh private key. You can find the private key at:
/var/snap/multipass/common/data/multipassd/ssh-keys/id_rsa

If you are installing it via snap.
You can also find it using locate.
$ locate id_rsa | grep multipass

and connect to the vm using ssh:
ssh ubuntu@vm-ip-address -i /var/snap/multipass/common/data/multipassd/ssh-keys/id_rsa

You may want to change the ownership of the ssh key to your user account. Mine currently set to root.

To find the vm ip address, it depends on the backend. Mine is using libvirt.
virsh net-dhcp-leases default

A: For the shell connection problem, I recommend to you check the host.ics file in windows (C:\WINDOWS\System32\drivers\etc\hosts.ics). If you find duplicate entries there, delete the last ones and try connect again. Usually this solve the problem and you see the IP for the instance is showed again using the next command:
multipass list

About the ubuntu password, I think via ssh any password is required but via "direct access" using Hyper-V is requested as you say. Probably not possible login using a password because default ubuntu password is configured as "--disabled".

A: In multipass instance, set a password to ubuntu user.
sudo passwd ubuntu

A: From command line
### to find the instance name
c:\ multipass list
### to change the root password
c:\ multipass shell <instance name> passwd


text:
Q: Code-behind page cannot "see" any items/controls declared in the aspx page Here's a my Default.aspx page (with unnecessary details excised):
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

        <asp:Panel runat="server" ID="pnlLoginIn">

            Username
            <asp:TextBox id="txtUsername" runat="server" />
            <asp:RequiredFieldValidator runat="server" ID="rfvUserName" ErrorMessage="*" ControlToValidate="txtUsername" ValidationGroup="credentials" Display="Dynamic" />

            Password
            <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" />
                <asp:RequiredFieldValidator runat="server" ID="rfvPassword" ErrorMessage="*" ControlToValidate="txtPassword" ValidationGroup="credentials" Display="Dynamic" />

        <asp:Panel ID="pnlInvalidCredentials" runat="server">

            <asp:Literal runat="server" ID="litInvalidCredentials" Text="Invalid Username or Password" />

        </asp:Panel>

    </asp:Content>

Here's the code-behind (with unnecessary details excised):
namespace webapp
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            (webapp.MasterPages.MasterPage)Page.Master).headerImage = "default";
            this.Master.headerImage = "default";

            if (!Page.IsPostBack)
            {
                this.pnlInvalidCredentials.Visible = false; // error is here
                this.BindPressRoomItem();
            }
        }
    }
}

This page/code-behind is top level, it's not it any folder or anything.  Also this project is an ASP.NET Web Application that is borrowing code from a legacy web site project.  I didn't "Add Existing" to any files, all files were "Add New" to prevent compatibility problems. Tried this, didn't work.
In the code-behind, every attempt to manipulate items declared in the aspx page results in an error like:

'_Default' does not contain a definition for 'pnlInvalidCredentials'

or

The name 'txtUsername' does not exist in this context.

A: Since I refreshed this page you've removed the line with the page directive at the top of your html file, but it looked like you maybe need to include the namespace.
Try:
Inherits="webapp._Default" instead of Inherits="_Default"

A: Try changing the "CodeBehind" attribute in your Default.aspx page to "CodeFile."

A: If this is a web application, sometimes it happens that the *.designer.cs file is not updated with your latest changes.
Try this:

*

*Remove the panel (just cut it)

*Save

*Undo

*Save again (this will regenerate the *.designer.cs file)

*Rebuild

Edit:
Other possibilities that will fail the regeneration of the *.designer.cs file are syntax errors such as missing end tags in your aspx pages.

A: I just had the same problem. What fixed it for me was:

*

*in my code behind file, the class was defined as 'Public class'. Changing this to 'Partial Class', then clicking 'Convert to Web Application' regenerated the 'Designer' file and fixed the problem.


text:
Q: An Image Button navigate to another site html/css This is my code:
HTML:

    <input type="image" class="button" value="">

CSS:
.button {
  background:url(example.jpg) no-repeat;
  cursor:-webkit-grab;
  border: none;
}

What should happen is that it display an image and when I click on, it will navigate to another this site index2.html. It worked with another image but it had an annoying border but after I changed the image it doesn't work any more.

A: You do not need an input type button, simply use img...
html:

css:
a img {
  border: none;
  cursor: grab;
}


text:
Q: How to add token_id to .kube/config file directly The official documentation of kubernetes (https://kubernetes.io/docs/reference/access-authn-authz/authentication/) states at some point: "3. Call Kubectl with --token being the id_token OR add tokens to .kube/config" (just search for mentioned phrase in the provided doc url to get the context).

Can anyone give me example where can I "add tokens to .kube/config" directly?
I am in a scenario, when it is needed for me, I can access my cluster with --token inline option but I need to go with adding it to .kube/config.
I am trying to do sth like this but doesn't work (still need to add --token inline option, doesn't work without it):
users:
  - user:
      token: >-
        ey...........

A: Yeah... yellow duck works... 5 sec after posting question I noticed that the "context" stuff is the key factor here, so the user of clyster need to match the name of user in users (I was missing the "name" filed for my user, matching the correct cluster context...), e.g.:
users:
  - name: shoot-x
    user:
      token: >-
        ey


text:
Q: how to use googlecharts API: DataTable.toJSON() all
I want to use php to get data from mySQL database, then use googe charts to draw a chart. I used json_encode() to convert my query result table to JSON, but it does not work. It returned, the table has no columns. I noticed there is toJSON() function in Google charts API, but there is no detailed information. Anyone knows how to use this function? thanks


text:
Q: How to filter the oldest cell in row with Cloud BigTable connector for DataFlow? I'm trying to retrieve the oldest cell of a certain row in BigTable in my DataFlow pipeline (using Beam SDK 2.4.0). However I can't seem to find any type of filter that would allow me to do this?
Further down the pipeline the value of the oldest cell would be used in conjunction with the newest cell and be written to BigQuery. This is what I have so far to retrieve the most recent cell:
input.apply("Read protos from BigTable", BigtableIO.read()
                .withProjectId(config.getBigtableProject())
                .withInstanceId(config.getBigtableInstance())
                .withTableId(this.bigTableId)
                .withRowFilter(RowFilter.newBuilder()
                        .setFamilyNameRegexFilter("proto")
                        .setCellsPerColumnLimitFilter(1)
                        .build()))
     .apply("Row to TableRow", ParDo.of(new DoFn<Row, TableRow>() { ...

I would expect there to be something similar, selecting 1 cell but in reverse order?
Any ideas?

A: This feature is possible, but there's no easy easy answer.  In general, Bigtable only allows one form of ordering.  In the case of cells, the version ordering is largest to smallest.
If you want to get a notion of "oldest", you can do one of the following:

*

*Read all of the cells, and get the oldest one.

*Reverse the ordering of the cells.  Explicitly set Long.MAX_VALUE - now when you write, and then you can use the standard ordering.

*Read all of the cells, but use the "strip value" filter so that you don't return all of the data, and then follow up with another read for each row with a filter for the "oldest" timestamp you found in the first read.


text:
Q: Finding all properties and subproperties of an object Sometimes I want to know if an object has a property that I am looking for but sometimes an object has a lot of properties and it may take some time to find it debugging it. It will be nice if I could write a function that will find all the properties and its values in a a string then I can paste that string in notepad for instance and look for the value that I am looking for with the find feature that notepad has. So far I have something like this:
public void getAllPropertiesAndSubProperties(System.Reflection.PropertyInfo[] properties)
        {
            foreach (var a in properties)
            {
                //MessageBox.Show(a.ToString());
                // do something here to test if property a is the one
                // I am looking for
                System.Reflection.PropertyInfo[] temp = a.GetType().GetProperties();
                // if property a has properties then call the function again
                if (temp.Length > 0) getAllPropertiesAndSubProperties(temp);
            }
        }

Editing the question I have worked:
so far I have added the following code. I can pass whatever object I want to the following method and I can see all the properties. I am having trouble viewing the values of the properties
![public void stackOverex(dynamic obj)
{
    // this is the string where I am apending all properties
    string stringProperties = "";

    Type t = obj.GetType();
    List<PropertyInfo> l = new List<PropertyInfo>();
    while (t != typeof(object))
    {
        l.AddRange(t.GetProperties());
        t = t.BaseType;

        var properites = t.GetType().GetProperties();
        foreach (var p in properites)
        {
            string val = "";
            try
            {
                val = obj.GetType().GetProperty(p.Name).GetValue(obj, null).ToString();
            }
            catch
            {

            }
            stringProperties += p.Name + " - " + val + "\r\n";
        }

    }

    MessageBox.Show(stringProperties);
}

Yeah visual studio debugger is great but look how many properties an object can have. I am actually looking for the indexSomething property of a gridViewColumnHeader I don't remember the exact name I just remember I have used it before. I have an event that fires when a column gets clicked and I would like to know the index not the name "column number 2? or 3 was clicked". I know I can get it with the name but it will be nice if I can implement this debugger function. See how complex it can get in the picture below.

A: If you want all properties including of base type then you could do this:
        Type t = typeof(AnyType);
        List<PropertyInfo> l = new List<PropertyInfo>();
        while (t != typeof(object))
        {
            l.AddRange(t.GetProperties());
            t = t.BaseType;
        }

or maybe you want a recursive print of properties, up to a level:
    public static void ReadALotOfValues(StringBuilder b, object o, int lvl, int maxLvl)
    {
        Type t = o.GetType();
        List<PropertyInfo> l = new List<PropertyInfo>();
        while (t != typeof(object))
        {
            l.AddRange(t.GetProperties());
            t = t.BaseType;
        }
        foreach (var item in l)
        {
            if (item.CanRead && item.GetIndexParameters().Length == 0)
            {
                object child = item.GetValue(o, null);
                b.AppendFormat("{0}{1} = {2}\n", new string(' ', 4 * lvl), item.Name, child);
                if (lvl < maxLvl)
                    ReadALotOfValues(b, child, lvl + 1, maxLvl);

            }
        }
    }

EDIT: Calling the above method:
object o = ...some object here...;
var b = new StringBuilder();
ReadALotOfValues(b, o, 0, 5);
Console.WriteLine(b.ToString());

The above will read properties of up to 5 levels of depth into the objeto.
The search must be limited somehow, otherwise it would loop forever... think of a self-referencing object.


text:
Q: Flutter and Firebase: Show stored information from cloud_firestore in widget I want to show data from my firebase cloudfirestore as you see in the picture:

In a Settings page I want to show all the information from the logged-in user.
Here is the Settings-Code ("einstellungen" in german):
class einstellungen extends StatelessWidget {
  final user = FirebaseAuth.instance.currentUser;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text("Einstellungen"),
      ),
      backgroundColor: Colors.orange,
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
                margin: const EdgeInsets.only(
                    left: 8.0, right: 8.0, top: 10.0, bottom: 5.0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.white.withOpacity(0.2),
                ),
                child: Column(
                  children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text('Benutzer:',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            bottom: 10.0, left: 10.0, right: 10.0),
                        child: Text(''),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text('Spitzname:',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            bottom: 10.0, left: 10.0, right: 10.0),
                        child: Text(''),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text('E-Mail:',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            bottom: 10.0, left: 10.0, right: 10.0),
                        child: Text(''), // here should print the email address from firestore
                      ),
                    ),
                    Text(''),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text('Hinweis: ',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text(
                            'Wenn Du dein Konto löschen oder dein Passwort zurücksetzen möchtest, schreibe bitte eine Email an medien@visuhome.de'),
                      ),
                    ),
                    Text(''),
                  ],
                )),
            Container(
              margin: const EdgeInsets.only(
                  left: 8.0, right: 8.0, top: 3.0, bottom: 3.0),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20),
                color: Colors.white.withOpacity(0.2),
              ),
              child: Row(
                children: [
                  ButtonNutzung(),
                  Text("Nutzungsbedingungen",
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Divider(),
            ),
            SizedBox(height: 10),
            if (user.uid != null)
              Text(
                'Cloud User-ID: ' + user.uid,
                style: TextStyle(color: Colors.black),
              ),
            SizedBox(height: 10),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Divider(),
            ),
            GestureDetector(
              onTap: _launchURL2,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                    child: Text(
                      'created by visuhome',
                      style: TextStyle(
                          fontWeight: FontWeight.w300,
                          fontSize: 12,
                          color: Colors.black),
                    ),
                  ),
                  Image(
                    //AssetImage oder SizedBox mit child und width
                    image: AssetImage('assets/visuhome_logo_black_flutter.png'),
                    fit: BoxFit.fitHeight,
                    height: 30,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                    child: Text(
                      'Version 1.0',
                      style: TextStyle(
                          fontWeight: FontWeight.w300,
                          fontSize: 12,
                          color: Colors.black),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

As you can see I do get information from the FirebaseAuth.instance.currentUser, so the userid from the logged-in user is shown. But I want the information from the userdata in firestore too.
Can anybody help with this basic firestore-trick I guess? I'm new in flutter. Tried a lot but cannot find solutions which fit for my example. Thanks a lot

A: You should to create query to Firestore and get user details.
If you know the user ID, you can call doc function to create query.
 @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data.data();
          return Text("Full Name: ${data['full_name']} ${data['last_name']}");
        }

        return Text("loading");
      },
    );
  }

Or use where expression to find user by its attributes (for example email):
FirebaseFirestore.instance
  .collection('users')
  .where('email', isEqualTo: "test@yahoo.de")
  .get()

For more details check Firestore tutorial


text:
Q: How can i pass jTextField value from one class to another when clicking a jButton? Greetings from jamaica,
I'm having trouble with a netbeans java project. I have two separate classes: A gui class called MainJFrame.java and another class called main.java.
In the MainJFrame form i have a jTextField and a jbutton. How can i pass the jtextfield value to the main.java class by clicking the jbutton?
thanks.

A: one possible solution would be to create a third class which handles the communication. There you would have to register the main.java and pass it to MainJFrame.java.
For Example
public class handler {
    public static main myClass = new main;

    public static main getClass() {
        retunr myClass;
    }

}

Your JFrameMain should containt a new variable
private main mainClass = handler.getClass();

Your onClicklistener should now voi dthe method from your mainClass which gets the text.
mainClass.setText(textFromJText);

Hope i could help you.

A: *

*You keep a reference to an instance of your Main class in the MainJFrame class.

*You define an ActionListener for your JButton.

*In this ActionListener, you get the value of the JTextField with JTextField.getText()

*And you call a method of Main class on the instance you kept in first step with the text as a parameter.


text:
Q: Files not uploading to remote server with Net_SFTP I have the following class for uploading files in a directory, however, the first directory that should be created is getting set up as 'File' rather then a 'File Folder'. Because of that, the items that should be uploaded are not uploading properly. I'm not sure if I am missing a step or not or if I set this up incorrectly.

include 'Net/SFTP.php';

class SFTPConnection
{
    private $sftp;

    public function __construct($host, $username, $password)
    {
        $this->sftp = new Net_SFTP($host);
        if (!$this->sftp)
            error_log("Could not connect to $host.");

        if (!$this->sftp->login($username, $password))
            error_log("Could not authenticate with username $username " .
              "and password $password.");
    }

    public function uploadFiles($dir, $to, $from) {
        $result = array();
        $toDir = str_replace($from, $to, $dir);
        $cdir = scandir($dir);

        foreach ($cdir as $key => $value) {
            if (!in_array($value, array(".", ".."))) {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
                    if(!$this->sftp->mkdir($toDir . DIRECTORY_SEPARATOR .$value)) {
                        echo "Could not create directory
'";
                        exit();
                    }
                    $result[$value] = $this->uploadFiles($dir . DIRECTORY_SEPARATOR . $value, $to, $from);
                } else {
                    $result[] = $value;
                    echo "Uploading $dir/$value
";
                    if(!$this->sftp->put($toDir . DIRECTORY_SEPARATOR . $value, $dir . DIRECTORY_SEPARATOR . $value, NET_SFTP_LOCAL_FILE)) {
                        echo "Could not upload file
";
                        exit();
                    }
                }
            }
        }
        return $result;
    }
}

A: It works for me. I tried $sftp->mkdir('Test folder') and $sftp->mkdir('./Test folder/Another folder'). The directories that were created were created as expected.
One thing to keep in mind...  DIRECTORY_SEPARATOR is probably not the best thing to use in this instance. On Windows, for example, DIRECTORY_SEPARATOR is \ - not /. This is an issue because the SFTP specs say that directories are to be represented with / - not . Quoting draft-ietf-secsh-filexfer-02:

This protocol represents file names as strings.  File names are assumed to use the slash ('/') character as a directory separator.

I guess to have further insight a copy of the SFTP logs would be helpful. Maybe just provide the SFTP logs of a mkdir operation. You can get the SFTP logs by doing define('NET_SFTP_LOGGING', 2) at the top and then doing echo $sftp->getSFTPLog() after the mkdir.