text:
Q: Sum Over Solutions to an Equation Two Related Questions

*

*Is there any general built-in functionality for computing a sum over solutions to an equation? This is common in number theory. For example, computing sums of the following form...

$$F(n)=\sum_{i+j+k=n}f(i,j,k)$$
where i, j, and k are nonnegative integers.
Note: The above is just an example. I would like to be able to sum over solutions to other simple equations where IntegerPartitions[] does not apply, like $i^2+j+k=n$.

*A related question: How can I sum over a set of sets using the $Sum[]$ function? Because if the answer to question 1 is "no", then I would hope I could still use $Sum[]$ to sum over a set of solutions (sets).

• For example, I know
$$\sum_{i \in \{a,b,c\}}f(i,j)$$
can be computed with
Sum[f[i,j],{i,{a,b,c}}]

giving
$$f[a, j] + f[b, j] + f[c, j]$$
• What I'm looking for is a way for Mathematica to compute
$$\sum_{\{i,j\} \in \{(a,x),(b,y),(c,z)\}}f(i,j)$$
to give
$$f[a, x] + f[b, y] + f[c, z]$$
I would expect/want Mathematica to give that using the code
Sum[f[i,j],{{i,j},{{a,x},{b,y},{c,z}}]

but that gives an error.
Any ideas?

A: 1.
n=7;
Total[f@@@IntegerPartitions[n,{3}]]
(*f[3, 2, 2] + f[3, 3, 1] + f[4, 2, 1] + f[5, 1, 1]*)

Revised for the additional condition to not make any use of IntegerPartitions and to Select on an arbitrary condition.
n=7;
g[{i_,j_,k_}]:=i^2+j+k==n;
Select[Partition[Flatten[Table[{i,j,k},{i,1,n},{j,1,n},{k,1,n}]],3],g]
(*{{1,1,5},{1,2,4},{1,3,3},{1,4,2},{1,5,1},{2,1,2},{2,2,1}}*)

Revised for non-negative
n=7;
g[{i_,j_,k_}]:=i^2+j+k==n;
Select[Partition[Flatten[Table[{i,j,k},{i,0,n},{j,0,n},{k,0,n}]],3],g]

(*{{0,0,7},{0,1,6},{0,2,5},{0,3,4},{0,4,3},{0,5,2},{0,6,1},{0,7,0},
   {1,0,6},{1,1,5},{1,2,4},{1,3,3},{1,4,2},{1,5, 1},{1,6,0},
   {2,0,3},{2,1,2},{2,2,1},{2,3,0}}*)

2.
Total[f@@@{{a,x},{b,y},{c,z}}]
(*f[a, x] + f[b, y] + f[c, z]*)

There are almost always a dozen different ways of doing almost anything in Mathematica

A: Clear["Global`*"]

For the first part
F[n_] := Sum[f[i, j, k], {i, 1, n - 2}, {j, 1, n - i - 1}, {k, 1, n - i - j}];

F /@ Range[5]

(* {0, 0, f[1, 1, 1], f[1, 1, 1] + f[1, 1, 2] + f[1, 2, 1] + f[2, 1, 1],
 f[1, 1, 1] + f[1, 1, 2] + f[1, 1, 3] + f[1, 2, 1] + f[1, 2, 2] + f[1, 3, 1] +
   f[2, 1, 1] + f[2, 1, 2] + f[2, 2, 1] + f[3, 1, 1]} *)

For the second part
Sum[f @@ i, {i, {{a, x}, {b, y}, {c, z}}}]

(* f[a, x] + f[b, y] + f[c, z] *)

Or using Total
Total[f @@@ {{a, x}, {b, y}, {c, z}}]

(* f[a, x] + f[b, y] + f[c, z] *)

EDIT: For the modified first part
Clear["Global`*"]

F[n_Integer?Positive] := Module[{inst = FindInstance[
     {i^2 + j + k == n, i > 0, j > 0, k > 0},
    {i, j, k}, Integers, n^3]},
  Total[f[i, j, k] /. inst]]

F[12]

(* f[1, 1, 10] + f[1, 2, 9] + f[1, 3, 8] + f[1, 4, 7] + f[1, 5, 6] +
  f[1, 6, 5] + f[1, 7, 4] + f[1, 8, 3] + f[1, 9, 2] + f[1, 10, 1] +
  f[2, 1, 7] + f[2, 2, 6] + f[2, 3, 5] + f[2, 4, 4] + f[2, 5, 3] +
  f[2, 6, 2] + f[2, 7, 1] + f[3, 1, 2] + f[3, 2, 1] *)

A: For the first part, if the equation is linear, use IntegerPartitions together with Permutations:
Total[f @@@ Join @@ Permutations /@ IntegerPartitions[7, {3}]]

f[1, 1, 5] + f[1, 2, 4] + f[1, 3, 3] + f[1, 4, 2] +
   f[1, 5, 1] + f[2, 1, 4] + f[2, 2, 3] + f[2, 3, 2] + f[2, 4, 1] +
   f[3, 1, 3] + f[3, 2, 2] + f[3, 3, 1] + f[4, 1, 2] + f[4, 2, 1] +
   f[5, 1, 1]

If you want to include zero, use the third argument of IntegerPartitions to supply an explicit list of values to choose from:
Total[f @@@ Join @@ Permutations /@ IntegerPartitions[7, {3}, Range[0, 7]]]

f[0, 0, 7] + f[0, 1, 6] + f[0, 2, 5] + f[0, 3, 4] +
   f[0, 4, 3] + f[0, 5, 2] + f[0, 6, 1] + f[0, 7, 0] + f[1, 0, 6] +
   f[1, 1, 5] + f[1, 2, 4] + f[1, 3, 3] + f[1, 4, 2] + f[1, 5, 1] +
   f[1, 6, 0] + f[2, 0, 5] + f[2, 1, 4] + f[2, 2, 3] + f[2, 3, 2] +
   f[2, 4, 1] + f[2, 5, 0] + f[3, 0, 4] + f[3, 1, 3] + f[3, 2, 2] +
   f[3, 3, 1] + f[3, 4, 0] + f[4, 0, 3] + f[4, 1, 2] + f[4, 2, 1] +
   f[4, 3, 0] + f[5, 0, 2] + f[5, 1, 1] + f[5, 2, 0] + f[6, 0, 1] +
   f[6, 1, 0] + f[7, 0, 0]

If you're not into @@@ @@ /@ voodoo, the same can be done with
Total[Apply[f, Apply[Join, Map[Permutations, IntegerPartitions[7, {3}]]], {1}]]

For more complicated equations, you can use Solve over the integers:
Total[f[i, j, k] /. Solve[i^2 + j + k == 7, {i, j, k}, PositiveIntegers]]

f[1, 1, 5] + f[1, 2, 4] + f[1, 3, 3] + f[1, 4, 2] + f[1, 5, 1] + f[2, 1, 2] + f[2, 2, 1]

If you want to include zero:
Total[f[i, j, k] /. Solve[i^2 + j + k == 7, {i, j, k}, NonNegativeIntegers]]

f[0, 0, 7] + f[0, 1, 6] + f[0, 2, 5] + f[0, 3, 4] +
   f[0, 4, 3] + f[0, 5, 2] + f[0, 6, 1] + f[0, 7, 0] + f[1, 0, 6] +
   f[1, 1, 5] + f[1, 2, 4] + f[1, 3, 3] + f[1, 4, 2] + f[1, 5, 1] +
   f[1, 6, 0] + f[2, 0, 3] + f[2, 1, 2] + f[2, 2, 1] + f[2, 3, 0]

A: For your more complicated example, you can use Solve to find the needed triples:
set = Values @ Solve[
    i^2 + j + k == 13 && i > 0 && j > 0 && k > 0,
    {i, j, k},
    Integers
]

{{1, 1, 11}, {1, 2, 10}, {1, 3, 9}, {1, 4, 8}, {1, 5, 7}, {1, 6, 6}, {1, 7,
    5}, {1, 8, 4}, {1, 9, 3}, {1, 10, 2}, {1, 11, 1}, {2, 1, 8}, {2, 2, 7}, {2,
    3, 6}, {2, 4, 5}, {2, 5, 4}, {2, 6, 3}, {2, 7, 2}, {2, 8, 1}, {3, 1, 3}, {3,
     2, 2}, {3, 3, 1}}

Then you can use one of the methods from the other answers to form the desired sum, e.g.:
Sum[f @@ t, {t, set}]

f[1, 1, 11] + f[1, 2, 10] + f[1, 3, 9] + f[1, 4, 8] + f[1, 5, 7] +
   f[1, 6, 6] + f[1, 7, 5] + f[1, 8, 4] + f[1, 9, 3] + f[1, 10, 2] +
   f[1, 11, 1] + f[2, 1, 8] + f[2, 2, 7] + f[2, 3, 6] + f[2, 4, 5] +
   f[2, 5, 4] + f[2, 6, 3] + f[2, 7, 2] + f[2, 8, 1] + f[3, 1, 3] + f[3, 2, 2] +
    f[3, 3, 1]

or
Total[f @@@ set]

f[1, 1, 11] + f[1, 2, 10] + f[1, 3, 9] + f[1, 4, 8] + f[1, 5, 7] +
   f[1, 6, 6] + f[1, 7, 5] + f[1, 8, 4] + f[1, 9, 3] + f[1, 10, 2] +
   f[1, 11, 1] + f[2, 1, 8] + f[2, 2, 7] + f[2, 3, 6] + f[2, 4, 5] +
   f[2, 5, 4] + f[2, 6, 3] + f[2, 7, 2] + f[2, 8, 1] + f[3, 1, 3] + f[3, 2, 2] +
    f[3, 3, 1]

A: Overall concept: Sum is built around iterators. If you are wanting to sum up something based on criteria other than sequential iterators, you are better off generating a list and just saying to add everything in the list (i.e., Total).
Most of the other answers are excellent. Here are my favorites, with explanations rooted in the overall concept above.
Question 1:
Generate a list containing the answers and call Total to add them all up. Using your example:
Total[f[i,j,k]/.Solve[{i+j+k==13,i>0,j>0,k>0},{i,j,k},Integers]]

Here, Solve[{i+j+k==13,i>0,j>0,k>0},{i,j,k},Integers]] generates replacement rules for all of the cases that meet your criterion, f[i,j,k]/. puts those solutions into the function, and Total adds them all up.
When Version 12 comes out, you can do this even more concisely:
Total[f[i,j,k]/.Solve[i+j+k==13,{i,j,k},PositiveIntegers]]

Question 2:
Again, use Total. This time make a list of the parameter lists, and use the @@@ version of Apply:
Total[f@@@set]

This takes elements of set and puts them in f as parameters, so f@@@{{i1,j1,k1},{i2,j2,k2}} returns {f[i1,j1,k1],f[i2,j2,k2]}
You can generate your set however you like, but if it is based on the first example, you could do it like this:
set={i,j,k}/.Solve[{i+j+k==13,i>0,j>0,k>0},{i,j,k},Integers]


text:
Q: Basic MySQL help? - submitting data I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code

I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
    $mysqli = mysqli_init();

//Log in to the DB
    if (!$mysqli) {
        die('mysqli_init failed');
    }

    if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
        die('Setting MYSQLI_INIT_COMMAND failed');
    }

    if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
        die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
    }

    if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
}

That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)

A: Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
  $conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
  $sql = "SELECT * FROM users WHERE username = '$username'";
  $result = $conn->query($sql);
?>

Read more here.

A: If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)

Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;

and then fetch the query results.
If this does not answer your questions please provide some clarifications.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure NLog programmatically, web.config I have following Nlog config section in my web.config (modified to show only relevant info)
<nlog>
    <targets async="true">
      <target name="mail" type="Mail"
              body="${date:format=yyyy-MM-dd HH\:mm\:ss} - ${level} [${logger}] - ${message} ${newline}${newline}${event-context:item=OtherInfo}${newline}${newline}${exception:maxInnerExceptionLevel=2:format=ToString}${newline}${newline}"
              subject="[${machinename}] ${logger}"
              to="mail@domain.com" encoding="UTF-8" from="anotheremail@domain.com" smtpServer="" enableSsl="true" smtpAuthentication="Basic"
      />
    </targets>
    <targets>
      <target name="mailsync" type="Mail" body="${date:format=yyyy-MM-dd HH\:mm\:ss} - ${level} [${logger}] - ${message} ${newline}${newline}${event-context:item=OtherInfo}${newline}${newline}${exception:maxInnerExceptionLevel=2:format=ToString}${newline}${newline}" subject="[${machinename}] ${logger}"
              to="mail@domain.com" encoding="UTF-8" from="anotheremail@domain.com" smtpServer="" enableSsl="true" smtpAuthentication="Basic"
      />
    </targets>
    <rules>
      <logger name="*" level="Error" writeTo="mail" />
    </rules>
</nlog>

I am updating the configuration via code in Application_Start,
var config = LogManager.Configuration;
const string targetName = "mail";

var wrapper = (AsyncTargetWrapper) config.FindTargetByName(targetName);
wrapper.WrappedTarget.SmtpServer = "hostname";
wrapper.WrappedTarget.SmtpUserName = "username";
wrapper.WrappedTarget.SmtpPassword = "password";

config.RemoveTarget(targetName);
config.AddTarget(targetName, wrapper);

LogManager.Configuration = config;

However, when I log any errors, the emails are not being sent. I have an additional file target (not shown in the code snippet), that contains the error message. That tells me the errors are getting logged, but somehow not sent via email.
If instead of updating the config via code, if I hard code the values in the web.config, then the emails get sent. I have verified that the smtp values that I am using via code are valid.
I did search through many similar questions on SO, but I haven't yet found one that mentions a solution that works for me.
EDIT:
Based on Xharze's answer, I enabled exceptions, internal logging and I also outputted the values of the target after I had made my changes. The internal log showed an exception about a MailAdrress being the incorrect format. So I checked all target values that accept an email address and I found the issue. The from property of the target accepts an email address whereas I was providing it a display name!

A: Could you try enabling throw exceptions and the interalnal log, and post it? It may provide more information. See github.com/NLog/NLog/wiki/Logging-troubleshooting.


text:
Q: Using For Loop and Foreach to create a list in C# I am trying to create a draft order for a game I'm working on but I cannot get it to function how I need it to. I need 5 rounds with each round number properly and each pick should be numbered 1-10 for each round. Here is the code I'm working with:
List<Draft> _draftorder = new List<Draft>();

foreach (Team t in teams)
{
    for (int i = 1; i <= 5; i++)
    {
        _draftorder.Add(new Draft()
        {
            city = t.city,
            round = i++,
            pick = i++,
        });
    }
}

Any help is appreciated!

A: I find the logic is easier to follow when the code matches the stepwise workflow of the requirements, and the variable names match the concepts in the requirements.
List<Draft> _draftorder = new List<Draft>();

for (int currentRound=1; currentRound<=10; currentRound++)
{
    int pickOrder = 1;
    foreach (Team t in teams)
    {
        _draftorder.Add(new Draft()
        {
            city = t.city,
            round = currentRound,
            pick = pickOrder++
        });
    }
}

A: You need to add an additional for loop and put the foreach loop inside the first for loop:
List<Draft> _draftorder = new List<Draft>();

// Allow 5 rounds
for (int i = 1; i <= 5; i++)
{
    // Allow every team to pick some drafts
    foreach (Team t in teams)
    {
        // Limit them to a specific amount of picks per round
        for (int j = 1; j <= 10; j++)
        {
            _draftorder.Add(new Draft()
            {
                city = t.city,
                round = i,
                pick = j,
            });
        }
    }
}


text:
Q: SQLite drop table when row in another table is deleted I've been wrestling with setting up a trigger and keep getting the error:

SQL logic error near "DROP": syntax error

I have several tables main_table, other_one, other_two, etc.

*

*main_table has several columns with the primary key column named filehash

*The values in the primary key column of main_table are also the names of the other_* tables

So, if I delete a row in main_table with a primary key of other_one, I want the trigger to DROP the table other_one too
Here's the trigger statement that is producing the error
CREATE TRIGGER remove_other_one AFTER DELETE ON 'main_table'
WHEN (OLD.filehash == 'other_one')
BEGIN
 DROP TABLE IF EXISTS 'other_one' ;
END remove_other_one;

EDIT: the 'fuller' error I get when I run the trigger statement in SQLite DB Browser is:

near "DROP": syntax error: CREATE TRIGGER remove_other_one AFTER DELETE ON 'main_table' WHEN (OLD.filehash == 'other_one') BEGIN DROP

A: Based on SQLite trigger doc I believe that it is not possible:

There is no option for DDL/dynamic SQL inside trigger.
I guess that you wanted to achieve something like PostgreSQL DBFiddle Demo 1  and Demo 2
You could handle your case in application code. Anyway table per date/customer/hash almost always indicates poor design and in long run will cause more problems.


text:
Q: Problem in Telegram bot logic on node-telegram-bot-api Just starting to learn JS and NodeJs in general. I'm writing a TG bot just as a project to gain knowledge and experience in JS, in general, that's not the point! Faced such a problem in the event handler: I have something like a registration window with keyboard_inline, where when the /start command comes out several buttons with a gender selection

bot.onText(/\/start/, async msg => {
db.get("SELECT * FROM users WHERE user_id = ?", [msg.chat.id], async (no, yes) => {
    yes ?
    console.log('ss')
    : await bot.sendMessage(msg.chat.id, msg.chat.first_name + ',' + ' ' + 'добро пожаловать! \n\n' +
    'Вы ещё у нас не зарегистрированы! Пожалуйста, выберите свой пол для продолжения регистрации:', keyboardName(signup));
}); });

There is a database, but this is not the point, the check is disabled there, it does not affect it in any way. But the actual call to the keyboardName function, made it to simplify the readability of the code
    const keyboardName = (name) => {
    return {
        reply_markup: JSON.stringify ({
            inline_keyboard: name
        })
    }
};

Here are the buttons:
const signup = [
    [
      {
        text: ' Я парень',
        callback_data: 'signup_man'
      },
      {
        text: ' Я девушка',
        callback_data: 'signup_woman'
      }
    ]
];

And here is the button click event handler itself:
bot.on('callback_query', async query => {
    switch (query.data) {
        case 'signup_man':
            await bot.sendMessage(query.message.chat.id, 'Введи возраст от 16 до 90');
            bot.on('message', async msg => {
                if (msg.text >= 1 && msg.text <= 90) {
                    return await bot.sendMessage(msg.chat.id, 'это тестовое сообщение');
                } else
                bot.sendMessage(msg.chat.id, 'Возраст от 16 до 90');
            })

            break;
        case 'signup_woman':
            bot.sendMessage(msg.chat.id, 'С тобой приятно иметь дело! А теперь введи свой возраст, просто в чат, цифрами :)');
            break;
    }
});

The problem is this: when you use the bot from one account, then all the logic and checks work properly, but if I launch several more accounts at the same time, then in the last paragraph, when entering the age of the user (chat.id), several messages will be sent to the chat ( commensurate with the number of accounts with a running bot and clicking on the button). I would like to understand what is wrong and why it happens)
Tried a lot of things, but I don't seem to understand the logic

A: This happens because each button click adds another handler.
Big problem of node-telegram-bot-api that you cannot use some handler in other case and not use in another.
To handle this, you can create and "array" that will contain user ids and their stages. You can check my implementation of this logic
https://github.com/Blabolka/five-minutes-to-three-tg-bot/blob/master/src/common/services/StageManager.ts
And here the example of using:
USING EXAMPLE IMAGE
In your case, you need to declare your bot.on('message') handler initialization on the same level with bot.on('callback_query') and write some if condition in bot.on('message') handler that will check if user clicked on any of the buttons


text:
Q: Do I need to update Kotlin every time I work on my company's application? I'm having trouble building an Android project at the company I am working for. Currently, I get a whole bunch of errors when I try to build my project due to the specified versions of the dependencies defined in the .gradle file not matching the current version of kotlin.
So, to rectify this I have updated the highlighted dependency versions in the project to match the current version of kotlin I am using.
My big question is whether I have to do this every time I want to develop on Android? I'm assuming the answers a big fat NO, but as someone completely new to this, I definitely need some help from the community if possible.
Just to explain me, we have limited development resources, hence the question on here. I'm going to be taking over the Android side of things and should probably sign up for a one-week taster course (or something like that) but for now, I have our whole Android app on our hands with minimal comments, tests or instructions.
I also posted this question to Reddit and the best advice I was given was to add a '+' to the dependencies in build.gradle instead of version numbers. I've since tried this and feel like it might not be the solution I need. This is because I feel that the live application wouldn't be working if this were the issue.
In short, I feel like my local version of the application might not be working because I have some settings in Kotlin/Android studio somewhere that I need to change.....Any suggestions you can provide RE what these settings may be would be a huge help!

A: The error from your comment isn't related to Kotlin. Make sure that all versions of the support library are the same, currently you're using 26.0.0-alpha1 for customtabs and 25.3.1 for cardview-v7. You should probably use version 25.3.1 for customtabs as well.
Also, avoid using +, as this makes your build always use the latest version of the dependency, which makes specific builds unreproducable.


text:
Q: Is there anyway to hide / obfuscate .realm files on android? I'm planning to store hashed passwords and PINs using realm. I've been researching on salting, and it's recommended to have a different salt for each password / PIN. Also it's recommended that the salt should be somewhere within the database.
My question is are .realm files secure? Is there a way to guarantee that the contents of the .realm files cannot be opened?

A: In general you can get the the realm file from the phone (if it rooted) and read it via realm browser (https://github.com/realm/realm-browser-osx). But there are possibility to encrypt the *.realm file. Look at the corresponding section of the documentation https://realm.io/docs/java/latest/#encryption .

A: Realm files aren't encrypted by default, however realm does support encryption of the files.
You can view the encryption documentation here, and an example implementation here.
You should also read up on the Android keystore, which will allow you to securely store the key.


text:
Q: Creating a dropdown list with sub action items in asp.net, c# I need to create a dropdownlist of items. It should have an action and a sub action. for ex, how an unordered list looks.
I have to do it in my code behind only. I am getting a ListItemCollection and binding it to dropdown list.
So before i bind it to dropdown list i have to do some thing to make the the dropdown list look like the way i need.
Please help me out.
Thanks in advance
Santosh

A: the solution is subclass DropDownList class and use optgroup attribute when render item.
Checkout this link:
http://ignatu.co.uk/articles/Adding_groups_to_the_ASPNET_DropDownList_control/


text:
Q: request paramater id always returns same value I am trying to fetch single document from db with id parameter
const router = express.Router();
// middleware for base url
server.use("localhost/api/v1", tasksRouter);
router
  .route("/tasks/:id")
  .get(controllers.getSingleTask)

const getSingleTask = async (req, res) => {
  try {
    const taskID = req.params.id;
    const task = await Task.findOne({ _id: taskID });
    if (!task) {
      return res.status(404).json({ msg: `No task with ID: ${taskID}` });
    }
    return res.status(200).json({ task });
  } catch (error) {
    return res.status(500).json({ msg: error });
  }
};

but every time i am making request the request.params contains parameter 'id' with same value even i am providing id value which doesn't exist and 'getSingleTask' controller returns same document.
I am using "express": "^4.17.1", and "mongoose": "^5.11.10"
i made request localhost/api/v1/tasks/somerandomid
and i logged my req.params.id and task getting after querying with id is
// id i am getting even after making request with 'somerandomid' as parameter
635651c3112d5405147b7e86

// since the id matches with first document of database controller 'getSingleTask' responds with the document.
{
  completed: true,
  _id: 635651c3112d5405147b7e86,
  task: 'task number 1',
  __v: 0
}


text:
Q: Calculate the average from 3 colors based on a percentage How can I calculate the average of three colors based on a given percentage?
For example we've green, yellow and red and want to get the average value:
The simplest way to do this is to create an image like this one:

And increase/decrease the background-position:
$('input').change(function(){
    $('#color').css({
        backgroundPosition: -this.value + "px 0"
    });
});

http://fiddle.jshell.net/VY4D8/
...however I think that can be done "better" with rgb/a or hex as output.
Just for interpretation purposes:

*

*** [0%] | #ff0000

*-- [1%]

*-- [2%]

*-- [3%]

*-- [4%]

*-- [5%]

*-- [...]

*** [11%] | #ffc600

*-- [12%]

*-- [13%]

*-- [14%]

*-- [15%]

*-- [16%]

*** [17%] | #ffee00

*...etc...

Is there already an implementation for this problem or has one of you written something in the past?
Update
Got it, thanks to Eevee https://stackoverflow.com/a/15125778/1250044:
var div = document.getElementsByTagName('div')[0];

$('input').change(function () {

    var max = this.getAttribute("max"),
        cur = this.value / max * max,
        r = Math.min(cur * 2, max),
        g = Math.min(max * 2 - cur * 2, max),
        rgb = g + "%, " + r + "%, 0%";

    div.style.backgroundColor = "rgb(" + rgb + ")";

}).change();

http://fiddle.jshell.net/VY4D8/1/

A: Do math?
You have:

*

*at 0%, red: rgb(100%, 0%, 0%)

*at 50%, yellow: rgb(100%, 100%, 0%)

*at 100%, green: rgb(0%, 100%, 0%)
If you want to figure out the color at 11%:

*

*Figure out which section it belongs to.  11% of the full spectrum lies 22% of the way between red and yellow.

*Interpolate: 22% of red plus 78% of yellow comes out to rgb(100%, 78%, 0%) or #ffc600.

A: You can do that CSS linear-gradient.
Demo: http://jsfiddle.net/ThinkingStiff/Jqdkq/
CSS:
.gradient {
    background: linear-gradient(
        to right,
        red, yellow, green
        );
    height: 20px;
    width: 300px;
}

HTML:


text:
Q: I get Proguard Error with Navigation Component, How can I solve the problem? I turned on Proguard in my android application project.
And I published app and lots of crashes occurred. 99% crash free become 40% crash free...
And I get this critical exception.
java.lang.IllegalStateException: View android.widget.LinearLayout{ffb46cf V.E...... ......ID 0,0-720,1238} does not have a NavController set
        at b.m.B.a(Navigation.java:84)
        at com.example.view.main.fragment.k.a(WebViewFragment.kt:448)

I am using Navigation Component and most of the crashes happen at this line.
Navigation.findNavController(mView).navigate(R.id.action_aFragment_to_bFragment, bundle, null)

I added this in my proguard-rules.pro
-keep class * extends androidx.fragment.app.Fragment{}

But Couldn't solve my problem. What should I do?


text:
Q: I've installed libcurl 7.51, but autogen could not recognize it I'm trying to install cgminer. using the instructions:
# git clone https://github.com/ckolivas/cgminer
# cd cgminer && git checkout v3.1.1
# cd ADL_SDK && wget http://www.lurkmore.com/mining/ADL_SDK.zip && unzip -j ADL_SDK.zip 'include/adl_*.h'
# cd .. && ./autogen.sh && ./configure --enable-opencl --enable-scrypt && make && make install
# cd && rm -rf cgminer && mkdir .cgminer

But, the autogen.sh show the following error:
checking for LIBCURL... no
checking for LIBCURL... no
configure: error: Missing required libcurl dev >= 7.18.2

So, I downloaded the last source code from Curl website
And checking the version:
$ curl-config --version
libcurl 7.51.0

But running the ./autogen.sh again I got the same error:
checking for LIBCURL... no
checking for LIBCURL... no
configure: error: Missing required libcurl dev >= 7.18.2

What am I doing wrong?

A: The line
configure: error: Missing required libcurl dev >= 7.18.2

indicates that you need the curl development files. Depending on your system they can be installed via
sudo apt-get install libcurl4-gnutls-dev

for Debian and Debian-based distributions like Ubuntu.
(Alternative packages are libcurl4-nss-dev for the NSS flavour of curl or libcurl4-openssl-dev for the OpenSSL flavour of curl.)
On RPM-based distributions like CentOS, use
sudo yum install libcurl-devel

instead. Package names and package managers might vary, depending on what Linux distribution you are using.
Unless you depend on a very recent version of curl, it should be sufficient to use the packages that are provided by your distribution instead of downloading the most recent version from the curl website. It saves you the trouble of compiling the library yourself, and the distributions also make sure that the library and its development files are placed in a location where configure scripts should find them.

A: look for lib path at debian packages website at files section and run before configure
export LIBCURL_LIBS=-L/path/to/libfile
export LIBCURL_CFLAGS=-I/path/to/include/dir


text:
Q: Which development skills have you acquired after 7-10++ years of experience in OO development? Some development skills, like refactoring operations, feel like they have an almost unlimited
pontential for learning - only the fool will say he's finished learning that.
Other skills are bound to specific tools, and being good developers we learn new tools
most of the time.
But some skills are related to how you think about code and how you approach coding, sometimes how a specific tool feature can be
applied. Rotating pair programming and working closely with other people seem to be the best way of acquiring these skills,
though certainly not the only method. (And sometimes you learn things you SHOULD have learned 5 years ago, these are not the ones I am asking about)
So I want to pair program with all of StackOverflow:
What are your late-acquired coding skills ?
Edit: I suppose I'm not thinking about the things you would have learned as a part of the curriculum if you were coming right out of school today.

A: Only when I realised that I needed people skills to complement my technical skills did I really start developing my career.
Amazing how often this is overlooked by programmers or seen as unimportant compared to 'development skills'.

A: It may seem silly and obvious but... I think this has required a lot of years to get the hang of it as far as I'm concerned :

*

*Knowing when to write comments where they are really needed.

*Knowing when NOT to write comments, because the code is now self-documenting enough.

A: It's the soft skills around being a better developer in a team than the nuts and bolts of actually being able to make an application that (more or less) meets the spec and compiles and makes the user/tester not shout too much.

*

*when to defensively write extensible code because you know that it will save you time in the end.

*

*when to explicitly not do point (1).

*how to work in a team

*how to read and react to a specification that isn't wonderfully exact or clearly written

*when (and how) to let someone else have the funky project because you are too busy with drudge

Mainly it's about being a better pack animal, there are times and places to be an alpha-male, but too often programmers can't take criticism and we can't always be playing with the projects like they're our toys.
If you can't do that, then Guy Kawasaki and Joel Spolsky have written a lot of good stuff on founding your own company.

A: Prototyping & Mocking.
I think about the times in the past when I've plunged feet-first into developing a feature 'in-situ' - much better to isolate the problem in a sandbox app.
Mocking - again, following on from the principles of isolation (Divide & Conquer), this is absolutely core to any design I come up with nowadays.

A: Some of the skills where not around when I started coding:

*

*Unit testing,

*Refactoring,

*Some other agile paradigms.

You should only stop learning if you stop breathing.

A: Pragmatism and People Skills.
Being pragmatic about a situation.  Yes, it may be ideal, but is it really necessary.  Something may be the coolest feature in the world, but will it really generate any more revenue.  Asking these questions and being realistic will allow you to filter out a lot of chaff from the wheat.
I am still learning People Skills.  It is not all about knowing all the answers, but rather being able to relay these to the Management and the Clients in a way they will understand and embrace.  Being an Autistic with OCD and Bi-Polar makes things a little tricky sometimes.

A: Hmm, writing testable code thanks to dependency injection. How did we manage before...
For me it's, knowing what to test.
I was a zealot for a while who said everything must be tested, DTO's get/set methods etc. This is impractical and unecessary. You must test (to death) the complex and critical stuff, because that's where your complex and critical defects are. Lightly test the rest.

A: I've learned not to be personally attached to the code I write. I no longer feel a personal attack/violation when people change my code or are critical of my code.

A: That I probably do not belong in management (where I spent a couple of years). I'm happier coding than managing :)
Edit: Furthermore; I'm just beginning to get a real grasp on TDD, and I'm enjoying it!

A: Software Architectures, Programming in the large.
I realized that software >> code, and the question of programming languages is tertiary at best.

A: The humility of seeing so much code, some good, some bad and then some that is just weird, that you recognize what you want to have where you work and what you don't want to have.  For example, some like a "Cowboy" style programming while others are totally methodical and won't do anything with it being part of a plan that has been written up, vetted and signed off on by 3 upper management folks to have the blessing to do something that may take a couple of weeks.
Getting better at organizing code and seeing where one can refactor to make something more generic so it has more uses or when to try to lock something down so it gets done as opposed to cosmetic changes done over and over again as the customer doesn't know what they want but they don't want the 101 prototypes they have seen.

A: Knowing: Although I can, doesn't mean I should "indulge" myself and build every request that comes my way. My primary objective is to provide a solution, and if that means taking something already there and expanding on it - then that's it.

A: I really agree with the "People skills" post, but aside from that:
To name one - I've really understood how languages are actually not languages. They are dialects.
It seems that for each micro-piece-of-knowledge that goes into the autonomous parts of my fingers, I'm blessed with the ability to generalize into a higher level of understanding of things. -- These are words from my father who is a welder/steel-worker. Couldn't agree more.
/Robert

A: Working with only the logical structure of my code and ignoring physical file locations as much as possible.


text:
Q: What performance gain will this code give? Code sample # 1
$customer_obj = Mage::getModel('customer/customer');
foreach(){
$customer_data = $customer_obj->load(customer_id);
$customer_data->getFirstname();
$customer_data->getEmail();
........
}

Code sample # 2
$customer_obj = Mage::getModel('customer/customer');
foreach(){
$customer_obj->load(customer_id)->getFirstname();
$customer_obj->load(customer_id)->getEmail();
.........
}

The loop count will be something around 1800-2000 every day.It is one time cron job every day
I am assuming it in this way,
in sample # 1 $customer_data will have the entire customer details in memory and from there on wards it will fetch it from memory.but in sample # 2 it always hit db with every load call
Can someone please enlighten me?

A: I think it is better to use the collection method of magento, and then only load the attributes you need:
$collection = Mage::getModel("customer/customer")->getCollection()->addAttributeToSelect('firstname','email');

Then loop with a foreach through this collection.

A: For your question:
code sample 1 is better, because it only does the load once for each customer.
code sample 2 does multiple loads per customer.
But as Patrick Steenks mentions, it is even much better to use a customer collection to do this, because then you only have ONE query for ALL customers :)


text:
Q: error CS0121: Problem with automapper when compile so mapper doesn't work in my project
services.AddAutoMapper();

error:

Startup.cs(112,21): error CS0121: The call is ambiguous between the following methods or properties: 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[])' and 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Type[])' [/Users/admin/Desktop/YP/youplay/server/YouPlay.Api/YouPlay.Api.csproj]

When i change to:
services.AddAutoMapper(typeof(Startup));

It's compile, but, when i trying to make req to
    public async Task<ActionResult<BetOpenForm>> CreateBetAsync([FromBody]CreateBetForm bet)
    {
        BetOpenForm response;
        try
        {

            BetOpen newBet = await _betService.CreateBetOpenAsync(bet);
           response = _mapper.Map<BetOpenForm>(newBet);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
           // return new BadRequestObjectResult(new ApiError("Something gone wrong ;("));
             return new BadRequestObjectResult(new ApiError(ex.Message));
        }

        return Ok(response);
    }

I getting:

Models:
using System;
using System.Collections.Generic;

namespace YouPlay.Api.Controllers.ViewModels.Bet
{
    public class BetOpenForm
    {
        public string Id { get; set; }
        public int StreamId { get; set; }
        public List<BetOptionForm> BetOptions { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public string AuthorId { get; set; }
    }
}

using System;

namespace YouPlay.Api.Controllers.ViewModels.Bet
{
    public class BetOptionForm
    {
        public string Id { get; set; }
        public string BetOpenId { get; set; }
        public string OptionText { get; set; }
        public double Odd { get; set; }
        public decimal Amount { get; set; }
        public int BetsCount { get; set; }
    }
}

A: Use this:
services.AddAutoMapper(typeof(Startup).Assembly);


text:
Q: Is there a way to automatically keep Chrome/Ask Tool Bar from installing? So of lately, I've had to warn my users to watch out for unwanted programs that are coming in with Adobe Flash and Java updates.  Adobe seems to be pushing Google's Chrome and Java with the Ask.com Toolbar.  I admit that it could be much worse because both instance simply require an uncheck during some point of the update process, but on a large scale, prevention is better than confrontation.
Any suggestions?

A: If you download from those sites, there is no way to stop them from asking you to install their ware. You will have to refuse every time.

A: The answer is Group Policy, but as with all security it's a fine line between usability and security. For the Ask toolbar you can simply disable add-ons in IE (provided it's v6 or above) by doing the following (from KB883256):

*

*Click Start, click Run, type gpedit.msc, and then click OK.

*Go to Computer Configuration (or User Configuration) → Administrative Templates → Windows Components → Internet Explorer → Security Features, and then click Add-on Management.

As for Chrome, you have a bazillion options in Group Policy to prevent installs, or run-times, or simply change users to non-admins. Sadly not too easy on this one.
Took me a bit to figure out how my users (small base) kept getting the Ask toolbar and Chrome (I don't mind the latter as long as it doesn't add toolbars, change search options, or homepage in IE).

A: Ask toolbar is often bundled with java. And Oracle company do this nasty thing, which really sucks. There is a ask toolbar petition on https://www.change.org/petitions/oracle-corporation-stop-bundling-ask-toolbar-with-the-java-installer, sign the petition and aks oracle stop bundling.
My laptop get this nasty toolbar last week, and i have to search a lot to remove it completely. Finally removed it with the help of a ask toolbar removal guide: http://www.virus-delete.com/en/guides/browser-hijacker-removal/20130814-how-to-remove-ask-search-toolbar-through-isafe-virus-removal-tool.html.
But is it possible to punish Oracle for its nasty deeds?

A: Unfortunately, you need to deal with this on a host-software-by-host-software or piggybacking-by-piggybacking-sofware basis.
The most frequent complaints I hear, is the Ask Toolbar bundled with Java.
To disable the installation of bundled software with the Java installer/updater, see this Q&A: How can I prevent Ask.com Toolbar from being installed every time Java is updated?


text: Q: Fourier transform trick in solving Legendre's differential equation Differential equations can often be solved by the method of Fourier transform. I have a particular equation in mind that appears very often in physical applications which is the Legendre differential equation: $$(1-x^2)y^{\prime\prime}-2xy^{\prime}+l(l+1)y=0.$$ I know that this can be solved by the method of series solution. But does the Fourier transform trick work here? If not why?


text:
Q: Can Samba 3 still be used? I am struggling with a trust relationship issue between a windows 7 machine and my companies samba 3 domain controller. The issue is only arising when I try to add a domain user to my machine for admin permissions. I have adjusted the machines registry as per https://wiki.samba.org/index.php/Required_settings_for_NT4-style_domains under windows 7. The machine joins the domain just fine, but when I go to add a domain user to the machine I get "The user could not be added because the following error has occured: The trust relationship between this workstation and the primary domain failed."
Things we've tried:
leaving and rejoining the domain,
reseting the workstation to factory settings and starting over (regedit first).
I've tried to find the answer to this issue and everything I've come across is fixed by leaving and rejoining the domain.
I am realtively new to this field so I apologize if I've missed vital information or reports I should be including; if so please ask me for whatever it is and I'll do my best to provide it.
Thank you.

A: Welcome to the club. Getting domain joins to work can be a black art, sometimes...
Samba needs an OS-level user for the machine, too. This user needs to have the format name$, where name is the machine name which you're trying to join, and $ is exactly that -- a dollar sign. If you use winbindd this happens automatically, but if you don't then you need to create that username yourself (e.g., by adding it to /etc/passwd).
Check if that user exists: run getent passwd machine$. If it doesn't, add it, or check if winbindd is working properly.
Apart from at the OS level, samba also needs to have the machine account in its own accounts database. In theory it should be possible for samba to add this on the fly when the join is attempted; but I find that in practice, it's more likely to work if you create them manually beforehand:
smbpasswd -m -a machine

Note: smbpasswd wants the machine name without the trailing $-sign (just to keep things interesting, I guess). The -m tells smbpasswd that you're dealing with a machine account; the -a tells it that you want it added to the database.
If all that doesn't help, play with the log level parameter in your smb.conf and look closely at the logs (post them if you can't figure it out)


text:
Q: cant select the tab drag n sortabke in t he link http://demoqa.com/draggable/ (none of the tabs there) I tried using all known element identifier to select the tabs in the drag n drop options in the link but constantly giving error object cant be located .
can anyone help me.
public class DragnDrop {

public static void main(String[] args) throws InterruptedException  {
    System.setProperty("webdriver.gecko.driver", "D:\\Auto\\geckodriver-v0.11.1-win32\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.get("http://demoqa.com");
    driver.findElement(By.xpath(".//*[@id='menu-item-140']/a")).click();
    Actions builder = new Actions(driver);
    WebElement know = driver.findElement(By.xpath(".//*[@id='tabs']/ul"));
    builder.moveToElement(know, 10, 10 ).click().build().perform();

i tried to even use action to click at particular location none worked

A: As far as I can see, if it's the "Draggable + Sortable" tab you're trying to click, the below should allow that:
WebElement draggableTab = driver.findElement(By.id("ui-id-5"));
draggableTab.click();

I've tried the above (using C#) and it worked fine.

A: public class DragDrop {
public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    System.setProperty("webdriver.gecko.driver",
            System.getProperty("user.dir") + "\\src\\Browser_Driver\\geckodriver.exe");

    WebDriver driver = new FirefoxDriver();
    driver.get("http://demoqa.com");
    driver.findElement(By.xpath(".//*[@id='menu-item-140']/a")).click();

    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(), 'Draggable + Sortable')]")));

    driver.findElement(By.xpath("//a[contains(text(), 'Draggable + Sortable')]")).click();

A: // code works perfectly for demoqa site

Actions builder = new Actions(driver);
    List<WebElement> list = driver.findElements(By.cssSelector("#sortablebox li"));
    WebElement source = driver.findElement(By.id("draggablebox"));
    WebElement dest1 = list.get(1);
    WebElement dest2 = list.get(4);
    builder.click(source).clickAndHold().moveToElement(dest1).moveByOffset(0, 10).release().build().perform();
    Thread.sleep(2000);
    builder.click(source).clickAndHold().moveToElement(dest2).moveByOffset(0, 10).release().build().perform();


text:
Q: libGDX getColor() method I have a grid of buttons, displayed on a stage. Setting and getting the color of the buttons is behaving strangely.
int X=0;
int Y=0;
buttons[X][Y].setColor(Color.BLUE);  //this works, the button displays blue
boolean test = (buttons[X][Y].getColor()==Color.BLUE);
System.out.println(test);  //prints 'false' , why???
System.out.println(buttons[X][Y].getColor()); //prints '0000ffff'
System.out.println(Color.BLUE); //prints '0000ffff'

I need to be able to set and get the color of the buttons for the game I'm creating. Does anyone know what is going on and what I could do?

A: The Color objects are different, but they have the same value.  So, the objects may not be == equal but will be .equal() equal.  See What is the difference between == vs equals() in Java?


text:
Q: KARATE: Should setting an XML body with an updated payload overwrite an existing one with the same name? I have created a reusable feature with the goal of taking in a payload as an argument and sending a request containing the received payload.
I have a predefined xml, envelope, I use for the request. The problem I'm seeing is when I set the payload into the body of the envelope and print out the request, it includes the self-closing tag from the envelope along with the payload I pass in. My intention is to replace the self-closing tag with the tag I am passing in. The self-closing tag is only there for situations in which no argument is supplied, since it is necessary for the request to be valid.
The predefined XML, or envelope, looks like this:
<ser:getDefaultConfig>
   <DefaultConfigRequest/>
</ser:getDefaultConfig>

The reusable looks like this:
@Reusable
Feature: Get Default Config

  Background:
    Given url baseUrl + '/DataInterface'
    And xml params = __arg

  Scenario: Get Default Config - getDefaultConfig
    Given set envelope /Envelope/Body = read('classpath:path/to/envelope.xml')
    And set envelope /Envelope/Body/getDefaultConfig = params
    And request envelope
    And header Content-Type = 'application/soap+xml; charset=utf-8'
    When method post
    Then def result = response

And the calling feature looks like this:
Feature: Default Config Integration Test

    Background:
    Given url baseUrl
    And copy envelope = read('classpath:path/to/envelope.xml')
    And copy expectedConfig = defaultConfig

  Scenario: Validate config details optional start and end times
    Given def expectedTimes =
    """
    {
      DefaultConfigRequest:{
        'fromTime': #(fromTime),
        'toTime': #(toTime)
      }
    }
    """

    When def actualFareDetails = call read('classpath:path/to/reusable.feature') expectedTimes
    Then match actualDetails.responseStatus == 200
    And match actualDetails.defaultConfig == expectedDetails

The request looks like this:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://ser">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:getDefaultConfig>
         <DefaultConfigRequest/>
         <DefaultConfigRequest>
            <fromTime>1970-01-01T00:00:00.000-07:00</fromTime>
            <toTime>2037-12-31T23:59:00.000-07:00</toTime>
         </DefaultConfigRequest>
      </ser:getDefaultConfig>
   </soapenv:Body>
</soapenv:Envelope>

but it should not include the self closing <DefaultConfigRequest/> tag on the 5th line. I can get rid of it if I remove it from the envelope, but then I have to add some conditional logic to check for a null argument and add it to the request when necessary.
The issue seems to be that it doesn't overwrite the existing tag even when it is set at the same level. Even if I append the tag to the set line in the reusable
And set envelope /Envelope/Body/getDefaultConfig/DefaultConfigRequest = params

karate nests the argument within that tag.
The other thing that is bugging me is I have to wrap both fromTime and toTime into a parent element DefaultConfigRequest in my payload, or else the reusable only sends the first one, fromTime.
I'm wondering if anyone has come across this and if this expected behavior? Is there something I'm missing? My coworker and I spent a lot of time experimenting with this and could not come up with a better solution than the one I described above.


text:
Q: Affecting a current install with a Live-CD after current install breaks Long story short, battery failed me while in a 15.10 to 16.04 upgrade. Now, I'm stuck with Lubuntu telling me the Light Daemon is lying.
I have my 15.10 CD with me, and was wondering if there's a way to use this to repair or continue the upgrade.
It has access to my files at least.
=========
Update:
I tried Live CD Recovery - Update Failure but I can't seem to log in to TTY1. The console says it's still a 15.10, but doing the steps on the Terminal says it's Xenial(16.04) now. Other people's problems don't seem to match mine, since it either requests a reboot (for a live cd?) and the /etc/passwd has my username on it. And yes, I've tried both my username and real name.
Further more, doing apt update or apt-get update gets me failed fetches saying
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

... which which led me to do apt-get -f install after.
It seemed like there was progress, but I'm still getting failed fetches, saying Temporary failure resolving 'archive.ubuntu.com'

A: I have no real explanation how and why, but the steps described above was enough to fix it. The instructions in Live CD Recovery were enough, somehow. But use the Terminal (Ctrl-Alt-T) if you can't log in.

*

*Boot the Ubuntu Live CD.

*Press Ctrl-Alt-F1 (Or Ctrl-Alt-T if you can't log in)

*sudo mount /dev/sda1 /mnt

*sudo mount --bind /dev /mnt/dev

*sudo mount --bind /proc /mnt/proc

*sudo mount --bind /sys /mnt/sys

*sudo chroot /mnt

*apt update (and follow suggestions when errors occur)

*apt upgrade (and follow suggestions when errors occur)
It won't look like much happened, and you still have to continue your update, but it was enough to get back to the regular install.


text:
Q: How to efficiently bucket pandas data frames and then perform groupby operations on those buckets? I want to bucket volumes and build up a summary report over the aggregate data via those buckets. Currently I use apply to do this, but apply can be very slow for large data sets. Is there a generic form of the syntax given in create_lt_ten_buckets? I'm guessing this is more of a numpy thing, with which I am less familiar.
def create_buckets(df_internal, comparison_operator, column_to_bucket, min_value, max_value, ranges_pivots):
    low = [min_value] + ranges_pivots
    high = ranges_pivots + [max_value]
    ranges = list(zip(low, high))
    max_str_len = len(str(max(high + low)))
    def get_value(row):
        count = 0
        for l,h in ranges:
            if comparison_operator(l, row[column_to_bucket]) and comparison_operator(row[column_to_bucket], h):
                return "{}|{}_to_{}".format(str(count).zfill(max_str_len),l,h)
            count+=1
        return "OUTOFBAND"
    df_internal["{}_BUCKETED".format(column_to_bucket)] = df_internal.apply(get_value, axis=1)

def create_lt_ten_bucket(df_internal, column_to_bucket):
    df_internal["{}_is_lt_ten".format(column_to_bucket)] = df_internal[column_to_bucket] < 10

dftest = pd.DataFrame([1,2,3,4,5, 44, 250, 22], columns=["value_alpha"])
create_buckets(dftest, lambda v1,v2: v1 <= v2, "value_alpha", 0, 999, [1, 2, 5, 10, 25, 50, 100, 200])
display(dftest)

create_lt_ten_bucket(dftest, "value_alpha")
display(dftest)

dftest.groupby('value_alpha_BUCKETED').sum().sort_values('value_alpha_BUCKETED')

OUTPUT
value_alpha value_alpha_BUCKETED
0   1   000|0_to_1
1   2   001|1_to_2
2   3   002|2_to_5
3   4   002|2_to_5
4   5   002|2_to_5
5   44  005|25_to_50
6   250 008|200_to_999
7   22  004|10_to_25

dftest = pd.DataFrame([1,2,3,4,5, 44, 250, 22], columns=["value_alpha"])
create_buckets(dftest, lambda v1,v2: v1 <= v2, "value_alpha", 0, 999999999, [1, 2, 5, 10, 25, 50, 100, 200])
display(dftest)

create_lt_ten_bucket(dftest, "value_alpha")
display(dftest)

OUTPUT
value_alpha value_alpha_BUCKETED    value_alpha_is_lt_ten
0   1   000|0_to_1  True
1   2   001|1_to_2  True
2   3   002|2_to_5  True
3   4   002|2_to_5  True
4   5   002|2_to_5  True
5   44  005|25_to_50    False
6   250 008|200_to_999  False
7   22  004|10_to_25    False

In the end I'm trying to get a summary of the data similar to this:
dftest.groupby('value_alpha_BUCKETED').sum().sort_values('value_alpha_BUCKETED')
    value_alpha value_alpha_is_lt_ten
value_alpha_BUCKETED
000|0_to_1  1   1.0
001|1_to_2  2   1.0
002|2_to_5  12  3.0
004|10_to_25    22  0.0
005|25_to_50    44  0.0
008|200_to_999  250 0.0

A: I'm not entirely clear on what you're asking, but what you have is roughly pd.cut and pd.DataFrame.groupby:
dftest['new_bucket'] = pd.cut(dftest['value_alpha'], [0, 1, 2, 5, 10, 25, 50, 100, 200, 999])
dftest['value_alpha_is_lt_ten'] = dftest['value_alpha'] < 10
print(dftest.groupby("new_bucket").sum())

            value_alpha  value_alpha_is_lt_ten
new_bucket
(0, 1]                1                    1.0
(1, 2]                2                    1.0
(2, 5]               12                    3.0
(5, 10]               0                    0.0
(10, 25]             22                    0.0
(25, 50]             44                    0.0
(50, 100]             0                    0.0
(100, 200]            0                    0.0
(200, 999]          250                    0.0

If you don't want the empty buckets, you could .query on values where value_alpha > 0


text:
Q: Faster input and output #include<iostream>
using namespace std;
int main(){
    int i,x,max=0;
    cin>>x;
    int a[x];
    for(i=0;i<x;i++){
        cin>>a[i];
        if(max<a[i]){
            max=a[i];}
        }
        int b[max+1];
        for(i=0;i<max+1;i++){
            b[i]=-1;
        }
        for(i=0;i<x;i++){
            if(b[a[i]]==-1){
            b[a[i]]=1;
        }
        else{
            b[a[i]]++;
        }
    }
    i=0;
    while(i<=max){
        while(b[i]>0&&b[i]!=-1){
            cout<<i<<endl;
            b[i]--;
        }
        i++;
    }
    return 0;
}

Guys I tried indexing method for sorting and codechef shows tle .. complexity of this problem is not o(n) but closer to it ... the question has a time limit of 5 sec and source limit is 50000 bytes..
Any help on how to improve the performance either by faster i/o or code computations ...

A: I'm pretty certain your code is problematic because you are using cout << x << endl; in a loop that will print a huge number of lines.
I will be back with "difference" in a few minutes.
Edit: Not sure I can make much of a difference either way. Obviously, depending on compiler, it may vary greatly, but with my g++ -O2 and 100000 input numbers, it takes 0.16 - 0.18s to use endl; and 0.06 - 0.07s to use '\n' for the output.
Using printf isn't faster than cout, but scanf is a little faster than cin (0.04s +/- 0.05).
However, that is really related to sync_with_stdio. If we use cin.sync_with_stdio(false); then the results are the same for scanf and cin.
All measurements are made with a file as input and a file as output - it takes much longer to write to the shell, but that's because it's scrolling 100k lines of text past me.
(Your program will crash with eithr "large" inputs or with large number of inputs - if max is greater than about 1 million, the code will crash due to out of stack - on many systems, that may happen for lower values too)

A: Avoid cin and cout, and use the C IO functions scanf and printf instead. You'll find they can be up to 5x faster than the slow c++ functions.


text:
Q: How to Compare 2 Dates and subtract 1 second if it's true I want to Compare The date which is manually inputted by the user to the Specific date which is 12:00AM, after that i want to subtract 1 second on the 1st date
var d1 = $('#d1').val();
var d11 = new Date(d1);
var d12 = new Date();
d12.setHours(0,0,0,0);
   if(d11.getTime() === d12.getTime()){
       var seconds = d11.getSeconds() - 1;
       d11 = d11 - seconds;
   }

I expect output is 23:59:59 but the actual input is error

A: You can achieve this in several ways. But not the way you tried. Issue is you can
not perform integer operations on Date type as you have tried here.
You can go along something similar to below.
var t = new Date();
t.setSeconds(t.getSeconds() - 1);

or
new Date(Date.now() - 1000);

here 1000 is in milliseconds.


text:
Q: Data modeling with levels of detail, some of which are absent I'm doing a data model for a roller derby league to track their matches. I track things like lap times, penalties per lap, penalties per period, and penalties per match.
The problem is that in some cases, I will only have the overall data; I might have "penalties per match" for one match and "penalties per period" for another. So at the lowest level, for some matches, I'll have the very detailed data (penalties per hap), and at the highest level I'll have penalties per match.
I'm not sure how to model/use this to do reporting when I don't have a high detail for some records. I thought about something like this:
PenaltiesPerMatch
MatchID
PenaltyCount
PenaltiesPerPeriod
MatchID
PeriodID
PenaltyCount
PenaltiesPerLap
MatchID
PeriodID
LapID
PenaltyCount
But my concern is that the higher-level information can be derived from lower level. Do I duplicate records (e.g. fill in a record for penalties per period with data that is also in penalties per lap, summed by period?) or keep unique records (don't put in penalties per period for data that I have already in penalties per lap; calculate it by summing on period).

A: What I would do is record the information that you have.  For some matches, record it in high detail, for others in low detail.
When you report on the matches:

*

*Calculate the sums per match for the high detail matches

*Use the sum per match from the low detail matches

Store data at the lowest detail level that you have; calculate the higher detail levels.

A: You could save the information in one table, with NULL values indicating that you don't have the data down to that level. You wouldn't be able to put a primary key over that, so you would need a surrogate key, but you should be able to use a unique constraint.
For example:
CREATE TABLE PenaltyCounts
(
    penalty_count_id INT NOT NULL,
    match_id         INT NOT NULL,
    period           TINYINT NULL CHECK (period BETWEEN 1 AND 3),
    lap              SMALLINT NULL,
    penalty_count    SMALLINT NOT NULL,
    CONSTRAINT PK_PenaltyCounts PRIMARY KEY NONCLUSTERED (penalty_count_id),
    CONSTRAINT UI_PenaltyCounts UNIQUE CLUSTERED (match_id, period, lap),
    CONSTRAINT CK_lap_needs_period CHECK (lap IS NULL OR period IS NOT NULL)
)

One problem with this for which I don't see an easy solution yet is how to enforce that they ONLY can enter penalties at one level. For example, they could still do this:
INSERT INTO PenaltyCounts (penalty_count_id, match_id, period, lap, penalty_count)
VALUES (1, 1, NULL, NULL, 5)
INSERT INTO PenaltyCounts (penalty_count_id, match_id, period, lap, penalty_count)
VALUES (2, 1, 1, NULL, 3)
INSERT INTO PenaltyCounts (penalty_count_id, match_id, period, lap, penalty_count)
VALUES (3, 1, 2, NULL, 2)

The advantage of this single-table solution is that your statistics can all be found by querying one table and the GROUP BYs will roll everything up nicely.
You could also use the separate table method but put views over them to pull everything together. This still allows the problem above though of putting numbers in at multiple levels.

A: I think it depends on what information is valuable to the customer. If they would like to have the information by period, then you should include that as a separate record. Penalty by period and by match must be separated.
I you always had the penalty by period information, then you could do a query that sums the data.
If your periods is always a fixed number, then you could probably just do two columns in the table instead of a new table to hold the period information


text:
Q: How can I create a customized colormap for geoviews (bokeh)? I'm trying to plot an xarray dataset in Geoviews, like this:
https://geoviews.org/gallery/bokeh/xarray_image.html#bokeh-gallery-xarray-image
There I can define a colormap by cmap.
The cmap is just a list of hex-codes, like:
['#150b00',
'#9b4e00',
'#f07800',
'#ffa448',
'#a8a800',
'#dddd00',
'#ffff00',
'#ffffb3',
'#ffffff',
'#b0ffff',
'#00e8e8',
'#00bfbf',
'#008a8a',
'#79bcff',
'#0683ff',
'#0000c1',
'#000048']
I want to define to levels of values for these color, like this list:
[-10.0,
-5.0,
-2.5,
-1.0,
-0.5,
-0.2,
-0.1,
-0.05,
0.05,
0.1,
0.2,
0.5,
1.0,
2.5,
5.0,
10.0]
How can I define these levels?

A: Please try to set the parameter color_levels to the wanted values. This is explained in HoloViews Styling Plots in the section Custom color intervals. HoloVies is the source where the gv.Image comes from. Therefore this should work.
cmap = ['#150b00', '#9b4e00', '#f07800', '#ffa448', '#a8a800', '#dddd00', '#ffff00', '#ffffb3', '#ffffff', '#b0ffff', '#00e8e8', '#00bfbf', '#008a8a', '#79bcff', '#0683ff', '#0000c1', '#000048']
levels = [-10.0, -5.0, -2.5, -1.0, -0.5, -0.2, -0.1, -0.05, 0.05, 0.1, 0.2, 0.5, 1.0, 2.5, 5.0, 10.0]

images.opts(
    cmap=cmap,
    color_levels=levels,
    colorbar=True,
    width=600,
    height=500) * gf.coastline

Comment
If this is not working, then I apologize. In the moment I am not able to install GeoViews on my machine.


text:
Q: How do I expose my own Elixir websocket using WebSockex I see the basic example for Elixir's WebSockex library here but it doesn't really explain how I can expose my own websocket to the internet. This question has answers which explain how to chat to an existing websocket externally, but I want to expose my own websocket. I'm actually using websockex as part of a Phoenix application, so perhaps bits of Phoenix might help here?
I obviously know the ip:port combo of my phoenix application so given these, how do I expose a websockex websocket on that ip:port? In other words, what should I pass as the URL? in this basic example code:
defmodule WebSocketExample do
  use WebSockex

  def start_link(url, state) do
    WebSockex.start_link(url, __MODULE__, state)
  end

  def handle_frame({type, msg}, state) do
    IO.puts "Received Message - Type: #{inspect type} -- Message: #{inspect msg}"
    {:ok, state}
  end

  def handle_cast({:send, {type, msg} = frame}, state) do
    IO.puts "Sending #{type} frame with payload: #{msg}"
    {:reply, frame, state}
  end
end

Please note that I need to expose a raw websocket, not a Phoenix channel, as the consumer doesn't understand Phoenix channels. If Phoenix can expose a raw websocket then I'll consider that a solution too.
If neither Phoenix nor WebSockex can help, what are my options?

A: Websockex is a client library, I don't think it has any code for exposing a websocket. Since you're already using phoenix, you probably can do what you need with phoenix channels.
If you're on cowboy (and you probably are, since it's the default), then you can also use it to expose a raw websocket. However, it requires some fiddling with routing. You will need to replace YourAppWeb.Endpoint with a manual configuration of cowboy:
{
  Plug.Cowboy,
  scheme: :http,
  plug: YourAppWeb.Endpoint,
  options: endpoint_options(),
  dispatch: [
    _: [
      # Dispatch paths beginning with /ws to a websocket handler
      {"/ws/[...]", YourApp.WebsocketHandler, []},
      # Dispatch other paths to the phoenix endpoint
      {:_, Plug.Cowboy.Handler, {YourAppWeb.Endpoint, endpoint_options()}}
    ]
  ]
}

I have honestly only done this with raw plug, so you might need to convert the endpoint to be a Plug instead of a Phoenix.Endpoint. Then, you need to implement YourApp.WebsocketHandler to conform to cowboy's API and perform a websocket upgrade (and handle sending/receiving messages), as described in cowboy docs. You can also see this gist for a more fleshed-out example.

A: WebSockex implements many callbacks, including, but not limited to WebSockex.handle_connect/2. It holds WebSockex.Conn in a state and passes it to all callbacks.
WebSockex.Conn is a plain old good struct, having socket field.
So from any callback (I'd do it from WebSockex.handle_connect/2) you might share this socket with the process which needs it and use it then from there.

Also, you can borrow some internals and check how the connection is being created.
You'll see it uses WebSockex.Conn.new/2 that returns an initialized connection, that, in turn, holds a socket. In that case, you'll be obliged to supervise the process that holds the socket manually.

The power of OSS is all answers are one mouse click far from questions.


text:
Q: Packet sending script, iOS 9.1 I have an app which sends specific packets to a server every time I press a particular button on the app, the problem is that I need to press it every 30 seconds during a few hours and it's annoying. Is there any way to script it so that the packets are automatically sent every 30 seconds to the server?
I thought about a macro tool but it's not possible since I can't jailbreak.
Any ideas on how to approach to a solution?

A: Solved! This might be really helpful for those with the same issue, follow these steps:

*

*Download and install Burp Suite Free Edition in your PC/Mac

*Go to Proxy->Options and edit the *.8080 interface to "All interfaces" in "Bind to address"

*Go to your iPhone/Tablet/Whatever and connect it to the same Wi-Fi network your PC is connected to, set up a manual proxy to your PC's IP on port 8080.

*In Burp Suite go to Proxy->HTTP History and press the button in your cellphone that sends the request you want to automate.

*Compile a script in C# that sends a HTTP request with the same method, parameters and headers.

*Make it loop :)

Now your PC will send the packets to the host and you can even simulate it was sent from iOS using the parameters you just coppied, it also wont drain your phone's battery at all.


text:
Q: How to Write UTF-8 in Mifae Card I try to make Member Membership Management Program using MifareCard & NFC Reader.
In this code, English is normally, but other languages are broken.
Like this
Write Data to Card  "北京",    read wrote Data  "yyyy"
Write Data to Card  "서울",    read wrote Data  "yyyy"
Write Data to Card  "さくら",  read wrote Data "yyyyyy"
How can I use UTF8 Encoding for Write Data in to MifareCard?
Main.CS
#region Write_Data
private void Button_Click_2(object sender, RoutedEventArgs e)
{
    if (connectCard())// establish connection to the card: you've declared this from previous post
    {
        byte[] bytes = Encoding.Default.GetBytes(textBox2.Text);
        String insert_Value = Encoding.UTF8.GetString(bytes);
        submitText(insert_Value, Combo_W.Text); // 5 - is the block we are writing data on the card
        Close();
    }
}

//submit data method
public void submitText(String Text, String Block)
{

    String tmpStr = Text;
    int indx;
    if (authenticateBlock(Block))
    {
        ClearBuffers();
        SendBuff[0] = 0xFF;                             // CLA
        SendBuff[1] = 0xD6;                             // INS
        SendBuff[2] = 0x00;                             // P1
        SendBuff[3] = (byte)int.Parse(Block);           // P2 : Starting Block No.
        SendBuff[4] = (byte)int.Parse("16");            // P3 : Data length

        for (indx = 0; indx <= (tmpStr).Length - 1; indx++)
        {
            SendBuff[indx + 5] = (byte)tmpStr[indx];
        }
        SendLen = SendBuff[4] + 5;
        RecvLen = 0x02;

        retCode = SendAPDUandDisplay(2);

        if (retCode != Card.SCARD_S_SUCCESS)
        {
            MessageBox.Show("fail write");

        }
        else
        {
            MessageBox.Show("write success");
        }
    }
    else
    {
        MessageBox.Show("FailAuthentication");
    }
}

// block authentication
private bool authenticateBlock(String block)
{
    ClearBuffers();
    SendBuff[0] = 0xFF;                         // CLA
    SendBuff[2] = 0x00;                         // P1: same for all source types
    SendBuff[1] = 0x86;                         // INS: for stored key input
    SendBuff[3] = 0x00;                         // P2 : Memory location;  P2: for stored key input
    SendBuff[4] = 0x05;                         // P3: for stored key input
    SendBuff[5] = 0x01;                         // Byte 1: version number
    SendBuff[6] = 0x00;                         // Byte 2
    SendBuff[7] = (byte)int.Parse(block);       // Byte 3: sectore no. for stored key input
    SendBuff[8] = 0x60;                         // Byte 4 : Key A for stored key input
    SendBuff[9] = (byte)int.Parse("1");         // Byte 5 : Session key for non-volatile memory

    SendLen = 0x0A;
    RecvLen = 0x02;

    retCode = SendAPDUandDisplay(0);

    if (retCode != Card.SCARD_S_SUCCESS)
    {
        //MessageBox.Show("FAIL Authentication!");
        return false;
    }

    return true;
}

// clear memory buffers
private void ClearBuffers()
{
    long indx;

    for (indx = 0; indx <= 262; indx++)
    {
        RecvBuff[indx] = 0;
        SendBuff[indx] = 0;
    }
}

// send application protocol data unit : communication unit between a smart card reader and a smart card
private int SendAPDUandDisplay(int reqType)
{
    int indx;
    string tmpStr = "";

    pioSendRequest.dwProtocol = Aprotocol;
    pioSendRequest.cbPciLength = 8;

    //Display Apdu In
    for (indx = 0; indx <= SendLen - 1; indx++)
    {
        tmpStr = tmpStr + " " + string.Format("{0:X2}", SendBuff[indx]);
    }

    retCode = Card.SCardTransmit(hCard, ref pioSendRequest, ref SendBuff[0],
                         SendLen, ref pioSendRequest, ref RecvBuff[0], ref RecvLen);

    if (retCode != Card.SCARD_S_SUCCESS)
    {
        return retCode;
    }

    else
    {
        try
        {
            tmpStr = "";
            switch (reqType)
            {
                case 0:
                    for (indx = (RecvLen - 2); indx <= (RecvLen - 1); indx++)
                    {
                        tmpStr = tmpStr + " " + string.Format("{0:X2}", RecvBuff[indx]);
                    }

                    if ((tmpStr).Trim() != "90 00")
                    {
                        //MessageBox.Show("Return bytes are not acceptable.");
                        return -202;
                    }

                    break;

                case 1:

                    for (indx = (RecvLen - 2); indx <= (RecvLen - 1); indx++)
                    {
                        tmpStr = tmpStr + string.Format("{0:X2}", RecvBuff[indx]);
                    }

                    if (tmpStr.Trim() != "90 00")
                    {
                        tmpStr = tmpStr + " " + string.Format("{0:X2}", RecvBuff[indx]);
                    }

                    else
                    {
                        tmpStr = "ATR : ";
                        for (indx = 0; indx <= (RecvLen - 3); indx++)
                        {
                            tmpStr = tmpStr + " " + string.Format("{0:X2}", RecvBuff[indx]);
                        }
                    }

                    break;

                case 2:

                    for (indx = 0; indx <= (RecvLen - 1); indx++)
                    {
                        tmpStr = tmpStr + " " + string.Format("{0:X2}", RecvBuff[indx]);
                    }

                    break;
            }
        }
        catch (IndexOutOfRangeException)
        {
            return -200;
        }
    }
    return retCode;
}

//disconnect card reader connection
public void Close()
{
    if (connActive)
    {
        retCode = Card.SCardDisconnect(hCard, Card.SCARD_UNPOWER_CARD);
    }
    //retCode = Card.SCardReleaseContext(hCard);
}
#endregion

#region Read_Data
private void Button_Click_1(object sender, RoutedEventArgs e)
{
    string text = verifyCard(Combo_R.Text); // 5 - is the block we are reading
    byte[] bytes = Encoding.Default.GetBytes(text);
    textBox1.Text = Encoding.UTF8.GetString(bytes);
}

public string verifyCard(String Block)
{
    string value = "";
    if (connectCard())
    {
        value = readBlock(Block);
    }

    value = value.Split(new char[] { '\0' }, 2, StringSplitOptions.None)[0].ToString();
    return value;
}

public string readBlock(String Block)
{
    string tmpStr = "";
    int indx;

    if (authenticateBlock(Block))
    {
        ClearBuffers();
        SendBuff[0] = 0xFF; // CLA
        SendBuff[1] = 0xB0;// INS
        SendBuff[2] = 0x00;// P1
        SendBuff[3] = (byte)int.Parse(Block);// P2 : Block No.
        SendBuff[4] = (byte)int.Parse("16");// Le

        SendLen = 5;
        RecvLen = SendBuff[4] + 2;

        retCode = SendAPDUandDisplay(2);

        if (retCode == -200)
        {
            return "outofrangeexception";
        }

        if (retCode == -202)
        {
            return "BytesNotAcceptable";
        }

        if (retCode != Card.SCARD_S_SUCCESS)
        {
            return "FailRead";
        }

        // Display data in text format
        for (indx = 0; indx <= RecvLen - 1; indx++)
        {
            tmpStr = tmpStr + Convert.ToChar(RecvBuff[indx]);
        }

        return (tmpStr);
    }
    else
    {
        return "FailAuthentication";
    }
}
#endregion

A: You can convert a string from one encoding to another like this
byte[] bytes = Encoding.UTF8.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);

See the docs here.


text:
Q: Apache DEFLATE configuration I have VirtualHost definition in my Apache config file. In this definition I have implemented SetOutputFilter DEFLATE. My problem is that I need to exclude files from deflate which have size smaller then 10k.
When I try to use SetEnvIf Content-Length "^[0-9][0-9]?[0-9]?[0-9]?$" no-gzip function it doesnt work. Because of Content-Length of my request is exemined instade of response

A: It is possible to set some specific header in your request. Based on this header apache can decide to compress your page or not.
LoadModule deflate_module                 /modules/mod_deflate.so
LoadModule headers_module                 /modules/mod_headers.so

<IfModule mod_deflate.c>
    <IfModule mod_setenvif.c>
        BrowserMatch ^Mozilla/4 gzip-only-text/html
        BrowserMatch ^Mozilla/4\.0[678] no-gzip
        BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
        BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
    </IfModule>
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
    SetEnvIf DoCompress "^true" no-gzip dont-vary
    AddOutputFilterByType DEFLATE text/css application/x-javascript text/html
</IfModule>


text:
Q: Why can't I install more than one application at once? Why can't APT install more than one application at a time? Why does it need to exit before installing the next.  I know with MS Windows you can install how many application at once.  This problem is not unique to Ubuntu but to all distros, that I have notice.

A: That's because each package has specific details about how it can be installed.
Post-processing for a package sometimes has follow up (symlinking, documentation generation, et cetera). Such processing may pre-depend on other processes having completed.
This isn't a Linux flaw. It's a "computation" flaw. (https://en.wikipedia.org/wiki/Halting_problem).
No package manager can determine if it's successfully installed the dependencies shy of actually trying to install. Windows is not immune from this.

A: Both dpkg and RPM can handle more than one application install at a time. For instance:
sudo apt-get install firefox thunderbird

This command will install both Firefox and Thunderbird in the same command. More recent versions of apt-get will actually begin the downloads using potentially different sources as well.
yum, zypper, and dnf also handle multiple applications in the same way.

A: You can install more than one application at once by typing the following command in terminalsudo apt-get install <package-one> <package-one> ...
replace the latter by package names
It will install the packages sequentially not all at once but it will save you the trouble for waiting one installation to finish and the entering another to installation


text:
Q: Creating a hyperlink using apache poi I am trying to create a hyperlink using the following code
CreationHelper createHelper = wb.getCreationHelper();
cell.setCellValue("Click Here");
Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_FILE);

File f = new File("C:\\Test\\1.pdf");
link.setAddress(f.getCanonicalPath());
cell.setHyperlink((org.apache.poi.ss.usermodel.Hyperlink) link);

It works fine and it adds a link Click Here to the cell
But how i can set a partial text and a link using same type of code,  I mean the link need to be like your file is here, where only here is the link

A: As far as I know I don't think it is possible, as it is not supported by Excel as well. To achieve that in Excel too there is no straight way and you have to do some tricks to achieve that. Something that is not supported right from Excel cannot be supported by Apache POI too.


text:
Q: Is there a topological proof that additon and multiplication are continous functions from $\mathbb R \times \mathbb R $ into $\mathbb R $? Is there a topological proof that additon and multiplication are continous functions from $\mathbb R \times \mathbb R $ into $\mathbb R $? That is, can we prove continuity using the topological description of a continuous function?
I know that one can make a "$\epsilon $- $\delta $ argument, but this proof isn't so "elegant", and of course these two definitions are equivalent.
Thanks in advance!

A: Let $f: \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R}$ with $(x,y)\mapsto x+y$.
Given an open set $O\subset\mathbb{R}$, let $(a,b) \in f^{-1} (O)$. Then $a+b \in O$, since $O$ is open, there exists a ball centered at $a+b$ with radius $\epsilon$ such that
$$B_{a+b}(\epsilon) \subset O.$$
By construction
$$(a,b) \in B_a\left(\frac{\epsilon}{2}\right) \times B_b\left(\frac{\epsilon}{2}\right) \subset f^{-1}(B_{a+b}(\epsilon)) \subset f^{-1} (O),$$
thus $f^{-1} (O)$ is open.
Edit: the inclusion $B_a\left(\frac{\epsilon}{2}\right) \times B_b\left(\frac{\epsilon}{2}\right) \subset f^{-1}(B_{a+b}(\epsilon))$ is clear, but not trivial, you might want to write a short argument for this on a test.


text:
Q: set bin field in an array based on offset and length I want to develop a function in C that set a binary field in array starting from a given offset and finish with a given length.
For example, my binary array is:
01101011 10010101 11001011 11010001 11000101 00101011

the buffer used for set:
10011001 01011011 10100010

So if the offset = 5 and the length = 7, the result will be
we will set the 7 first bit from the set buffer (1001100) in the binary buffer starting from the offset 5:
01101100 11000101 11001011 11010001 11000101 00101011
     ^      ^
     |      |__End of set field (len=7)
   offset=5

Are there predefined algorithms for that? using bitwise operators?

A: Given char * arrays, you can easily implement operators set and get to set and retrieve, respectively, the i-th bit:
void set(char *a, int position, int value) {
     int byte = position >> 3;
     int bit = 1 << (position & 0x07); // 00000001b to 10000000b
     a[byte] = value ?
           a[byte] | bit :  // on
           a[byte] & ~bit;  // off
}

int get(char *a, int position) {
     return a[position>>3] & (1 << (position&0x07)) ? 1 : 0;
}

This can be made slightly faster with compiler intrinsics to get both division and modulus at the same time, and there is probably some bitwise trick to avoid branching in 'set' - but hopefully this code communicates the gist of the operation.
Implementing your desired function is essentially an extension of the code in my set function, where instead of only touching one bit, you continue until you run out of bits to modify, starting at the indicated offset.

Edit: adding a bitwise trick from this answer to remove branching from set:
void set(char *a, int position, int value) {
     int byte = position >> 3;
     int offset = position & 0x07);
     a[byte] = (a[byte] & ~(1<<offset)) | (value<<offset);
}

Note that this version requires value to be either 0 or 1; the previous version would work with any false or true (=zero vs. non-zero) value.


text:
Q: Mongoose doesn't save all the fields of my POST request I have a very simple "social network" app: users can register, write posts, like/unlike them and comment a post.
I have a probleme with my Post Schema :

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const PostSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "user",
  },
  text: {
    type: String,
    required: true,
  },
  name: {
    type: String,
  },
  avatar: {
    type: String,
  },
  likes: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: "user",
      },
    },
  ],
  comments: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: "user",
      },
    },
    {
      text: {
        type: String,
        required: true,
      },
    },
    {
      name: {
        type: String,
      },
    },
    {
      avatar: {
        type: String,
      },
    },
    {
      date: {
        type: Date,
        default: Date.now,
      },
    },
  ],
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = Profile = mongoose.model("post", PostSchema);

When I receive my POST request for comments...

// @route   POST api/posts/comment/:id
// @desc    Add comment to post
// @access  Private
router.post(
  "/comment/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const { errors, isValid } = validatePostInput(req.body);

    // Check Validation
    if (!isValid) {
      // If any errors, send 400 with errors object
      return res.status(400).json(errors);
    }

    Post.findById(req.params.id)
      .then(post => {
        const newComment = {
          text: req.body.text,
          name: req.body.name,
          avatar: req.body.avatar,
          user: req.user.id,
        };
        console.log("newComment: ", newComment);

        // Add to comments array
        post.comments.unshift(newComment);
        console.log("post: ", post.comments);

        // Save
        post.save().then(post => res.json(post));
      })
      .catch(err => res.status(404).json({ postnotfound: "No post found" }));
  },
);

The only fields that are saved in the post.comments array is the User. Not the other fields (text, name, avatar, date).
My console.log("newComment: ", newComment); properly returns the complete object with all its properties but then, 2 lines below, console.log("post: ", post.comments); only returns the comment _id and the user and those are the only fields saved in the DB...
What did I miss here?

A: There is some Problem in the creation of the schema structure, this is the correct way:
comments: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: "user",
      },
      text: {
        type: String,
        required: true,
      },
      name: {
        type: String,
      },
      avatar: {
        type: String,
      },
      date: {
        type: Date,
        default: Date.now,
      },
    }
  ]

the valid structure is nothing but like this(showing the changes made above):
comments: [{
  user: {},
  text: {},
  // others...
}]


text:
Q: How to setup an intermediate git server? And is it advisable? Current Situation
My team is based in Singapore. We needed to install a Django web app inside China for speed reasons for an enterprise client for intranet usage.

So we did it like this.
What's wrong?
The git clone is painfully slow and our files are > 50 mb.
What have you tried?
I am thinking of setting up an intermediate server in HongKong to reduce the latency for git clone.

Maybe the diagram is a bit off.
We used CircleCI. I think we can get CircleCI to have the following setup.

Whenever GitHub received an update on the master branch of our repo,
  the HongKong server will pull the latest master branch copy down.

For the China server, I guess I can configure it to do a git pull every day at some off peak hours using cronjob.
So what's your issue?
I can google for the git setup steps quite easily like this https://git-scm.com/book/en/v1/Git-on-the-Server-Setting-Up-the-Server
My concern is whether my approach described above makes sense.
If it makes sense, then my question is how do I configure the CircleCI to do
that?
Our team experience with CircleCi is limited to having it work with GitHub and Heroku. We never have used it with GitHub and a standalone server which we will operate on.

A: You can use a shallow clone in the China server to improve git clone's performance.
For example, if you want only the last version:
git clone --depth 1 <repository-url>

You say that your files are > 50 MB, so it will still take a bit to clone if there are many of them, but at least you only download them once.


text:
Q: How to use function inside for loop of another function into python I want to use function inside function but I get error
I want to get previous object,current object and next object how can I define that can anyone help me ?
Actually I am new into the programming
Thank you in advance
class DataHandler:
    def previous_and_next(some_iterable):
        prevs, items, nexts = tee(some_iterable, 3)
        prevs = chain([None], prevs)
        nexts = chain(islice(nexts, 1, None), [None])
        return zip(prevs, items, nexts)

    def current_obj(self):
        print("The current object is : ",employee_list[0])

    def next_obj(se):
        property = previous_and_next(employee_list)
        for previous, item, nxt in property:
            print("Item is now", item, "next is", nxt, "previous is", previous)

employee_list = []
n = int(input("Enter number of Employee you want to add:"))
for i in range(n):
    fname = input("Enter First name : ")
    lname = input("Enter Last name : ")
    emp_type = input("Enter Employee type : ")
    details = [fname,lname,emp_type]
    print(details)
    employee_list.append(details)

obj = DataHandler()
obj.current_obj()
obj.next_obj()

I am getting error at :
property = previous_and_next(employee_list)
NameError: name 'previous_and_next' is not defined

A: Your issue is that you are trying to access a method that belongs to an instance of a class. You need to use self:
def next_obj(self):
    property = self.previous_and_next(employee_list)
    for previous, item, nxt in property:
        print("Item is now", item, "next is", nxt, "previous is", previous)

You also need to do make the previous_and_next method take self as an argument, or make it a staticmethod:
def previous_and_next(self, some_iterable):

or
@staticmethod
def previous_and_next(some_iterable):

I'm not convinced that the rest of your code will actually achieve the intended result, but this should fix that error you have.

A: Well you can define function by self. Just add self in all functions and then you can use:
def previous_and_next(self,some_iterable):
        prevs, items, nexts = tee(some_iterable, 3)
        prevs = chain([None], prevs)
        nexts = chain(islice(nexts, 1, None), [None])
        return zip(prevs, items, nexts)

Property = self.previous_and_next(employee_list)


text:
Q: accessing StageWebView via ANE I'd like to write an ANE that can access the native part of a StageWebView (iOS's UIWebView/Android's WebView).  This is so that I can call native webview methods that StageWebView doesn't provide (e.g., accessing cookies).
I'd like to think this is possible, but I'm not sure how to get started.


text:
Q: Google Sheets API with Python I am attempting to connect to this Google Sheet:
https://docs.google.com/spreadsheets/d/1u3Ql_Rs19PEe0mwqpsiw2wf2cUEbnSG4vZL63rh_OaE/edit?usp=sharing
Both the .json file and the .py file are saved to my desktop.
The email in the .json has been shared with the Google Sheet
I am getting a 'JSONDecodeError: Expecting value' and cannot figure out why.
I have revised the client id and key info in the .json for pirvacy as I am new to this and was not sure if sharing this was wise
Any help is greatly appreciated. thank you
python:
import gspread

gc = gspread.service_account(filename = 'credentials.json')

sh = gc.open('User')

worksheet=sh.sheet1

res=worksheet.get_all_records()

print(res)

credentials.json:
{
  "type": "service_account",
  "project_id": "clear-heaven-331616",
  "private_key_id": "abcxyz",
  "private_key": "-----BEGIN PRIVATE KEY-----\abcxyz=\n-----END PRIVATE KEY-----\n",
  "client_email": "my-service-account@clear-heaven.iam.gserviceaccount.com",
  "client_id": "abcxyz",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/my-service-account%40clear-heaven-331616.iam.gserviceaccount.com"
}

traceback:
  File "C:\Users\dusti\Desktop\googlesheets.py", line 10, in <module>
    gc = gspread.service_account(filename = 'credentials.json')

  File "C:\Users\dusti\anaconda3\lib\site-packages\gspread\auth.py", line 196, in service_account
    creds = ServiceAccountCredentials.from_service_account_file(

  File "C:\Users\dusti\anaconda3\lib\site-packages\google\oauth2\service_account.py", line 238, in from_service_account_file
    info, signer = _service_account_info.from_filename(

  File "C:\Users\dusti\anaconda3\lib\site-packages\google\auth\_service_account_info.py", line 73, in from_filename
    data = json.load(json_file)

  File "C:\Users\dusti\anaconda3\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),

  File "C:\Users\dusti\anaconda3\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)

  File "C:\Users\dusti\anaconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())

  File "C:\Users\dusti\anaconda3\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value

A: First off I would double check that you created service account credentials on google cloud console.
Then I would consider using the Google-api-Python-client library this is googles official client library.
Then you should consider using from_json_keyfile_name
"""Hello Sheets API V4."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = ['https://www.googleapis.com/auth/drive']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'

def initialize_sheets():
  """Initializes an sheets API V4 service object.

  Returns:
    An authorized sheets API V4 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  sheets = build('sheets', 'v4', credentials=credentials)

  return sheets


text:
Q: Google Fit REST API - dataStreamId with whitespace results in error I want to use Google's REST API to get the Fitness data of my account. To do so i issue 2 subsequent calls.

*

*GET https://www.googleapis.com/fitness/v1/users/me/dataSources. This returns a list of all available dataSources as in [1].

*POST https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate.
I use the dataType name and dataStreamId in the request body from [1] to build the request body [2].
The problem: The second call returns an error [3] for all dataSourceIds that contain whitespace although they were returned exactly that way in the first request. In the code sample there is whitespace because the dataSourceId contains the phone model "Nexus 5". If there is no whitespace, the request succeeds without errors.
I already tried replacing the space by something else ("%20" or "_" or "+") but nothing helped. Is this a bug in the API or am i doing something fundamentally wrong?
Thanks in advance!
Edit 1:
btw i am using Google's oauth-playground with all the fitness scopes selected.
https://developers.google.com/oauthplayground/
Edit 2:
In code sample [2] i used the wrong dataTypeName. Was "activity_confidence" but should be "com.google.activity.samples".
[1] GET response
    {
      "dataSource": [
        {
          "application": {
            "packageName": "com.google.android.gms"
          },
          "dataQualityStandard": [
          ],
          "dataStreamId": "derived:com.google.activity.samples:com.google.android.gms:LGE:Nexus 5:c80045fc:detailed",
          "dataStreamName": "detailed",
          "dataType": {
            "field": [
              {
                "format": "map",
                "name": "activity_confidence"
              }
            ],
            "name": "com.google.activity.samples"
          },
          "device": {...},
          "type": "derived"
        },
        ...
      ]
    }

[2] POST body
    {
      "aggregateBy": [
        {
          "dataSourceId": "derived:com.google.activity.samples:com.google.android.gms:LGE:Nexus 5:c80045fc:detailed",
          "dataTypeName": "com.google.activity.samples"
        }
      ],
      "endTimeMillis": 1511132400000,
      "startTimeMillis": 1510268400000
    }

[3] POST Error message
    {
      "error": {
        "code": 400,
        "errors": [
          {
            "domain": "global",
            "message": "datasource not found: derived:com.google.activity.samples:com.google.android.gms:LGE:Nexus 5:c80045fc:detailed",
            "reason": "invalidArgument"
          }
        ],
        "message": "datasource not found: derived:com.google.activity.samples:com.google.android.gms:LGE:Nexus 5:c80045fc:detailed"
      }
    }

A: Did you try using a escape character like '\'?
Your data stream ID would look like
derived:com.google.activity.samples:com.google.android.gms:LGE:Nexus\ 5:c80045fc:detailed


text:
Q: Application of Hahn–Banach theorem I'd like to prove this statement:

Let $X$ a normed space. If $X$ has a linearly independent subset of cardinal $n$, then so does $X'$.

I know that I have to use the Hahn-Banach theorem to prove the existence of functionals in $X'$ that hold the above mentioned property but I'm not sure how.
Any suggestions are welcome. Thanks in advance.

A: Let $E=\{x_1, x_2, \cdots, x_n\}$ be the linearly independent set. Let $Y:=\textit{span}\{x_1, x_2, \cdots, x_n\}$. Then $E$ is a basis of $Y$. Let $p_i: Y \rightarrow \mathbb{K}$     ($\mathbb{K}=\mathbb{R}$ or $\mathbb{C}$) be the co-ordinate functional, i.e., $p_i(\sum_{i=1}^nc_ix_i)=c_i$. Since $Y$ is finite dimensional each $p_i$ is continuous  and $p_i(x_j)=1$ if $i=j$ and $p_i(x_j)=0$ if $i \neq j$. Now by the Hahn-Banach theorem, $\exists~~~f_1, f_2, \cdots, f_n \in X'$ such that $f_i|_Y=p_i~~~\forall~i$. $\therefore~~~f_i(x_j)=p_i(x_j)~~~\forall~i,j$. It can be easily shown that $f_i$'s are linearly independent.


text:
Q: How to avoid "fake" ids creation in db? I have python code which push new record to db to column info.
   try:
        db.add_new_record(info)
    except Exception as e:
        log.error(e)
        db.db.rollback()
        continue

I use standard sql query
INSERT INTO mydb (info, desc) VALUES ('value1', 'value2')

python:
import psycopg2
def add_new_record(self, info):
    info['table'] = self.table
    query = "INSERT INTO {table} (c1, c2)  VALUES ('{val1}', '{val2}')".format(**self.make_dct(info))
    self.make_execute(query)
    self.db_commit()
    return True

Sometimes I see exception
 exception: duplicate key value violates unique constraint "mydb_info_key"

It's normal.
I count rows in db: 25000 records.
But my last ids start with 60000+.
Duplicate exception records new id? How to avoid this?

A: there is another table mydb_seq that tells sql what the next index to use is(you can look at what it is with SELECT * FROM mydb_seq;)
somewhere else you are actively setting an ID to a higher value than this pointer, so sometimes this pointer points at an index that already exists in your table
you can identify where using the following logic
first find the pointer for the next_id
SELECT * FROM mydb_seq;

then query your table for anything with a bigger id
SELECT id FROM mydb WHERE id > $next_id;  // replace $next_id... with the value from above

as an aside you should really really really use the cursor.execute variable insertion ... what you are doing now is madness that will get you sql injected
qry = "INSERT INTO {table} (field1,field2,field3) VALUES (%s,%s,%s)".format(table="my_db")
cursor.execute(query,(var1,var2,var3))


text:
Q: 2 eclipse installations 1 ADT install Is there a way to have 2 installations of eclipse but 1 installation of ADT? I'm trying to save hard drive space, and thought I would ask. Thanks.

A: You should just download the plugin through the first installation of Eclipse and copy the plugin into second Eclipse's plugin directory.
The point is to have only one folder for SDK (just setting the SDK path in ADT configuration panel) to save space (and Android Emulator Settings).

A: ADT is an Eclipse plug-in.  You can have as many Eclipse installations as you like and choose to add ADT to any or all of them.  Note that RUNNING two ADT instances at the same time will confuse adb and generate a bunch of console warnings.