text:
Q: Proper GKTurnBasedMatch End Of Match When participantQuitOutOfTurnWithOutcome In my turn based match, I am unable to cleanly end the match when an out of turn player quits the match. I believe this is preventing me from starting a rematch.
Here is what I have observed. When I examine the completed game status of this game from the GKTurnBasedMatchmakerViewController of Player 1's device, it shows that the match outcome of Player 1 is Quit and the match outcome of Player 2 is "This player's turn". However, if I examine the completed game status of this game from the GKTurnBasedMatchmakerViewController of Player 2's device, it shows that the match outcome of Player 1 is Quit and the match outcome of Player 2 is "Won". BUT, if I click on "View Game" from the GKTurnBasedMatchmakerViewController from within the Player 1 device, the match outcome switches to "Won" for Player 2. How do I end this game properly so that Player 2 has a match outcome of "Won" from the perspective of Player 1?
In my scenario, player 1 starts a match and takes his turn. Then player 2 starts his turn. During that time, player 1 quits the match. The code sequence is then as follows:
Player 1:
[currentMatch participantQuitOutOfTurnWithOutcome:GKTurnBasedMatchOutcomeQuit withCompletionHandler:nil];

Player 2 - after receiving a call to handleTurnEventForMatch:didBecomeActive:
        // For each participant, set their matchOutcome relative to the local player who has just won.
        for (GKTurnBasedParticipant *part in [currentMatch.participants) {
            if ([part.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID]) {
                part.matchOutcome = GKTurnBasedMatchOutcomeWon;
            }
            else {
                part.matchOutcome = GKTurnBasedMatchOutcomeQuit;

            }
        }
        [currentMatch endMatchInTurnWithMatchData: data
                             completionHandler: ^(NSError *error) {
                                if (error) {
                                    NSLog(@"%@", error);
                                }
                                else {
                                    NSLog(@"After win: match ended successfully");
                                }];

Player 1 receives a prompt asking whether they want a rematch. If the user responds affirmatively, the following is sent:
[currentMatch rematchWithCompletionHandler:^(GKTurnBasedMatch *reMatch, NSError *error) {
    if (error) {
        NSLog(@"In rematchWithCompletionHandler. Error creating rematch: %@", error.localizedDescription);
    } else {
        NSLog(@"Success");
    }];

Unfortunately, the above rematch attempt fails because of the incorrect status of Player 2. The resultant error message from above is:
The requested operation could not be completed because the match request is invalid.

The following stack overflow problem suggests this is due the errant match data described above: Trouble Using the new rematchWithCompletionHandler method from Game Center

A: In order to solve this problem, I had to programmatically load the match data to force the matchOutcome of player 2 to switch to the state of "Won". So, instead of immediately calling rematchWithCompletionHandler when the user affirms the prompt for a rematch, I do the following when they affirm the prompt for a rematch:
[GKTurnBasedMatch loadMatchWithID:currentMatch.matchID withCompletionHandler:
  ^(GKTurnBasedMatch *match, NSError *error) {
    if (error) {
        NSLog(@"In requestRematch, failed to receive match data: %@", error.localizedDescription);
    }
    else {
         // Received the match data. Now request a rematch
         [match rematchWithCompletionHandler:
            ^(GKTurnBasedMatch *reMatch, NSError *error) {
              if (error) {
                  NSLog(@"In requestRematch: rematchWithCompletionHandler. Error creating rematch: %@", error.localizedDescription);
              }

              else
              {
                  NSLog(@"In requestRematch: Rematch granted with new matchID=%@. currentMatch was: %@", match.matchID, currentMatch.matchID);

                  // Do something with the reMatch data
              }

          }];
     }
}];


text:
Q: Вывод значения из большого словаря. Выборка из API Tinkoff. Язык Python Входные данные https://api.tinkoff.ru/v1/currency_rates
Если я правильно понимаю, по ссылке выдается массив с разными словарями, которые имеют одинаковые пары ключей.
Нужно вытянуть значение пары Sell:"текущий курс покупки доллара" в словаре со значением 'category': 'DebitCardsOperations'.
Код выглядит так
import requests
import json

def get_usd():
    url = "https://api.tinkoff.ru/v1/currency_rates"
    r = requests.get(url).json()
    rate_dict = (r["payload"]["rates"]) #получаем массив rates, который содержит всё что нам надо
    def has_sale(string): #здесь я пытался вытянуть значение sell, но вытянул все словари, которые содержат значение sell
        return "sell" in string

    l = list(filter(has_sale, rate_dict))

    print(l)

Дальше я запутался

A: У вас rate_dict - это список, содержащий словари. Вы можете обойти в цикле этот список и вывести только те словари, у которых значение ключа category это DebitCardsOperations.
import requests
import json

def get_usd():
    url = "https://api.tinkoff.ru/v1/currency_rates"
    r = requests.get(url).json()
    rate_dict = (r["payload"]["rates"]) #получаем массив rates, который содержит всё что нам надо

    for rate in rate_dict:
        if rate["category"] == "DebitCardsOperations":
            print(rate)
            print("sell: ", rate["sell"])

get_usd()

Пример вывода значения sell каждого словаря из списка:
sell_list = [
    {'sell': 1},
    {'sell': 2},
    {'sell': 3},
    {'sell': 4},
]

for s in sell_list:
    print(s)
    print(s['sell'])

# Результат:
# {'sell': 1}
# 1
# {'sell': 2}
# 2
# {'sell': 3}
# 3
# {'sell': 4}
# 4

Пример вывода значений из словаря:
rate = {
    'category': 'DebitCardsOperations',
    'fromCurrency': {'code': 840, 'name': 'USD', 'strCode': '840'},
    'toCurrency': {'code': 643, 'name': 'RUB', 'strCode': '643'},
    'buy': 64.6,
    'sell': 67.25
}

print(rate['category'])
# DebitCardsOperations

print(rate['fromCurrency'])
# {'code': 840, 'name': 'USD', 'strCode': '840'}

print(rate['fromCurrency']['name'])
# USD

print(rate['sell'])
# 67.25

A: Получил нужные данные, требовалось добавить еще несколько условий. Спасибо за помощь. Теперь код выглядит так:
def get_usd():
    url = 'https://api.tinkoff.ru/v1/currency_rates'
    r = requests.get(url).json()
    rate_dict = (r['payload']['rates'])
    for rate in rate_dict:
        if rate['category'] == 'DebitCardsOperations' and rate['fromCurrency']['name'] == 'USD' and rate['toCurrency']['name'] == 'RUB':

            # print(rate['category'])
            # print(rate['fromCurrency'])
            # print(rate['toCurrency'])
            # print(rate['fromCurrency']['name'])
            # print(rate['toCurrency']['name'])
            print(rate['sell'])

get_usd()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: how to concatenate multiple pandas dataframes to produce a box-and-whisker plot? Say I have a dataset of values that were binned. The bins are stored in a dictionary called mydict. To obtain the histogram quantities needed to plot a Box-and-Whisker, I have done:
df_dataset = pd.DataFrame.from_dict(dict([ (k, pd.Series(v)) for k,v in mydict.items() ]))
To get the histogram quantities:
mydict_min = df_dataset.min()
mydict_max = df_dataset.max()
mydict_median = df_dataset.median()
mydict_1st3rd = df_dataset.quantile([.1, .3])

My problem: I need to plot a Box-and-Whisker plot given the histogram quantities shown above. How can I do this by using DataFrame.boxplot? In this example a Box-and-Whisker was built by doing:
import matplotlib.pyplot as plt
from pandas import DataFrame

df = DataFrame({'Parameter': ['A',]*8,
                'Site': ['S1', 'S2', 'S1', 'S2', 'S1', 'S2', 'S1', 'S2'],
                'Value':  [2.34, 2.67, 2.56, 2.89, 3.45, 4.45, 3.67, 4.56]})

df.boxplot(by=['Parameter', 'Site'])
plt.show()

Do I need to create a DataFrame of DataFrames? I already have the histogram quantities (shown above) and need no grouping. How could I amend this code to include my histogram quantities?

A: After a brief search I have figured out there is no need to concatenate anything. The simple answer is to construct the Box-and-Whisker from the df_dataset, as it already is a series and as such it stores all the relevant histogram quantities.
The line creating the Box-and-Whisker is:
df_dataset.plot.box()
Further information can be found here.
Details such as axis titles, plot title, grids, bins, and everything else can be set based on one's needs.


text:
Q: R Boxplot from CSV File I'm trying to create a box plot from the following CSV file:
CSV
Here are the commands I use to create:
x <- read.csv("sean.csv",header=T,sep=",")
boxplot(x)

However this is my output:
output
Where is the X coming from and why is the first entry so visually different than the rest? Thanks.
Solution: changed to
x <- read.csv("sean.csv",header=T,sep=",", row.names = 1)


text:
Q: Android SQLite database exception Currently having an issue in my SQLite database in android, when I try and run a comparison I get the following error:
Caused by: android.database.sqlite.SQLiteException: near "@hotmail": syntax error: , while compiling: SELECT DISTINCT _id, userName, password FROM userTable WHERE userName=djdss@hotmail.comAND password=shshsh
my search is:
public boolean getUserNameAndPassword(String userName, String Password) throws SQLException {
    Cursor mCursor =
            db.query(true, TABLE_NAME, new String[] {KEY_ROWID,USER,
                    PWD},USER + "=" + userName + "AND password=" + Password, null,
                    null, null, null, null);

    if (mCursor.getCount() > 0)
    {
        return true;
    }
    return false;}

My attempt to run it is:
  boolean signIn = dbHelper.getUserNameAndPassword(mEmail, mPassword);
        if (signIn){
            Toast.makeText(getBaseContext(),"Sign in successful",Toast.LENGTH_LONG).show();
        }else {Toast.makeText(getBaseContext(),"Sign in failed",Toast.LENGTH_LONG).show();}

Thanks in advance!

A: You should used a parameterized queries instead of just appending in the username and password variables, see the example below:
Cursor mCursor =
        db.query(true, TABLE_NAME, new String[] {KEY_ROWID,USER,
                PWD},USER + " = ? AND password = ?", new String[]{ userName, Password },
                null, null, null, null);

if (mCursor.getCount() > 0)
{
    return true;
}
return false;}

A: SELECT DISTINCT _id, userName, password FROM userTable WHERE userName=djdss@hotmail.comAND password=shshsh
You forgot a space between userName and AND.
Furthermore, have a look at John's answer about parameterized queries.

A: You forgot a space, try now:
Cursor mCursor =
            db.query(true, TABLE_NAME, new String[] {KEY_ROWID,USER,
                    PWD},USER + "='" + userName + "' AND password='" + Password + "'", null,
                    null, null, null, null);

    if (mCursor.getCount() > 0)
    {
        return true;
    }
    return false;}

Edit: Also, you should think about using parameterized queries as John proposes.

A: try this:
Cursor mCursor =
            db.query(true, TABLE_NAME, new String[] {KEY_ROWID,USER,
                    PWD},USER+"='"+userName+"' AND password='"+Password+"'", null,
                    null, null, null, null);


text:
Q: Calling APIs in my Django Rest app from a different Spring Boot 2 app I have a custom spring boot 2 app which is already integrated with key cloak and provide apis to authenticate users. I just want to use its APIs in my Django rest app or in simple words I want to use APIs from an external app in my Django rest app. I searched for a solution but I couldn't find one. Can please somebody tell me how to do so ?
Thanks in advance


text:
Q: Is it "safe" to use comments to explain the functions in Javascript? Is it "safe" to put comments explaining the functions of the script in Javascript ? (Visible inside the public script)
Given that every users can read and modify the "Javascript", does the fact of using comments directly in the script could be dangerous ?
Because if I was a "hacker" and wanted to find an exploit, I think comments in the script explaining all the functions would make my life easier...

A: Skilled hackers don't need any comments.
You can never rely on anything on the client for security; all security boundaries must be verified on the server.

A: In my opinion, no ...it's not safe. It's really up to you and your specific situation. I bundle and minify personally, which removes those comments.

A: It depends on really what your program or script is designed to do. If it is a script that deals with secure information or data storage then the code itself should not be able to be modified by every user. Users designed to use the program should have access only to running the program.

A: You can add whatever comments you want in your javascript code, however make sure that you minify the files (that removes the comments) and make non minified files not accessible

A: There is no expectation of your source code being secure client side. Anyone can view your html, css, and javascript files if they wanted to.
Instead, focus on making sure that data flow is secure between client and server. For example, use https when dealing with passwords, credit card numbers, and other sensitive information.

A: You can add as much comments as you want. Adding a comment behind a function is not going to cause any trouble and will give you a better view on how you script works. I personally add comments to my scripts ofter, because then I can tell easier what the function does.


text:
Q: value of variable in c language with 100 digits So I'm new to c , and I have just learned about data type, what confuse me is that a value range of a double for example is from 2.3E-308 to 1.7E+308
mathematically a number of 100 digits ∈ [2.3E-308 , 1.7E+308].
Writing this simple program
#include <stdio.h>
int main()
{
double c = 5416751717547457918597197587615765157415671579185765176547645735175197857989185791857948797847984848;
printf("%le",c);
return 0;
}

the result is 7.531214e+18   by changing %le by %lf th result is 7531214226330737664.000000
which doesn't equal c.
So whats is the problem.

A: This long number is actually a numerical literal of type long long. But since this type cannot contain such a long number, it is truncated modulo (LLONG_MAX + 1) and resulting in 7531214226330737360.
Demo.
Edit:
@JohnBollinger: ... and then converted to double, with a resulting loss of a few (binary) digits of precision.
@rici: Demo2 - here the constant is of type double because of added decimal point

A: It might seem that, if we can store a number of up to 10 to the power 308, we are storing 308 digits or so but, in floating point arithmetic, that isn't the case. Floating point numbers are not stored as huge strings of digits.
Broadly, a floating-point number is stored as a mantissa -- typically a number between zero and one -- and an exponent -- some number raised to the power of some other number. The different kinds of floating point number (float, double, long double) each has a different number of bits allocated to the mantissa and exponent. These bit counts, particularly in the mantissa, control the precision with which the number can be represented.
A double on most platforms gives 16-17 decimal digits of precision, regardless of the magnitude (power of ten). It's possible to use libraries that will do arithmetic to any degree of precision required, although such features are not built into C.
An additional complication is that, in your example, the number you assign to c is not actually defined to be a floating point number at all. Lacking any indication that it should be so represented, the compiler will treat it as an integer and, as it's too large to fit even the largest integer type on most platforms, it gets truncated down to integer range.

A: You should get a proper compiler or enable warnings on it. A recent GCC, with just default settings will output the following warning:
% gcc float.c
float.c: In function 'main':
float.c:4:12: warning: integer constant is too large for its type
 double c = 5416751717547457918597197587615765157415671579185765176547645735175197857989185791857948797847984848;
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Notice that it says integer, i.e. a whole number, not floating point. In C a constant of that form denotes an integer. Unless suffixed with U, it is additionally a signed integer, of the greatest type that it fits. However, neither standard C, nor common implementations, have a type that is big enough to fit this value. So what happens, is [(C11 6.4.4.1p6)[http://port70.net/~nsz/c/c11/n1570.html#6.4.4.1p6])  :

If an integer constant cannot be represented by any type in its list and has no extended integer type, then the integer constant has no type.

Use of such an integer constant without type in arithmetic leads to undefined behaviour, that is the whole execution of the program is now meaningless. You should have read the warnings.
The "fix" would have been to add a . after the number!
#include <stdio.h>
int main(void)
{
    double c = 54167517175474579185971975876157651574156715791\
85765176547645735175197857989185791857948797847984848.;
    printf("%le\n",c);
}

And running it:
% ./a.out
5.416752e+99

Notice that even then, a double is precise to average ~15 significant decimal digits only.


text:
Q: Vibration on button click not working in Android Studio I want to add vibration functionality to my app and just wanted to get started with a simple vibration, I tried lots od turtorias but none of them seemed to work
@SuppressLint("NewApi")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val timer_button = findViewById<Button>(R.id.timer_button)
    val timer_text: EditText = findViewById<EditText>(R.id.time_text)
    val vibrator  = getSystemService(VIBRATOR_MANAGER_SERVICE) as VibratorManager

   timer_button.setOnClickListener {
       //val pattern = longArrayOf(0, 200, 100, 300)
       vibrator.getDefaultVibrator().vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE))
       Toast.makeText(this, vibrator.getDefaultVibrator().getId().toString(),Toast.LENGTH_SHORT).show()

   }}

Also I added the vibration permission to my manifest.xml
<uses-permission android:name="android.permission.VIBRATE" />

A: It works in all APIS

val vibration = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val vbManager =
                getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
            vbManager.defaultVibrator
        } else {
            @Suppress("DEPRECATION")
            getSystemService(VIBRATOR_SERVICE) as Vibrator
        }
        if (vibration.hasVibrator()) {
            vibration.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        }


text:
Q: New child class or conditional read from same one? Lets say I've a class:
class Foo{
    datatype1 x;
    datatype2 y;
    datatype3 z;
}

I want to populate:

*

*x if y = a

*z if y = b
That is, Foo with constructor would look like:
class Foo{
    datatype1 x;
    datatype2 y;
    datatype3 z;

    Foo(x, y){
        // x and y are intialized
    }
    Foo(z, y){
        // z and y are intialized
    }
}

y is initialized to support decision making in the future of the object i.e. depending on value y, I'll read x or z.
Does it makes OOP's sense to extend Foo and do this:
class Bar extends Foo{
    datatype1 x;
}

class Zar extends Foo{
    datatype3 z;
}

and then instantiate Bar if the condition that used to make y equal a is met and Zar if the condition that used to make y equal b is met. Which means I will use instanceof on Bar's or Zar's object to do whatever I used to do earlier after reading y.
What I find ugly: Object of Foo will either have x intialized or z depending on y. The field left uninitialized will have default value (null or its equivalent). Its a see-saw like condition, always!

A: It really depends on what you are trying to model and the relationships. As Tagir wrote it also depends on what the client code look like.
Foo, Bar and Zar convey zero meaning to me, so it is hard to recommend anything.
Do you just use Foo, Bar and Baz to hold data or do they have other methods than getters?


text:
Q: set the background transparent on android nativescript?
I want to achieve this kinda transparency on my custom view as displayed by alert view for Android application.
Thanks

A: @Dlucidone I had this solved by using custom overlay from css.
<GridLayout>
    <StackLayout>
        // All your page content goes here!
    </StackLayout>
    <StackLayout class="dimmer" visibility="{{showLoading ? 'visible' : 'collapsed'}}"/>
    <GridLayout rows="*" visibility="{{showLoading ? 'visible' : 'collapsed'}}">
        <ActivityIndicator busy="true" />
    </GridLayout>
</GridLayout>

Set the dimmer class to background transparent css, with width and height to 100%
Information how to use visible and collapsed
https://www.tjvantoll.com/2015/06/05/nativescript-showing-and-hiding-elements/
BTW there is a problem with android on setting isUserInteractionEnabled
https://github.com/NativeScript/NativeScript/issues/3215

A: If you need this to show an activity indicator as an overlay with a dimmed background, you could use this one: https://github.com/nstudio/nativescript-loading-indicator
import {LoadingIndicator} from '@nstudio/nativescript-loading-indicator'
const loader = new LoadingIndicator()
loader.show({dimBackground: true})
loader.hide()


text:
Q: Is it neccesery to store Access Tokens? I'm new to FB application Development.
Just clear me, after user installing my application imma getting their access token is it necessary to store those access tokens to access their data and post behalf of them or is there any way to get all users access tokens who are all using my app....


text:
Q: Developing and Distributing Portable and Cross-platform Ruby/JRuby Application i was try to beginning ruby/jruby desktop application development, as i've googled before, ruby lacks of distribution/deployment system, so i haven't decided which one to use, is it ruby with green_shoes (gtk) or JRuby with purple_shoes (swing), if i go with green_shoes, then i should provide GTK Runtime, and if JRuby then i should provide JRE, or maybe if possible a portable internet browser and portable server (just like PHP's UniServer).
is there any other alternative to overcome this, so that i could distribute my program, ruby with all required dependency for my program only by copying the folder in such portable way?
so if i/they want to use it on windows, i only need to create a shortcut to the my program on the copied folder,
and when i/they want to use it on linux, i only need to "ln -s" to $PATH to that my program on the copied folder

A: for JRuby only:

*

*GUI toolkit, we can use Monkeybars https://github.com/monkeybars/monkeybars-core

*Deployment we can use rawr http://rawr.rubyforge.org/
answers from: Moh Hasbi Assidiqi


text:
Q: Create groups with maximum diversity of group members I have a list of students with two properties, in this case gender and class. How can I create 6 groups of 3 students (and 1 of 2) with maximum class and gender diversity in the groups? Students need to be assigned so that the chances of ending up in a group with somebody of the same gender or class are minimal. I.e. I want to mix up the groups as good as possible so students with different backgrounds intermingle.
import pandas as pd

data = [{'name': 'Katina', 'gender': 'f', 'class': 'a'}, {'name': 'Mary', 'gender': 'f', 'class': 'a'}, {'name': 'Manuel', 'gender': 'm', 'class': 'b'}, {'name': 'Timothy', 'gender': 'm', 'class': 'b'}, {'name': 'Eunice', 'gender': 'f', 'class': 'a'}, {'name': 'Gary', 'gender': 'm', 'class': 'a'}, {'name': 'Michael', 'gender': 'm', 'class': 'a'}, {'name': 'Melanie', 'gender': 'f', 'class': 'b'}, {'name': 'Edward', 'gender': 'm', 'class': 'a'}, {'name': 'Jessie', 'gender': 'm', 'class': 'b'}, {'name': 'Elizabeth', 'gender': 'f', 'class': 'a'}, {'name': 'Jared', 'gender': 'm', 'class': 'a'}, {'name': 'Jose', 'gender': 'm', 'class': 'b'}, {'name': 'Amado', 'gender': 'm', 'class': 'b'}, {'name': 'Matthew', 'gender': 'm', 'class': 'a'}, {'name': 'Charlie', 'gender': 'm', 'class': 'a'}, {'name': 'Willie', 'gender': 'm', 'class': 'b'}, {'name': 'Mary', 'gender': 'f', 'class': 'a'}, {'name': 'Susan', 'gender': 'f', 'class': 'b'}, {'name': 'Michael', 'gender': 'm', 'class': 'b'}]
df = pd.DataFrame(data)

The best thing I could come up with was to first apply clustering and then traverse the clusters to assign students to groups, but this basically only reduces the number of properties and doesn't solve the assignment issue. Any ideas?
from sklearn.cluster import KMeans

df['gender']= df['gender'].map({'f':1, 'm':2})
df['class'] = df['class'].map({'a':1, 'b':2})
kmeans = KMeans(n_clusters=10)

df['cluster'] = kmeans.fit_predict(df[['gender', 'class']])

A: The closest problem I can think of is set packing, which is NP-complete, so it's probably safe to say there's no fast algorithm for doing this.
One observation here is that all of the variables you're interested in are categorical, so we have an easy way to define the diversity of a group: the number of times two entities in the group share the same value for a given variable. To start, let's define a few things.
A student can be a struct-like object or a dict; let's go with the latter. A student can therefore just look like
pat = {
  'name': 'Pat',
  'gender': 'nonbinary',
  'class': 'stupid rich'
}

You might want to use enums for the values, but let's keep it simple. Each student has two traits ("variables" in the statistical sense), and each of those can assume any of a number of string values. Let's make sure we can keep track of those traits somewhere, maybe a private global variable:
_TRAITS = ['gender', 'class']

A group can just be a list of students.
Now we can define a function diversity_score, which accepts a group and returns an integer (higher is more diverse):
def diversity_score(group):
    score = 0
    for i, student_1 in enumerate(group):
        for student_2 in group[i + 1:]:
            for trait in _TRAITS:
                score -= (student_1[trait] == student_2[trait])
    return score

This can probably be done more efficiently with Pandas, but you get the point: every time the same trait is shared between two students, the diversity score goes down. This has the nice property that larger groups of homogeneous students will get quadratically penalized due to the number of connections in a fully-connected graph (two students with the same gender will reduce the score by one; three students by three; four students by 6; etc.). Therefore, a group with four women and four men will be more diverse than five women and three men; more diverse still than six and two, etc.
Now we can define a greedy algorithm. We'll start by randomly assigning all students to groups of relatively equal size. We'll then begin an iterative loop. On each iteration, we'll go through every student, and try swapping them to different groups. If we find that the overall diversity score improves (i.e., swapping students A and B from groups X and Y results in the sum of the X and Y's diversity scores increasing), we make the swap.
In code, that looks like this. First, the initial assignment:
import random

def random_assignment(students, num_groups):
    """Randomly assign students to groups.

    students: list of students, as described above
    num_groups: number of groups to return
    returns: lists of students of more-or-less equal size
    """
    random.shuffle(students)
    groups = [[] for _ in range(num_groups)]
    for i, student in enumerate(students):
        index = i % len(groups)
        groups[index].append(student)
    return groups

Now for the iterative step, where we go through each group and try swapping students with other groups. First, let's define the helper function maybe_swap, which will try swapping students between groups. If it finds a way to improve the diversity score, it will perform the swap in-place and return True; otherwise, it will return False:
def maybe_swap(group_1, group_2):
    diversity_1, diversity_2 = map(diversity_score, [group_1, group_2])
    old_sum = diversity_1 + diversity_2
    for _ in range(len(group_1)):  # do this for every student in group_1
        student_1 = group_1.pop(0)  # provisionally remove from group_1
        for _ in range(len(group_2)):
            student_2 = group_2.pop(0)  # provisionally remove from g_2
            group_1.append(student_2)  # provisionally swap students
            group_2.append(student_1)
            diversity_1, diversity_2 = map(
                diversity_score, [group_1, group_2])
            new_sum = diversity_1 + diversity_2
            if new_sum > old_sum:  # see what the new score is
                return True  # leave the swap intact and return if higher
            group_2.pop()  # else, remove student_1 from group_2 ...
            group_2.append(group_1.pop())  # and return student_2 to group_2
        group_1.append(student_1)  # return student_1 to group_1
    return False

With the helper functions initial_assignment and maybe_swap defined, we can create the main loop:
def assign_to_groups(students, num_groups):
    groups = random_assignment(students, num_groups)
    while True:
        has_swapped = False
        for i, group_1 in enumerate(groups):
            for group_2 in groups[i + 1:]:
                has_swapped = maybe_swap(group_1, group_2) or has_swapped
        if not has_swapped:
            return groups

This function is guaranteed to return because the diversity score is only permitted to increase (otherwise we might run into cycles), and the diversity score is capped at 0.
There's a lot to improve here. We could cache each group's diversity score. We could find more efficient ways to calculate diversity using data frames. We could iterate over lists using indices, cutting down on the number of slices.
But on the plus side, what we have here is an easy-to-understand algorithm in pure Python. It requires no clustering, just basic set-theoretic reasoning. Hope it helps!
Edit:
Putting it all together with the data you provided:
import random

data = [{'name': 'Katina', 'gender': 'f', 'class': 'a'}, {'name': 'Mary', 'gender': 'f', 'class': 'a'}, {'name': 'Manuel', 'gender': 'm', 'class': 'b'}, {'name': 'Timothy', 'gender': 'm', 'class': 'b'}, {'name': 'Eunice', 'gender': 'f', 'class': 'a'}, {'name': 'Gary', 'gender': 'm', 'class': 'a'}, {'name': 'Michael', 'gender': 'm', 'class': 'a'}, {'name': 'Melanie', 'gender': 'f', 'class': 'b'}, {'name': 'Edward', 'gender': 'm', 'class': 'a'}, {'name': 'Jessie', 'gender': 'm', 'class': 'b'}, {'name': 'Elizabeth', 'gender': 'f', 'class': 'a'}, {'name': 'Jared', 'gender': 'm', 'class': 'a'}, {'name': 'Jose', 'gender': 'm', 'class': 'b'}, {'name': 'Amado', 'gender': 'm', 'class': 'b'}, {'name': 'Matthew', 'gender': 'm', 'class': 'a'}, {'name': 'Charlie', 'gender': 'm', 'class': 'a'}, {'name': 'Willie', 'gender': 'm', 'class': 'b'}, {'name': 'Mary', 'gender': 'f', 'class': 'a'}, {'name': 'Susan', 'gender': 'f', 'class': 'b'}, {'name': 'Michael', 'gender': 'm', 'class': 'b'}]

_TRAITS = ['gender', 'class']

def diversity_score(group):
    score = 0
    for i, student_1 in enumerate(group):
        for student_2 in group[i + 1:]:
            for trait in _TRAITS:
                score -= (student_1[trait] == student_2[trait])
    return score

def random_assignment(students, num_groups):
    """Randomly assign students to groups.

    students: list of students, as described above
    num_groups: number of groups to return
    returns: lists of students of more-or-less equal size
    """
    random.shuffle(students)
    groups = [[] for _ in range(num_groups)]
    for i, student in enumerate(students):
        index = i % len(groups)
        groups[index].append(student)
    return groups

def maybe_swap(group_1, group_2):
    diversity_1, diversity_2 = map(diversity_score, [group_1, group_2])
    old_sum = diversity_1 + diversity_2
    for _ in range(len(group_1)):  # do this for every student in group_1
        student_1 = group_1.pop(0)  # provisionally remove from group_1
        for _ in range(len(group_2)):
            student_2 = group_2.pop(0)  # provisionally remove from g_2
            group_1.append(student_2)  # provisionally swap students
            group_2.append(student_1)
            diversity_1, diversity_2 = map(
                diversity_score, [group_1, group_2])
            new_sum = diversity_1 + diversity_2
            if new_sum > old_sum:  # see what the new score is
                return True  # leave the swap intact and return if higher
            group_2.pop()  # else, remove student_1 from group_2 ...
            group_2.append(group_1.pop())  # and return student_2 to group_2
        group_1.append(student_1)  # return student_1 to group_1
    return False

def assign_to_groups(students, num_groups):
    groups = random_assignment(students, num_groups)
    while True:
        has_swapped = False
        for i, group_1 in enumerate(groups):
            for group_2 in groups[i + 1:]:
                has_swapped = maybe_swap(group_1, group_2) or has_swapped
        if not has_swapped:
            return groups

Now, if I call assign_to_groups(data, 5), I get the output
group 0: [{'name': 'Manuel', 'gender': 'm', 'class': 'b'}, {'name': 'Jared', 'gender': 'm', 'class': 'a'}, {'name': 'Michael', 'gender': 'm', 'class': 'b'}, {'name': 'Eunice', 'gender': 'f', 'class': 'a'}] (diversity score: -5)
group 1: [{'name': 'Gary', 'gender': 'm', 'class': 'a'}, {'name': 'Elizabeth', 'gender': 'f', 'class': 'a'}, {'name': 'Willie', 'gender': 'm', 'class': 'b'}, {'name': 'Jose', 'gender': 'm', 'class': 'b'}] (diversity score: -5)
group 2: [{'name': 'Jessie', 'gender': 'm', 'class': 'b'}, {'name': 'Michael', 'gender': 'm', 'class': 'a'}, {'name': 'Mary', 'gender': 'f', 'class': 'a'}, {'name': 'Timothy', 'gender': 'm', 'class': 'b'}] (diversity score: -5)
group 3: [{'name': 'Matthew', 'gender': 'm', 'class': 'a'}, {'name': 'Susan', 'gender': 'f', 'class': 'b'}, {'name': 'Amado', 'gender': 'm', 'class': 'b'}, {'name': 'Mary', 'gender': 'f', 'class': 'a'}] (diversity score: -4)
group 4: [{'name': 'Katina', 'gender': 'f', 'class': 'a'}, {'name': 'Edward', 'gender': 'm', 'class': 'a'}, {'name': 'Charlie', 'gender': 'm', 'class': 'a'}, {'name': 'Melanie', 'gender': 'f', 'class': 'b'}] (diversity score: -5)


text:
Q: A single click on my trackpad occasionally acts like a double click I have a Macbook Pro and when I click with the trackpad, it will occasionally act like a double click. This happens whether I physically click the trackpad or if I just do a tap to click. I have tried changing the double click speed to no avail. It might be a hardware issue, but the fact that it happens when I tap to click leads me to believe it is at least not a mechanical issue (still possible an electronics/cable issue with the trackpad). I have also reset the NVRAM and the SMC (not sure why it would be an issue with those but I'm attempting everything). I'm on Yosemite.

A: Try disabling tap to click in the trackpad settings. If you're MacBook has the new vibrating force touch trackpad you could try to disable the force click and haptic feedback. Otherwise it may be a hardware issue.

A: I am having the same issue, and for now the only solution I found was to use a usb mouse. I think the problem began with 10.10.4, but I am not sure. It only happens to me with Chrome and Steam mostly.


text:
Q: Move an element to next line using CSS, if it doesn't fit in the available area width I have a View created using ExtJS, composed of a Autocompleting Textbox (bound to a store) and a custom templated DataView (again, bound to another store). And the view looks like below.

Here's how it works.

*

*User searches for a Tag in a searchbox, and selects the matching tag from dropdown. Once selected, it is automatically added to dataview right below, which appears like a Tag Cloud (though not exactly).

*Tag item added to DataView is custom styled, and has "remove" link next to label to remove it from DataView.

Now, here's a problem:

*

*The available width of DataView is fixed, so if a tag item text is longer, you  can see that it gets broken and remaining part of tag appears on next line.

What I want is something like this:

As you can see that if Tag item is not small enough to fit available area, it gets into next line, but if space is available, it will be on the same line.
Any way to attain it with CSS? or need to write JS logic for this?
Note that for CSS solution, I'm bound to support evil IE7/8.

A: Yes you can do something similar in the CSS,
Do you have a sample code you can post online somewhere? so we can give advice on your actual code?
But to achieve this, each input field needs to have a css style of
display: inline-block;

so if it fits in the provided width, it will remain in the same line, but if the text box is too large, it will goto next line.
Looking at your example, it seems you have some kind div container with "overflow: hidden".
In this senario, you either remove the overflow: hidden
OR
you can wrap the input text boxes with another div and set the width there.
EDIT
Here's the example
http://jsfiddle.net/Raver0124/7X2h3/

A: you can also do this using max-inline-size property:
.x-tagfield-input  {
  max-inline-size: size in px;
}


text:
Q: Why is callback function into directive controller not being recognized? I'm trying to get a directive to work with its own controller:
http://jsfiddle.net/edwardtanguay/xfbgjun5/14/
However, when I click the button:
var template = '<button ng-click="vm.addItem()">add item</button>'+
               '

{{item}}

';

It tells me that:
Error: vm.add is not a function

even though I define controllerAs and bindToController:
return {
  restrict: 'A',
    scope: {
        datasource: '=',
        add: '&'
    },
    controller: controller,
    controllerAs: 'vm',
    bindToController: true,
    template: template
};

and pass in a scope method from the main controller:

Why does it not recognize add as a function on vm?

ADDENDUM: The controller looks like this:
.controller('mainController', function ($scope) {
    $scope.customers = ['First','Second','Third'];
    $scope.score = 0;
    $scope.addCustomer = function() {
        $scope.score++;
    }
})

A: You can find the answer to your question in this blog post
If you use Angular 1.3 you need to add to the directive the following line of code:
bindToController: true,

Check the blog post and the code snippets.

A: When you bind to attributes, you have to bind it to $scope, not the controller.
var controller = function($scope) {
    var vm = this;
    function init() {
        vm.items = angular.copy($scope.datasource);
    }
    init();

    vm.addItem = function() {
        $scope.add();
        vm.items.push('new one');
    }
}

http://jsfiddle.net/xfbgjun5/15/


text:
Q: What excactly is a "fourier component of a density fluctuation"? Light scattering texts say depending on the scattering angle, you are seeing a certain fourier component of a density fluctuation. This density fluctuation varies sinusoidally due to Brownian motion of particles. I have a few questions to help my understanding:
Why does Brownian motion cause sinusoidal density fluctuations? For instance, the diagram on page 124 of this book on light scattering and colloids, shows this pictorally, but I cant understand why the Brownian particles would ever be like that?
At any moment in time isn't the position of each particle just in a random place?
How can I think of a "Fourier component of a density fluctuation?" What exactly is a "Fourier component" in this context.
Thanks


text:
Q: How to remove margin / padding from MaterialUI drawer? I am working on a React app using MaterialUI to create an Appbar and Drawer.
There is an extra space between the edge of the window and the Drawer.
The extra space is also covering up an IconButton I use to toggle opening and expanding the drawer. It looks like this:

Here's how I'm rendering the Appbar and Drawer:

render(){
    const { classes,drawerOpen,theme } = this.props;
    return(
      <React.Fragment>
        <AppBar
          position="absolute"
          className={classNames(classes.appBar,drawerOpen && classes.appBarShift)}
        >
        <Toolbar disableGutters={!this.state.open}>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={this.handleDrawerOpen}
            className={classNames(classes.menuButton, drawerOpen && classes.hide)}
          >
            <ToggleLeft />
          </IconButton>
          <Typography variant="title" color="inherit" noWrap>
            MYAPP
          </Typography>
        </Toolbar>
      </AppBar>
      <Drawer
        variant="permanent"
        classes={{
          paper: classNames(classes.drawerPaper, !drawerOpen && classes.drawerPaperClose),
        }}
        open={this.state.open}
      >
        <div className={classes.toolbar}>
          <IconButton onClick={this.handleDrawerClose}>
            {theme.direction === 'rtl' ? <ToggleLeft />:<ToggleRight />}
          </IconButton>
        </div>
        <Divider />
          <List><SideAccountsList {...this.props}/></List>
      </Drawer>
      </React.Fragment>
      )
  }


text:
Q: How can I get a jQuery event to fire on a direct link to http://www.website.com/#id? Trying to figure out how I can get jQuery to detect a hyperlink referencing a unique ID on the page. I want to load the event not only when the element is clicked on the page, but also if someone direct links to the page using the unique #id assigned to that #div.
UPDATE:
OK, this is what I have so far and it's not firing.
    function opencontact() {
        $("#first-name-check").hide();
        $("#last-name-check").hide();
        $("#phone-number-check").hide();
        $("#email-address-check").hide();
        $("#customer-message-check").hide();
        $("#send").button("disable");
        $("#email-form").dialog("open");
    }

    $(".email").click(opencontact);

    var hash = window.location.hash.substring(1);
        alert(hash);
        if (hash == "contact") {
            opencontact();
        }

Alert is returning the correct #hash so I don't know what's wrong.
Dialog initialized like this:
   $(function() {
        $("#email-form").dialog({
            autoOpen: false,
            resizable: false,
            draggable: false,
            closeOnEscape: false,
            height: 600,
            width: 540,
            modal: true,
            buttons: {
                "Send Joe Your Message": {
                    text: "Send Joe Your Message",
                    id: "send",
                    click: function() {
                        $.post("email.php", $(this).find('input, textarea').serialize());
                        $(this).find('input, textarea').val("");
                        $(this).dialog("close");
                    },
                },
                Cancel: function() {
                    $(this).find('input, textarea').val("");
                    $(this).dialog("close");
                }
            }
        });

    });

A: Something like this should do the trick :
//this will grab the url from the address bar
var oldUrl = document.location.href;
//now we need to find just the part after the #
var urlSlice = oldUrl.split('#',oldUrl.length);
//urlSlice is now an array of two items (one before the '#' one after)
//from which we can grab the div id
var divId = urlSlice[1];

//then if it is the id you want
if( divId === 'desiredID' ) {
    clickHandler();
}

function clickHandler() {
    //do stuff
}

Personally I would put all of that in a function to be cleaner but it will work outside of one too.

A: You could do this:
$(document).ready(function() {
  // Attach click handlers and set your dialog here..
  if(window.location.hash.length > 1) {
    switch(window.location.hash) {
      case '#contact':
        $('.email').click();
        break;
      case '#anyotheridyouvegot':
        $('.classoftheelementtobeclickedon').click();
        break;
    }
  }
});

This will check if there is a hash in the url at page load and then trigger a click on an element with its id depending on the hash value.


text:
Q: C++ Boolean with Integers OK so obviously this question might sound dumb for more experienced people, but, for the following lines the result I get is 0:
int x = 2,
y = -2;

cout << (x++ - y && (--x + y));

I understand it means that either one of these two expressions equals 0, but how? As far as I understand, this should be (3 && -1)?
Also, a little subquestion: when does x++ exactly take effect? On the next occurance of x within the same expression, after the left-shift operator within the same line, or in the next statement?
Thank you!

A:
As far as I understand, this should be (3 && -1)?

you understand wrong:
first left side is fully evaluated, as it is necessary for short circuit evaluation with logical and (details can be found here)
x++ - y == 4 // as result of x++ == 2 so (2-(-2)), after that x == 3

result is true so right side is evaluated:
--x + y ==  0 // as result of --x == 2 so (2+(-2)), after that x == 2

result on the right is false so result of and is false as well which printed by std::ostream as 0
Note: short circuit evaluation of logical or and and operations make such code valid (making them sequenced) but you better avoid such questionable expressions. For example simple replacing logical and to binary would make it UB.


text:
Q: Is there Visual Studio 2012 Pre-Run Event? I am hoping to run a batch file before running the exe from visual studio. Therefore, is there a pre-run event?
Why I am doing this. There are generated assets from other exe, and I want to copy over the newer assets automatically before running this exe.
To clarify, this should work without building from Visual Studio. Assume the build/exe to stay the same.

A: Turns out actually pre-build event is also pre-run event.
Everytime before running, it tries to figure out if it needs to build, so even if it doesn't build anything, it always runs the pre-build event.

A: VS project file is basically MSBuild file and MS Build provides such events.
Open your .csproj file in text editor and you will see plain MS Build xml file.
See this article:
http://msdn.microsoft.com/en-us/library/dd293582.aspx
Also, this question suggests: PreBuild for PreBuild Event Command in csproj

You can do it through Visual Studio which will actually edit your
  .csproj file in fact.
Right click on the project and select Project Dependencies and select
  the project which you need to build before this project. Verify it by
  selecting the Build order tab.


text:
Q: find the location of the whitish points on an image import matplotlib.image as img
import numpy as np
import matplotlib as plt
import matplotlib.pyplot as plt

image1 = img.imread("82.png",0)
image2 = img.imread("83.png",0)

diff = image2 - image1

matchingInd = np.where(diff > 0.6)

diff[matchingInd] = 1
plt.imshow(diff)

image1 and image2 has black background with some bright(whitish) points. image2 is the same photo as image1 but just added some bright(whitish) points or deleted some of the bright(whitish) points. How can I find the location of the added bright points on the image2?

A: Since you have tagged OpenCV I have replicated your problem the following way.
Consider 2 image arrays a and b, where 255 refers to the bright spots:
>>> a
array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0, 255,   0, 255,   0,   0, 255,   0,   0,   0,   0,   0],
       [  0, 255,   0,   0,   0,   0,   0, 255,   0, 255, 255,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0,   0,   0,   0],
       [  0, 255,   0,   0,   0, 255, 255,   0, 255,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]],
  dtype=uint8)

In b, some spots have been removed compared to a and new spots have been added:
>>> b
array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255, 255],
       [255,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255],
       [255,   0, 255,   0, 255,   0,   0, 255,   0,   0,   0,   0,   0],
       [  0, 255,   0,   0,   0,   0,   0, 255,   0, 255,   0,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0, 255,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0,   0,   0,   0]],
  dtype=uint8)

Finding only the newly added spots in b using cv2.subtract. This should be read as elements in a are subtracted from elements in a:
>>>diff = cv2.subtract(b, a)

diff contains only the newly added spots:
>>> diff
array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255, 255],
       [255,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255],
       [255,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0,   0,   0,   0]],
  dtype=uint8)

Now find the coordinates as mentioned above using np.argwhere:
>>> np.argwhere(diff == 255)
array([[ 0, 11],
       [ 0, 12],
       [ 1,  0],
       [ 1, 12],
       [ 2,  0],
       [ 4, 10],
       [ 5, 10],
       [ 6,  5]], dtype=int64)

A: You can use numpy.where or numpy.argwhere
They will give you the same results but the output shape will be different:
numpy.where will give you a tuple with two elements: the array of all the x coordinates (x1, x2, ...) and the array of all the y coordinates (y1, y2, ...)
numpy.argwhere will give you an array of shape (N, 2) with each row correponfing to the coordinates of one pixel
import numpy as np

my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

np.where(my_array < 4)
Out: (array([0, 0, 0]), array([0, 1, 2]))

np.argwhere(my_array < 4)
Out: array([[0, 0],
            [0, 1],
            [0, 2]])

Note: using np.argwhere should throw an error when trying to run the following line diff[matchingInd] = 1


text:
Q: Cannot install MySQL in Ubuntu 18.04 I am new to MySQL and I am having trouble installing it for a few days now. I was running MySQL and these are the things that I did.
mysql -u root -p

and entered my root password, then
I created a new user using
mysql>GRANT ALL PRIVILEGES ON *.* TO 'ananyapam'@'localhost' IDENTIFIED BY 'password';
mysql>\q

Entered using the new user
mysql -u ananyapam -p

(Succesful!)
Then tried deleting the new user ananyapam using
DELETE FROM mysql.user WHERE user = 'ananyapam';

Now when I listed my users and there was no user ananyapam.
However, now when I try to create the user ananyapam again using
mysql>GRANT ALL PRIVILEGES ON *.* TO 'ananyapam'@'localhost' IDENTIFIED BY 'password';

it returns an error message. Not understanding much after a while of searching, I thought of removing and then reinstalling it using the commands below:
 sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-* mysql-client-core-*
 sudo rm -rf /etc/mysql /var/lib/mysql
 sudo apt-get autoremove
 sudo apt-get autoclean

I then tried to reinstall MySQL using this
 sudo apt install mysql-server
 sudo mysql_secure_installation

it returns error
ERROR 1045 (28000): Access denied for user 'debian-sys-maint'@'localhost' (using password: YES)

This link might be useful for someone:Access denied for user 'debian-sys-maint' - installing mysql?
Edit:
@Melebius suggested the other answer but after
mysql> SELECT user,authentication_string,plugin,host FROM mysql.user;
+------------------+-------------------------------------------+-----------------------+-----------+
| user             | authentication_string                     | plugin                | host      |
+------------------+-------------------------------------------+-----------------------+-----------+
| root             |                                           | auth_socket           | localhost |
| mysql.session    | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys        | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *477880DFF7642ABC170F60991A43E7FFB8B000E4 | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
4 rows in set (0.00 sec)

it returns an error message
mysql> CREATE USER 'debian-sys-maint'@'localhost' IDENTIFIED BY 'password';
ERROR 1396 (HY000): Operation CREATE USER failed for 'debian-sys-maint'@'localhost'

Any help is appreciated.


text:
Q: istio internal GRPC services communication I am having trouble having two in-cluster GRPC services (written in netcore3.0) I get Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Connection reset by peer") (with uri = <service>.default.svc.cluster.local) or Grpc.Core.RpcException: Status(StatusCode=Unimplemented, Detail="") with uri = user.default.svc.cluster.local:80. The weird part is all the services work fine if they are communicating from different clusters. I'm I using the right urls. The configuration of one of the services in attached here.
apiVersion: v1
kind: Service
metadata:
  name: user
  labels:
    app: user
    service: user
spec:
  ports:
  - port: 80
    name: grpc-port
    protocol: TCP
  selector:
    app: user
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: user-v1
  labels:
    app: user
    version: v1
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: user
        version: v1
    spec:
      containers:
      - name: user
        image: ***
        imagePullPolicy: IfNotPresent
        env:
        - name: GOOGLE_APPLICATION_CREDENTIALS
          value: "***"
        ports:
        - containerPort: 80
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: user
spec:
  hosts:
  - user.default.svc.cluster.local
  http:
  - route:
    - destination:
        port:
          number: 80
        host: user.default.svc.cluster.local
        subset: v1
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: user
spec:
  host: user.default.svc.cluster.local
  subsets:
  - name: v1
    labels:
      version: v1
---

FIXED: I managed to the it to work by using gRPC's .NETCORE3 client factory integration as described here

A: Instead of creating a channel and client manually as one would usually do. i.e
var endpoint = "test"; //or http://test
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
Channel channel = new Channel(endpoint, ChannelCredentials.Insecure);
client = new TestService.TestServiceClient(channel);

I used GRPC client factory integration (in ConfigureServices (startup.cs) like this (after adding Grpc.Net.ClientFactory package version 0.1.22-pre1:
services.AddGrpcClient<TestService.TestServiceClient>(o =>
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            o.BaseAddress = new Uri("http://test");
        });

Thereafter you can access the client by using Dependency Injection.
I'm not sure why the second approach works but the first one doesn't.


text:
Q: Good 2D Collision Response References Hey, I'm currently looking for various methods of implementing collision response in 2D video games, something similar to this tutorial Metanet has: N Tutorial I'm looking to implement something in XNA, but any language would be fine. I'm more interested in implementing programmatically  than actual theory. I'd prefer more beginner friendly material, but I do welcome more advance topics.
So could someone suggest some good 2D collision response articles/books?
(PS: I'm more interested in response than detection)

A: I really like this one, it just arrived a week ago and it's everything you could want short of doing relativistic effects:
http://www.amazon.com/Physics-Game-Programmers-Grant-Palmer/dp/159059472X

A: The N tutorial that you mentioned already is a great resource to start with. I also recommend the very good article 2D Polygon Collision Detection. It comes with a great C# implementation and example for polygon collision detection using the Separating Axis Theorem and explains some of the concepts better.
As far as responding to a collision is concerned it depends on the scenario. For games you might want to check for a possible collision based on the current velocity and then simply adjust the actual velocity to prevent collision. You could also implement some sort of 'bounce' effect. In any case it will likely be adjusting both the velocity and direction of the object.
You can use the Separating Axis Theorem to do the collision detection and also use polygon projection to find the distance to the target on a specific axis. (most of the time the vector on which you move).

A: How much detail do you need?  Answering some of these questions would help you eliminate packages that don't do what you need.
Do you have to worry about object rotation?  Then you need to be concerned about lever arms, angular momentum, moments of inertia, and torques.
Do you have to worry about deformation?  Then you need to get into finite element analysis, stress/strain, etc. -- something that describes how the objects respond internally to external forces.
What about frictional effects?  Then you'll need coefficients of friction, or possibly velocity models for air resistance.
Gravitational effects?  Electromagnetic effects?  Other forces?

A: If you want a basic answer for collision response, here it is :
for each pair of objects that collide
    ask gently to the collision detection lib their interpenetration distance
    Apply an impulse (i.e. a force in the duration of the frame) to both objects :
        force proportional to penetration depth (you will have to tune the coef by hand)
        direction : perpendicular to the collision normal.
        application point : the collision point (approximately, since it s not a point anymore but a volume)
integrate (Euler, Verlet, )\

A: I was searching for same info too, The most usable
thing i found so far was
http://www.myphysicslab.com/collision.html
the worse thing here for me is tahat this is
withoout friction (tangent collision impulse
only normal impulse) and I think the one with
such friction impulse would be better but still
not found a tutorial how to correctly implement
that

A: Have you looked at Cocos2d?

*

*Intro to Cocos2D Tutorial

*Intro to Box2D Tutorial

*How to Create a Breakout Game with Box2D and Cocos2D Tutorial: Part 1/2

*How to Create a Breakout Game with Box2D and Cocos2D Tutorial: Part 2/2

A: Physics engines are very complicated.  You would be much better off using an existing one.

*

*Farseer  (C#, derived from an older version of Box2D).

*Box2d    (C++, It has .NET bindings)

*Chipmunk (C, I don't think it has a C# port, but you could make one).

If you want to use physics in your game, use Farseer, or a Box2D bindings.  If you want to learn about physics, consider making C# port of Box2D, or Chipmunk.  If you are just curious, all of their code is open source.


text:
Q: How to sort a dictionary in django? i'm a rookie in programming and i ran into a problem in django.
So i'm trying to sort a dictionary based on the value. I've tryed several methods seen here, but thing is nothing works for me. It worked to make the dictionary but i don't know why it's not sorting.
So 'scoruri' is the dictionary: when using it in html it's showing like this {User: alex_py: 6, User: ion: 3, User: lil: 1, User: sss: 1, User: ddd: 1, User: bbb: 7}, 'result' is the score for each 'user'(key).
When i'm printing the type of scoruri it prints 6 times (type 'dict')
It may be possible that each key:value in scoruri to be actually a dictionary so i'm having a dictionary of dictionaries?
Below are the methods i've tryed to sort.
views.py
def home(request):
    data = dict()
    data['users'] = User.objects.all()
    data['scoruri'] = dict()

    if request.method == "POST":
        for key in request.POST:
            if 'nota_' in key:
                nota_acordata = Punctaj.objects.filter(acordat_de=request.user,
                                                       acordat_catre__id=key.split('_')[1]).first()
                if nota_acordata:
                    nota_acordata.nota = request.POST.get(key)
                    nota_acordata.save()

                else:
                    Punctaj.objects.create(acordat_de=request.user,
                                           acordat_catre_id=key.split('_')[1],
                                           nota=request.POST.get(key))

                    messages.success(request, "Successfully Voted")
        return redirect('home')

    for user in data['users']:
        suma = Punctaj.objects.filter(acordat_catre=user).aggregate(punctaj=Sum('nota')).get("punctaj")
        count = Punctaj.objects.filter(acordat_catre=user).count()
        if not suma:
            result = 0
        else:
            result = int(suma)/count
        data['scoruri'][user] = result

        # sorted(data['scoruri'].items())
        # rezultate = sorted(data['scoruri'].items(), key=operator.itemgetter(1))
        print(type(data['scoruri']))
    return render(request, "login/home.html", data)

template
{{ scoruri }}
<!--{{ rezultate }}-->

<!--{% for key, value in scoruri %}-->

       <!--{{ key }}:{{ value }}-->

<!--{% endfor %}-->

A: You should use OrderedDict which preserves insertion order instead of dict. https://docs.python.org/2/library/collections.html
from collections import OrderedDict

def home(request):
    data = dict()
    data['users'] = User.objects.all()
    data['scoruri'] = dict()

    if request.method == "POST":
        for key in request.POST:
            if 'nota_' in key:
                nota_acordata = Punctaj.objects.filter(acordat_de=request.user,
                                                       acordat_catre__id=key.split('_')[1]).first()
                if nota_acordata:
                    nota_acordata.nota = request.POST.get(key)
                    nota_acordata.save()

                else:
                    Punctaj.objects.create(acordat_de=request.user,
                                           acordat_catre_id=key.split('_')[1],
                                           nota=request.POST.get(key))

                    messages.success(request, "Successfully Voted")
        return redirect('home')

    for user in data['users']:
        suma = Punctaj.objects.filter(acordat_catre=user).aggregate(punctaj=Sum('nota')).get("punctaj")
        count = Punctaj.objects.filter(acordat_catre=user).count()
        if not suma:
            result = 0
        else:
            result = int(suma)/count
        data['scoruri'][user] = result

        # sorted(data['scoruri'].items())
        # sorting and puting result into OrderedDict
        data['scoruri'] = OrderedDict(sorted(data['scoruri'].items(), key=operator.itemgetter(1)))
        print(type(data['scoruri']))

    return render(request, "login/home.html", data)

And in template
{% for key, value in scoruri.items %}
    {{ key }}:{{ value }}
{% endfor %}

A: You can't sort a dictionary, you can sort representation of a dictionary. Dictionary has a random ordered members.
You can make list of tuples from a dict members:
import operator
dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))

I hope this helps.


text:
Q: Grid VS Cloud Architecture? From reading on the Internet it seems to me that Grids are peer to peer systems while the cloud is (at least in most cases) a client-server system. Yet I haven't seen this point beeing made. Am I incorrect in thinking this?
From most Grid examples I have seen, several computers provide and request data from each other. Hence they act both as clients and servers (peers). Most cloud examples I have seen are simply companies offering resources (processing resources) to clients. It might be that the server in a cloud service uses something more complicated, like for example a grid, but it still seems like a client-server architecture to me.
So my question is:
Is the grid a p2p system while the cloud is a client-server system?

A: Short answer:
1st part: NO: Grid applications typically are not P2P.
2nd part: YES: Cloud is a client-server system.
Longer answer:
1st part: A grid application typically (but not exclusively) consists of a mass of client applications distributed to and executed on the individual computers making up the "grid". The work load of these clients is typically controlled by one (or more) central servers who segment and parcel the overall workload into pieces to be executed by one or more of the grid nodes. Thsese central instances also collect back the results provides by the external nodes.
2nd part: From point of view of an application or user connecting to a cloud (SaaS) application, SaaS indeed looks like a C/S application. Note that the architecture WITHIN the cloud application (everything behind the IP address endpoint) is COMPLETELY DIFFERENT from a typical three tier C/S application.


text:
Q: Output a String that has the categorical value of the final sum seperated out? Say I have a field [Client] which is either Yes/No
Then I Sum on [NumberOfAccounts]
But on my map I want a string that says "Clients: 23 Prospects: 11 Total: 33"
How do I do that with a calculated field??

A: Assuming you have one record, i.e. row of data per account, and an account is either a client or prospect depending on the value of the [Client] field. Further recommend you change Client to a Boolean valued field, taking on either True or False, instead of using a string, and finally assuming you rename the field [Client?]
Give all that, you define a calculated field called [Clients] as
INT([Client?])

And then you can put SUM([Clients]) on the Text/Label shelf to get the number of clients.
Likewise, you can define a calculated field called [Prospects] as
INT(NOT [Client?])

And also put SUM([Prospects]) on the Text/Label shelf.
This works because the type conversion function INT() converts True to 1 and False to 0. Then the SUM() function effectively counts the number of records that satisfy the Boolean condition.
Finally, also add SUM([Number of Records]) to Text/Label.
Once the measures are included in text or label, you can edit the label text by clicking on the Text/Label button on the marks card to add the surrounding strings.
BTW, The button is called either Text or Label depending on your choice of mark type.


text:
Q: jquery, js, jsp: //make text inside inputbox (or any other idea/suggestion beside input box) clickable

<input id= "eurl" type="text" name="eurl" readonly>

I have a input box which is dynamic (meaning I am getting values in text box from DB), right now the value inside text box are text (they are not responsive). What I was trying to get is make any text inside my textbox as a link (clickable). Also please consider that it does not have to be just  inputbox, is there anyway that I can make text as a link.
  //make text(coming form db) inside inputbox clickable/act as a url
.

A: I am not so sure of what end result you want but you can try to wrap your input box within a  tag that has a href to your link.

   <input type="text" value="google.com" />

To get the value from DB, you will need additional codes. For instance in PHP:
foreach($data as $value){
   echo '
           <input type="text" value="'+$value['link']+'" />
         '
}

Or you can do additional Javascript to map the values. You can even push the href in to the element attribute.

   <input id="inputWithLink" type="text" value="google.com" />

Or push in by getting the text input value:
var inputLink = document.getElementById('inputWithLink').value;
document.getElementById('justALink').setAttribute('href', inputLink);


text:
Q: Why do "f" and "g" ASCII characters turn negative in this code? #include <stdio.h>

/*************** CAESAR CYPHER *****************

  -Take a charater array input
  -Loop through 26 character shifts
  -Print all possibilities

************************************************/

void Brute_Force(char *message)// Character array pointer
{
    char *i;// Copy message for iteration: Stop at '/0'
    int j;// Iterate through the alphabet
    char t;//Temp variable for current letter

    for(j = 0; j < 26; j++)
    {
        printf("\n----------Shift %i----------\n", j);//Aesthetics

        for(i = message; *i != '\0'; i++)
        {
            //Multiple of 26 to start at original message
            unsigned char t = ((*i + j)%26) + 104;

            // Only loop 97 to 122. ASCII 'a'-'z'
            if(t > 122){t = t - 26;}
            printf("%c", t);
        }
    }
}

int main()
{
    char mess[26] = "ynkooejcpdanqxeykjrbdofgkq";
    Brute_Force(mess);
    return 0;
}

Before changing t to an unsigned char instead of a regular char, every time 'f'(102) or 'g'(103) would come up, it would output t = -127/-128 instead of 127/128. I'm just wondering what would have caused it to change to negative. It was only for 'f' and 'g', every other letter was correct.
a sample output would be:
ynkooejcpdanqxeykjrbdo��kq


text:
Q: Django 1.10 - Create two formsets from single queryobject I have Book model, which has title, and author string fields. title fields may be different, but author is always equal to joey or martin.
On a single page, I want to display two formsets, BUT I don't want to create QuerySet and make DB query separately for each form. Is it possible to, get all the objects at once, and then split them into separate lists and pass them info formset?
My view function:
def index(request):

    books = Book.objects.all()  # Here we will take all at once

    joey_books = []
    martin_books = []

    for book in books:  # books here are evaluated - only once!
        if book.author == 'joey':
             joey_books.push(book)
        elif book.author == 'martin':
             martin_books.push(book)

    joey_book_formset = forms.modelformset_factory(
        Book,
        form=BookForm,
        fields=['title', 'author'],
        can_delete=True, extra=1
    )

    joey_book_formset = joey_book_formset(queryset=joey_books)  # Exception raised

    martin_book_formset = forms.modelformset_factory(
        Book,
        form=BookForm,
        fields=['title', 'author'],
        can_delete=True, extra=1
    )

    martin_book_formset = martin_book_formset(queryset=martin_books)  # Exception raised

    context = {
        'joey_forms': joey_book_formset,
        'martin_forms': martin_book_formset,
    }

    return render(request, 'myapp/index.html', context)

My expectation:
Two formsets would be created and there would be running just one query.
Problem:
Following exception is raised:

AttributeError: 'list' object has no attribute 'ordered'

It is probably because formsets accept only QuerySet objects. Is there any workaround for this? Imagine I have like 50 forms on single page.. I dont want to run 50 separate queries for each formset.


text:
Q: WP WPQuery, not running properly in WP CLI I'm running a simple query just to find simple WooCommerce products, here is the query which works fine in the header of the site:
$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_type',
            'field' => 'slug',
            'terms' => array('simple')
        ),
    ),
);

$simpleProducts = new WP_Query($args);

This query returns 1065 products which are correct. If I run the same query through a WP CLI command, I get 0 posts... however, if I remove the tax query it's returns all the products on the site.
Here is the command that runs:
// Add the command.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
   \WP_CLI::add_command('update-stock', \stockChecker::syncStockFile());
}

Has anyone had this issue with WP CLI?
EDIT
To add, this runs fine:
$args = array(
    'post_type' => 'product_variation',
    'posts_per_page' => -1,
);

$products = new WP_Query($args);


text:
Q: How do I call an anonymous function inside Enum.map I am learning Elixir and I am working on Project Euler to try to strengthen my skills in Elixir. Right now I have this code
fib = fn
  a,b,0 -> a
  a,b,n -> fib.(b, a+b, n-1)
end
IO.puts Enum.sum(Enum.filter(Enum.map(1..50, fn n -> fib.(0,1,n) end), even and fn(x) -> x < 4000000 end))

But when I run this code I get:
undefined function fib/0
(elixir) src/elixir_fn.erl:33: anonymous fn/3 in :elixir_fn.expand/3
(stdlib) lists.erl:1238: :lists.map/2
(stdlib) lists.erl:1238: :lists.map/2
(elixir) src/elixir_fn.erl:36: :elixir_fn.expand/3

How do I fix this?

A: Elixir does not allow defining anonymous recursive functions at this moment. You have 2 options: define a normal function using def inside any module, or use the following trick (hack?) to make kind of anonymous recursive functions:
fib = fn
  fib, a, b, 0 -> a
  fib, a, b, n -> fib.(fib, b, a+b, n-1)
end

IO.puts Enum.sum(Enum.filter(Enum.map(1..50, fn n -> fib.(fib, 0, 1, n) end), fn(x) -> rem(x, 2) == 0 && x < 4000000 end))

I would recommend defining this function in a module instead of using this hack:
defmodule Fib do
  def fib(a, _b, 0), do: a
  def fib(a, b, n), do: fib(b, a + b, n - 1)
end

IO.puts Enum.sum(Enum.filter(Enum.map(1..50, fn n -> Fib.fib(0, 1, n) end), fn(x) -> rem(x, 2) == 0 && x < 4000000 end))

Note: there was also a syntax error in the second argument to Enum.filter/2 which I've fixed (hopefully correctly).
Tip: please read about the pipe operator to make the IO.puts code more idiomatic: http://elixir-lang.org/getting-started/enumerables-and-streams.html#the-pipe-operator


text:
Q: Парсинг pdf - файлов на c++ Всем доброго времени суток!
На днях получил задание - написать программу на c++, осуществляющую парсинг пдф файла, которая вытаскивает автора, название и краткую аннотацию из файла (который подразумевает под собой какую-нибудь статью)
Начал гуглить и яндексить сразу и на всех языках) На наших форумах такие вопросы остаются без ответов.. (надеюсь не в этот раз!), на англоязычных форумах нужной информации тоже не нашёл. В общем, ни как парсить пдф, ни как парсить на с++ - так и не понял...
Если вдруг кто-то поможет разобраться с заданием, объяснит, как можно парсить текстовые пдф-файлы на с++  - буду категорически признателен!
(Если кто-то и с заданием поможет - с меня пивко) :)

A: С помощью библиотеки QPDF например так:
https://github.com/qpdf/qpdf
#include <iostream>
#include <string.h>
#include <stdlib.h>

#include <qpdf/QPDF.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QIntC.hh>

static char const* whoami = 0;

void usage()
{
    std::cerr << "Usage: " << whoami << " filename page-number" << std::endl
          << "Prints a dump of the objects in the content streams"
              << " of the given page." << std::endl
              << "Pages are numbered from 1." << std::endl;
    exit(2);
}

class ParserCallbacks: public QPDFObjectHandle::ParserCallbacks
{
  public:
    virtual ~ParserCallbacks()
    {
    }

    virtual void contentSize(size_t);
    virtual void handleObject(QPDFObjectHandle, size_t offset, size_t length);
    virtual void handleEOF();
};

void
ParserCallbacks::contentSize(size_t size)
{
    std::cout << "content size: " << size << std::endl;
}

void
ParserCallbacks::handleObject(QPDFObjectHandle obj,
                              size_t offset, size_t length)
{
    std::cout << obj.getTypeName() << ", offset=" << offset
              << ", length=" << length << ": ";
    if (obj.isInlineImage())
    {
        std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << std::endl;
    }
    else
    {
        std::cout << obj.unparse() << std::endl;
    }
}

void
ParserCallbacks::handleEOF()
{
    std::cout << "-EOF-" << std::endl;
}

int main(int argc, char* argv[])
{
    whoami = QUtil::getWhoami(argv[0]);

    // For libtool's sake....
    if (strncmp(whoami, "lt-", 3) == 0)
    {
    whoami += 3;
    }

    if (argc != 3)
    {
    usage();
    }
    char const* filename = argv[1];
    int pageno = QUtil::string_to_int(argv[2]);

    try
    {
    QPDF pdf;
    pdf.processFile(filename);
        std::vector<QPDFPageObjectHelper> pages =
            QPDFPageDocumentHelper(pdf).getAllPages();
        if ((pageno < 1) || (QIntC::to_size(pageno) > pages.size()))
        {
            usage();
        }

        QPDFPageObjectHelper& page = pages.at(QIntC::to_size(pageno-1));
        ParserCallbacks cb;
        page.parsePageContents(&cb);
    }
    catch (std::exception& e)
    {
    std::cerr << whoami << ": " << e.what() << std::endl;
    exit(2);
    }

    return 0;
}


text:
Q: Edit form rendered blank My model/id/edit form is rendered blank, without rendering the values that are already in the database. I don't see this is the regular behaviour in a brand new rails app.
Any insights what's blocking those values to be rendered in the form?
Rails 6.1.4
ruby 2.7.3p183
_form.html.erb
<%= form_with(model: task) do |form| %>
  <%= render "shared/error_messages", resource: form.object %>

    <%= form.label :title %>
    <%= form.text_field :title, class: "form-control", prepopulated: "true", :value => params[:title] %>

    <%= form.label :description %>
    <%= form.rich_text_area :description, data: { controller: "mentions", mentions_target: "field" }, class: "form-control", :value => params[:description] %>

    <%= form.label :credits %>
    <%= form.number_field :credits, class: "form-control", :value => params[:credits] %>

    <%= form.label :category %>
    <%= form.select :category,  [ 'Development', 'Design' ], class: "form-control", :value => params[:category] %>

  <% if current_user.admin === true %>
    <%= form.collection_check_boxes(:user_ids, User.where(id: 1).all, :id, :name) do |u| %>
      <%= u.label(class: "check_box") { u.check_box(checked: true, class: "add_margin") + u.text } %>
    <% end %>
  <% end %>

    <%= form.button class: "btn btn-primary" %>

    <% if form.object.persisted? %>
      <%= link_to t("delete"), form.object, class: "btn btn-danger outline", method: :delete, data: { confirm: t("are_you_sure") } %>
    <% end %>

<% end %>

Controller
class TasksController < ApplicationController
  before_action :set_task, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!
  before_action :load_entities, only: :show

  # GET /tasks/1/edit
  def edit
  end

  # PATCH/PUT /tasks/1 or /tasks/1.json
  def update
    respond_to do |format|
      if @task.update(task_params)
        format.html { redirect_to @task, notice: "Task was successfully updated." }
        format.json { render :show, status: :ok, location: @task }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_task
    @task = Task.find(params[:id])
    puts @task
    puts @task.id
  end

  # Only allow a list of trusted parameters through.
  def task_params
    params.require(:task).permit(:title, :description, :credits, :deliverydate, :submitteddate, :createdby, :default, :status, :category, :assignedto, user_ids: [])
  end

end

Edit:
Adding trace for set_task , example when opening the Edit form for Task ID 7
10:30:24 web.1     |   ↳ app/controllers/tasks_controller.rb:91:in `set_task'
10:30:24 web.1     | #<Task:0x000000010d75ddf8>
10:30:24 web.1     | 7
10:30:24 web.1     |   Rendering layout layouts/application.html.erb


text:
Q: Extracting the top match from string comparison in R I am currently using the 'agrep' function with 'lapply' in a data.table code to link entries from a user-provided VIN# list to a DMV VIN# database. Please see the following two links for all data/code so far:
Accelerate performance and speed of string match in R
Imperfect string match using data.table in R
Is there a way to extract the "best" match from my list that is being generated by:

dt <- dt[lapply(car.vins, function(x) agrep(x,vin.vins, max.distance=c(cost=2, all=2), value=T)), list(NumTimesFound=.N), vin.names]

because as of now, the 'agrep' function gives me multiple matches, even with a lot of modification of the cost, all, substitution, ect. variables.
I have also tried using the 'adist' function instead of 'agrip' but because 'adist' does not have an option for value=TRUE like 'agrep', it throws out the same
Error in `[.data.table`(dt, lapply(vin.vins, function(x) agrep(x,car.vins,  :
x.'vin.vins' is a character column being joined to i.'V1' which is type 'integer'.
Character columns must join to factor or character columns.

that I was receiving with the 'agrep' before.
Is there perhaps some other package I could use?
Thanks!

A: Tom, this isn't strictly a data.table problem.  Also, it's hard to know exactly what you want without having the data you are using.  I tried to figure out what you want, and I came up with this solution:
vin.match <- vapply(car.vins, function(x) which.min(adist(x, vin.vins)), integer(1L))
data.frame(car.vins, vin.vins=vin.vins[vin.match], vin.names=vin.names[vin.match])
#   car.vins vin.vins vin.names
# 1  abcdekl   abcdef     NAME1
# 2   abcdeF   abcdef     NAME1
# 3  laskdjg  laskdjf     NAME2
# 4  blerghk  blerghk     NAME3

And here is the data:
vin.vins <- c("abcdef", "laskdjf", "blerghk")
vin.names <- paste0("NAME", 1:length(vin.vins))
car.vins <- c("abcdekl", "abcdeF", "laskdjg", "blerghk")

This will find the closest match for every value in car.vins  in vin.vins, as per adist.  I'm not sure data.table is needed for this particular step.  If you provide your actual data (or a representative sample), then I can provide a more targeted answer.


text:
Q: Access search index by cloudant-client api I have a document in cloudant server as:
 {
  "_id": "web",
  "_rev": "11-b1d0e315272a87c2549df4004d836049",
  "min_weight": 40,
  "max_weight": 65,
  "min_length": 1,
  "max_length": 2.2,
  "attributeCollection": {
    "attributeArray": [
      {
        "updateable": false,
        "lookup": "issuetype",
        "issueAttributeDefinitionId": 13,
        "attributeType": 1,
        "name": "web issue",
        "value": [
          "Improper Neutralization of Input During Web Page Generation"
        ]
      }
    ]
  },
}

I created search index for "name" and "value" in documents as:
function (doc) {
   if (doc.attributeCollection && doc.attributeCollection.attributeArray) {
      for (var i=0; i<doc.attributeCollection.attributeArray.length; i++) {
         if (doc.attributeCollection.attributeArray[i].name) {
            index("name", doc.attributeCollection.attributeArray[i].name, { store : true });
         }
            if (doc.attributeCollection.attributeArray[i].value) {
            for (var j=0; j<doc.attributeCollection.attributeArray[i].value.length; j++) {
               index("value", doc.attributeCollection.attributeArray[i].value[j], { store : true });
            }
         }
      }
   }
}

and I have successfully performanced the query (https://xxx.cloudant.com/issuedb/_design/searchJson/_search/newSearch?limite=10&include_docs=true&q=name:"web*")in browser to get the result. Moreover, I want to get the results by cloudant-client api. The below is my code
CloudantClient client=new CloudantClient("xxx", "xxx", "xxx" );
System.out.println("Connection successful! "+client.getBaseUri());
Database db=client.database("issuedb", true);
System.out.println("Datase available - "+db.getDBUri());

List<issue> issues=db.search("searchJson/newSearch")
.limit(10).includeDocs(true)
.query("name=\"web*\"", issue.class);

for (int i = 0; i < issues.size(); i++) {
    issue iss=issues.get(i);
    System.out.println(iss.getId());
    System.out.println(iss.getName());
    System.out.println(iss.getValue());
}

But it can not get the result as search query in browser (Data and index connection are also checked, it is fine). What is the mistake in this code.

A: Search indexes are queried using Lucene Query Parser Syntax. try using a colon instead of the equal sign:
List<issue> issues=db.search("searchJson/newSearch")
.limit(10).includeDocs(true)
.query("name:\"web*\"", issue.class);

More Info:
Cloudant Search
Lucene Query Parser Syntax


text:
Q: Image loading time (Next.js) I currently have a problem with the loading time of images using the builtin provided in Next js. I tried different options even when running it in production, the image loading time remains long (several seconds). Does anyone among you encounter this problem.
I am well aware that the first loading of the image can be long since there is a processing and caching on it. However this problem can appear even when the image is already cached.
<Image
  className="absolute inset-0 h-full w-full"
  src="/imgs/myimage.jpg"
  layout="fill"
  objectFit="cover"
  alt=""
/>


text:
Q: Quickly Rename Current Workspace I can rename my workspace by going into my WorkSpace Switcher Preferences:

Does anyone know a quicker way to rename my current workspace (Maybe something with GnomeDo)?

A: If you're using metacity, you could edit or create a bash script to edit it directly in gconf I guess:
~/.gconf/apps/metacity/workspace_names/%gconf.xml

A: Currently this is the fastest way. Maybe you might be better off reporting a wishlist item against Synapse (GNOME-Do was replaced by that).


text:
Q: Need to save textArea value in file using javascript (.sql file Extension) Try to save textarea value in sql file (.sql file extension) but it's not working.
if change type: 'text\plain than save in .txt file but
type: 'application\sql' than not save with .sql file extension

Text to Save:

            <textarea id="inputTextToSave" cols="80" rows="25"></textarea>

        Filename to Save As:
        <input id="inputFileNameToSaveAs"></input>
        <button onclick="saveSqlAsFile()">Save Text to File</button>

>

A: Simply add the extension to the file name:
function saveSqlAsFile() {
    var textToSave = document.getElementById("inputTextToSave").value,
        textToSaveAsBlob = new Blob([textToSave], { type: "application/sql" }),
        textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob),
        fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value,
        downloadLink = document.createElement("a");

    downloadLink.download = fileNameToSaveAs + ".sql";
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}


text:
Q: python beginner syntax statement if-elif I'm learning python, and I'm trying with a set of exercises, but I'm stuck on the next one:
     inp_1 = input('your score between 0.0 and 1.0')

        try:
score = float(inp_1)
if 0.9 <= score <= 1.0:
              print ("A")    elif score >= 0.8:
              print ("B")    elif score >= 0.7:
              print ("C")    elif score >= 0.6:
              print ("D")    elif score <  0.6:
              print ("Your grade is an F")
    else:
print ('your score is more than 1.0')
    except:
 print ('invalid input, please try with a number')

but I'm get the next message error:
IndentationError: unindent does not match any outer indentation level on line 7 elif score >= 0.8: ^ in main.py

A: The indentation (= number of tabs / spaces in front of each line) is important in python. The code you posted isn't indented properly. A correct indentation would look like this:
inp_1 = input('your score between 0.0 and 1.0')

try:
    score = float(inp_1)
    if 0.9 <= score <= 1.0:
        print ("A")
    elif score >= 0.8:
        print ("B")
    elif score >= 0.7:
        print ("C")
    elif score >= 0.6:
        print ("D")
    elif score <  0.6:
        print ("Your grade is an F")
    else:
        print ('your score is more than 1.0')
except:
    print ('invalid input, please try with a number')

The first line is always un-indented. When starting a block (e.g. try:, if:, elif:, ...), all following lines that belong within this block are indented with 4 spaces more than the opening line. "Closing" a block is done by writing the next statement with less indentation.
Another example:
if False:
    print(1)
    print(2)
# prints nothing because both print statements are part of the if condition

if False:
    print(1)
print(2)
# prints 2 because the `print(2)` statement is not part of the if condition

Does this answer your question?

A: Your indentations should be like this:
inp_1 = input('your score between 0.0 and 1.0')
try:
    score = float(inp_1)
    if 0.9 <= score <= 1.0:
        print ("A")
    elif score >= 0.8:
        print ("B")
    elif score >= 0.7:
        print ("C")
    elif score >= 0.6:
        print ("D")
    elif score <  0.6:
        print ("Your grade is an F")
    else:
        print ('your score is more than 1.0')
except:
    print ('invalid input, please try with a number')

I think you didn't understand indentations fully. This isn't like any other languages. You need to make indentations correctly.
Hope it will help you


text: Q: Is it possible to use ubuntu with fedora kernel? Ubuntu/mainline kernel have acpi problems with my notebook's firmware but fedora hasn't. I think it is patched or something, however I hate fedora and I would like to use Ubuntu with this kernel. Is it possible?


text:
Q: list length + string formatting + python How would one change the string "Point" to be a variable input (string)?
result = []
list =  [[a,b,c,d][a,b,c,d]]

result.append( [["Point {}".format(i) for i in range(1, len(sub)+1)] for sub in list])

I basically dont want to use string "Point" as a constant but rather as another parameter value. I tried this:
result = []
list =  [[a,b,c,d][a,b,c,d]]
p_name = "Number"

result.append( [[p_name, {}.format(i) for i in range(1, len(sub)+1)] for sub in list])

I would like to end up with:
result = [[Number 1, Number 2, Number 3, Number 4][Number 1, Number 2, Number 3, Number 4]]

Thank you,

A: result.append( [["{} {}".format(p_name, i) for i in range(1, len(sub)+1)] for sub in list])


text:
Q: Sum based on two flags I need your help. I have a data with one numeric field and two flags.
I want to sum the numeric filed based on two flags .
In the below data :
I want to calculate sum between FLAG1 and FLAG2.  But when the FLAG2 is TRUE then the next FLAG1 row value should be made TRUE and before any FLAG2 is true , FLAG one should be considered as False.
nf<-c(10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,180,190,200,210,220,230,240,250)
Flag1 <- c('FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE')
Flag2 <- c('FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE')

abc <- as.data.frame(cbind(Flag1,Flag2,nf))

Output I am looking for is  :
numeric field sum of 300,910 and 1890.
60+70+80+90 =300 100+110+120+130+140+150+160 After the second flag value is TRUE, firstflag next row value should become true and any subsequent value which is true in flag 1 should turn to false.
please guide.
Regards, Rohit

A: I'm not sure this is what you need, but thought it might be helpful.
First, as mentioned by @akrun, TRUE and FALSE are logical vectors and don't need to be put in quotes as strings. I converted them to logical values for this example.
This solution uses tidyverse. You can flip your Flag1 values in preceding or subsequent rows as you described using lead and lag. Using slice you can start your sums beginning with the first TRUE in Flag1. Using cumsum you can number your groups that always end with Flag2 being TRUE.
nf<-c(10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250)

Flag1 <- c('FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE',
           'FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE')
Flag2 <- c('FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE',
           'FALSE','FALSE','FALSE','TRUE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','FALSE','TRUE')

Flag1 <- Flag1 == 'TRUE'
Flag2 <- Flag2 == 'TRUE'

abc <- data.frame(Flag1,Flag2,nf)

library(tidyverse)

abc %>%
  mutate(Flag1 = if_else(lag(Flag2), TRUE, Flag1),
         Flag1 = if_else(lead(Flag2), FALSE, Flag1)) %>%
  slice(match(TRUE, Flag1):n()) %>%
  group_by(grp = cumsum(lag(Flag2, default = 0))) %>%
  summarise(sum = sum(nf))

# A tibble: 3 x 2
    grp   sum
  <dbl> <dbl>
1     0   300
2     1   910
3     2  1890