error "Could not resolve all files for configuration ':app:debugCompileClasspath'."

Question: I keep changing so many things in my Gradle files and nothing is working so far please help, when I click to run my app on the emulator this is the error I get.
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:debugCompileClasspath'.
build.gradle(:app)
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
}

android {
    namespace 'com.example.mechanicsapp'
    compileSdk 33
    buildToolsVersion "30.0.3"
    buildFeatures {
        dataBinding true
        viewBinding true
        compose true
    }

    defaultConfig {
        applicationId "com.example.mechanicsapp"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }

}

dependencies {

    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.6.0'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3'
    implementation 'androidx.navigation:navigation-ui-ktx:2.5.3'
    implementation "androidx.compose.ui:ui:1.3.3"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
    implementation 'androidx.activity:activity-compose:1.6.1'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    implementation "androidx.core:core-ktx:1.9.0"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.21"

    //dependencies
    //material design
    implementation 'com.google.android.material:material:1.7.0'
    //circle image view
    implementation 'de.hdodenhof:circleimageview:3.1.0'
    //scalable unit text size
    implementation 'com.intuit.ssp:ssp-android:1.0.6'
    //scalable unit size
    implementation 'com.intuit.sdp:sdp-android:1.0.6'
    //room database
    implementation 'androidx.room:room-runtime:2.5.0'
    kapt 'androidx.room:room-compiler:2.5.0'
    implementation 'androidx.room:room-ktx:2.5.0'
    implementation 'com.makeramen:roundedimageview:2.3.0'
    //crop image library
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
    //easy permission
    implementation 'pub.devrel:easypermissions:3.0.0'
    //coroutines core
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'

}

build.gradle(Mechanics App)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.4.0' apply false
    id 'com.android.library' version '7.4.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.21' apply false
}

repositories {
    google()
    mavenCentral()
    maven { url 'https://maven.google.com' }
}

settings.gradle (MechanicsApp)
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}
rootProject.name = "Mechanics App"
include ':app'

Comment: what is your gradle version?
Answer: So in platforms/android/build.gradle file,it should be something like this:
  buildscript {

    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.3.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}


How to use a function to open a csv and convert it to a dictionary?

Question: I am having trouble calling the function I made to open a CSV file. I am getting an error:

AttributeError: 'function' object has no attribute 'keys'.

In my for loop it won't load the load_dict I created from the function. Any help is appreciated! Please go easy, I am a beginner.
import csv

invest_dict = 'DOW_Stock_short.csv'

def load_dict():
    with open(invest_dict , 'r') as invest_obj:
        invest_reader = csv.reader(invest_obj)
        result = {}
        for row in invest_reader:
            if invest_reader.line_num !=1:
                key = row[0]
                result[key] = float(row[1])
        return(result)

print("The purpose of this project is to provide Stock Analysis by reading \n the data from a csv file and performing analysis on this data.")

def Greeting():
    print(".........Welcome.............")

def Conversions(investment_amount):

    investment_amount = float(investment_amount)

    Euro = float(round(investment_amount / 1.113195,2) )
    Pound = float(round(investment_amount / 1.262304,2) )
    Rupee = float(round(investment_amount / 0.014316,2) )

    print("The amount you invest in euro is:  {:.2f}" .format(Euro) )
    print("The amount you invest in pounds is:  {:.2f}" .format(Pound) )
    print("The amount you invested in Rupees is:  {:.2f}" .format(Rupee) )

def minimum_stock():
    key_min = min(load_dict.keys(), key = (lambda k: load_dict[k]))
    print("The lowest stock you can buy is: ",load_dict[key_min])

def maximum_stock():
    key_max = max(load_dict.key(), key = (lambda k: load_dict[k]))
    print("The highest stock you may purchase is: ",load_dict[key_max])

def invest_range(investment_amount):
    new_list = []
    new_list = [i for i in load_dict if i >=50 and i <=600]
    return(sorted(new_list))

answer = 'yes'

while answer:

print(Greeting())

try:
    investment_amount = float(input("Please enter the amount you want to invest:$ "))
    print("Thank you for investing:$ {:,.2f}".format(investment_amount))
except:
    print("Please enter a valid amount...")
    continue

print(Conversions(investment_amount))

for i in load_dict():
    i = investment_amount
    if i <25:
        print("Not enough funds to purchase stock")
        break
    elif i>25 and i <250:
        print(minimum_stock())
        break
    elif i >= 250 and i <= 1000:
        print(maximum_stock())
        break

print("This is the range of stocks you may purchase: ", invest_range(investment_amount))

answer = input("Would you like to complete another conversion? yes/no " )
if answer == 'no':
    print("Thank you for investing.")
    break

I want the output to display the contents of the dictionary depending on what the user inputs. error message:

AttributeError: 'function' object has no attribute 'keys'
Comment: Is your code after `while` indented properly?
Comment: `load_dict()` has no input parameters, how should it know what to load? Try to define it as `def load_dict(invest_dict):`
Comment: Yes, I added the input parameters and defined it as load_dict(invest_dict): and now I figured it out. Thank you for the help!
Answer: In brief: instead of appying the .keys() to the result of the function you are applying it to the function itself, and that is what the error says. Try to call the function instead:
# Wrong:
# load_dict.keys()

load_dict().keys()

This would (probably) solve your problem but from what I can see from the rest of your code, you use the function multiple times like you should use the result of it. So it's better to cache the result before using it:
load_dict = load_dict()

load_dict.keys()

Comment: I tried adding it and got this :'function' object is not subscriptable ???
Comment: Sorry for the late reply, but I added the load_dict(invest_dict) and got it to work for my functions. Thank you very much for your time and help! It was much appreciated!


Dovecot domain part empty

Question: I have a Postfix-Dovecot setup up and running. Today I added a new domain, so i had to change the mail setup to serve it. The Postfix installation is running well now: The mails are delivered to
/var/mail/<domain>/<userpart>

Unfortunately, Dovecot is not able to retrieve the domain-part and hence cannot get mails. I find messages like this in the logs:
Nov 12 10:58:10 gondwana dovecot: IMAP(so): mkdir(/var/mail//so/cur) failed: Permission denied

In the namespace part of dovecot, I have:
namespace private {
   separator = /
   prefix = INBOX/
   location = maildir:/var/mail/%d/%n
   inbox = yes
}

Any ideas=
Comment: Got the same problem and would very much like to hear the details of the resultion.
Answer: Your question seems incomplete, but I'm going to take a wild guess : you're not using virtual users, and not authenticating users with the domain part in their logins. Read this.
If this is not the right answer to your issue, then we're going to need more info. Are you using virtual users ? Can you post the relevant part of your config file ? What are the login for of your users ? user@domain ?
Comment: you're right, and I was able to solve it now, thanks.

Dovecot domain part empty


Update Access 2010 database in C#

Question: I'm going crazy about that,
I'm trying to save changes in a table in a Access 2010 .accdb database with c#
I have this method:
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + frmMain.dbPath + "; Persist Security Info=False;"))
{
    conn.Open();

    using (OleDbTransaction tx = conn.BeginTransaction())
    {
        using (OleDbCommand cmd = new OleDbCommand(
                "UPDATE Ricette SET " +
                    "Ricette.ResinaUreicaTotale = @ResinaUreicaTotale, " +
                    "Ricette.ResinaUreicaParziale = @ResinaUreicaParziale, " +
                    "Ricette.ResinaMelaminicaTotale = @ResinaMelaminicaTotale, " +
                    "Ricette.ResinaMelaminicaParziale = @ResinaMelaminicaParziale, " +
                    "Ricette.AcquaTotale = @AcquaTotale, " +
                    "Ricette.AcquaParziale = @AcquaParziale, " +
                    "Ricette.FarinettaTotale = @FarinettaTotale, " +
                    "Ricette.FarinaCoccoTotale = @FarinaCoccoTotale, " +
                    "Ricette.ComponenteATotale = @ComponenteATotale, " +
                    "Ricette.TempoMix = @TempoMix " +
                "WHERE Ricette.[Nome] = [@Nome];", conn))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Transaction = tx;
            using (OleDbDataAdapter ad = new OleDbDataAdapter(cmd))
            {
                try
                {
                    DataRow row = ds.Tables[0].Rows.Find(cmbIncollaggio.SelectedItem.ToString());
                    string[] ric = new string[1];

                    switch (cmbIncollaggio.SelectedItem.ToString())
                    {
                        case "IF20":
                            cmd.Parameters.Add("@Nome", OleDbType.VarChar, 100, "Nome").Value = "IF20";

                            cmd.Parameters.Add("@ResinaUreicaTotale", OleDbType.VarChar, 100, "ResinaUreicaTotale").Value = RUTEdit.Text;
                            frmMain.seriale.DataWrite("00WD", RUTEdit.Text, 2100);
                            ric = frmMain.seriale.DataRead("00RD", 2100, 1);
                            RUTLabel.Text = Convert.ToInt32(ric[0]).ToString();

                            cmd.Parameters.Add("@ResinaUreicaParziale", OleDbType.VarChar, 100, "ResinaUreicaParziale").Value = RUPEdit.Text;
                            frmMain.seriale.DataWrite("00WD", RUPEdit.Text, 2101);
                            ric = frmMain.seriale.DataRead("00RD", 2101, 1);
                            RUPLabel.Text = Convert.ToInt32(ric[0]).ToString();

                            cmd.Parameters.Add("@ResinaMelaminicaTotale", OleDbType.VarChar, 100, "ResinaMelaminicaTotale").Value = RMTEdit.Text;
                            frmMain.seriale.DataWrite("00WD", RMTEdit.Text, 2102);
                            ric = frmMain.seriale.DataRead("00RD", 2102, 1);
                            RMTLabel.Text = Convert.ToInt32(ric[0]).ToString();

                            cmd.Parameters.Add("@ResinaMelaminicaParziale", OleDbType.VarChar, 100, "ResinaMelaminicaParziale").Value = RMPEdit.Text;
                            frmMain.seriale.DataWrite("00WD", RMPEdit.Text, 2103);
                            ric = frmMain.seriale.DataRead("00RD", 2103, 1);
                            RMPLabel.Text = Convert.ToInt32(ric[0]).ToString();

                            cmd.Parameters.Add("@AcquaTotale", OleDbType.VarChar, 100, "AcquaTotale").Value = ATEdit.Text;
                            frmMain.seriale.DataWrite("00WD", ATEdit.Text, 2104);
                            ric = frmMain.seriale.DataRead("00RD", 2104, 1);
                            ATLabel.Text = Convert.ToInt32(ric[0]).ToString();

                            cmd.Parameters.Add("@AcquaParziale", OleDbType.VarChar, 100, "AcquaParziale").Value = APEdit.Text;
                            frmMain.seriale.DataWrite("00WD", APEdit.Text, 2105);
                            ric = frmMain.seriale.DataRead("00RD", 2105, 1);
                            APLabel.Text = Convert.ToInt32(ric[0]).ToString();

                            cmd.Parameters.Add("@FarinettaTotale", OleDbType.VarChar, 100, "FarinettaTotale").Value = FTEdit.Text;
                            frmMain.seriale.DataWrite("00WD", FTEdit.Text, 2106);
                            ric = frmMain.seriale.DataRead("00RD", 2106, 1);
                            FTLabel.Text = string.Format("{0,0}", Convert.ToInt32(ric[0]) / 10);

                            cmd.Parameters.Add("@FarinaCoccoTotale", OleDbType.VarChar, 100, "FarinaCoccoTotale").Value = FCTEdit.Text;
                            frmMain.seriale.DataWrite("00WD", FCTEdit.Text, 2107);
                            ric = frmMain.seriale.DataRead("00RD", 2107, 1);
                            FCTLabel.Text = string.Format("{0,0}", Convert.ToInt32(ric[0]) / 10);

                            cmd.Parameters.Add("@ComponenteATotale", OleDbType.VarChar, 100, "ComponenteATotale").Value = CATEdit.Text;
                            frmMain.seriale.DataWrite("00WD", CATEdit.Text, 2108);
                            ric = frmMain.seriale.DataRead("00RD", 2108, 1);
                            CATLabel.Text = string.Format("{0,0}", Convert.ToInt32(ric[0]) / 10);

                            cmd.Parameters.Add("@TempoMix", OleDbType.VarChar, 100, "TempoMix").Value = TMEdit.Text;
                            frmMain.seriale.DataWrite("00WD", TMEdit.Text, 2109);
                            ric = frmMain.seriale.DataRead("00RD", 2109, 1);
                            TMLabel.Text = Convert.ToInt32(ric[0]).ToString();
                            break;
                    }

                    ad.UpdateCommand = cmd;
                    ds.AcceptChanges();
                    ad.Update(ds);
                    tx.Commit();

                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    MessageBox.Show("Salvataggio non riuscito.\n" + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
    }

    conn.Close();
}

This code don't works... It works well in the dataset, but changes are not copied in the original database...
Could you find any errors?
Thank you for your help...
Answer: Solved!!!
Just add
cmd.ExecuteNonQuery();

and remove the DataAdapter object.

Update Access 2010 database in C#


The path is not a legal form

Question: It gives this error when debug..Button1 is about zip file,then copy it from source to destination..In delete function it deletes files which creation time older than the time that given..
Note: I'm quite new so please give lots of detail in your answer if possible.
private void button1_Click(object sender, EventArgs e)
{
    Backup._MAIN takeBackUp = new Backup._MAIN();
    try
    {
        takeBackUp.copyFile(textBox1.Text, textBox2.Text);
         MessageBox.Show("done");  //do stuff
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void button2_Click(object sender, EventArgs e)
{
    bool dater;
    string err = "";
    Backup._MAIN formDelete = new Backup._MAIN();
    DateTime dtp = dateTimePicker1.Value;
    dater = formDelete.deleteFiles(textBox3.Text, dtp,out err);
    if (err.Length > 0)
        MessageBox.Show(err);
    else
        MessageBox.Show("Done!");
}

Dll:
public void copyFile(string sSource,string sDestination)
{
    string sourcePath = sSource;
    string targetPath = sDestination;
    Directory.GetFiles(sourcePath,"",SearchOption.AllDirectories);

    string myBackUp="";
    string fileName;

    if (!System.IO.Directory.Exists(targetPath))
    {
        System.IO.Directory.CreateDirectory(targetPath);
    }

    using (ZipFile zip = new ZipFile(targetPath))
    {
        zip.AddDirectory(sourcePath, "");
        zip.Save(myBackUp);
    }

    if (System.IO.Directory.Exists(sourcePath))
    {
        string[] fileList = System.IO.Directory.GetFiles(sourcePath, "*.rar*");

        foreach (string files in fileList)
        {
            // from the path.
            fileName = System.IO.Path.GetFileName(files);
            targetPath = System.IO.Path.Combine(targetPath, fileName);
            System.IO.File.Copy(files, targetPath, true);
        }
    }
}

public bool deleteFiles(string sSource, DateTime dOlder, out string sError)
{
    string path = sSource;
    sError = "";
    try
    {
        string[] fileList = Directory.GetFiles(path);
        foreach ( string fname in fileList )
        {

            if ( File.GetCreationTime(path + fname) <= dOlder )
            {
                File.Delete(path + fname);
            }
        }
        return true;
    }

    catch ( Exception ex )
    {
        sError = ex.ToString();
        return false;
    }
}

Comment: _It puts the lotion in the basket or it gets the hose again_.  Can you reword your first paragraph, not sure what you mean
Comment: @MickyDuncan now I feel like some fava beans
Comment: Can you tell us what the actual question is? You just posted code and explained what it does..
Comment: I updated it...Question is in the title..The path is not a legal form...Both are them give the same error
Comment: i think your source path is not in a legal form - you should reformat it so that it is correct. If you want a more useful comment, provide the source paths you are using. Also, set breakpoints and step through the code.
Answer: Directory.GetFiles() returns full pathnames.
However, consider your code:
string[] fileList = Directory.GetFiles(path);

foreach ( string fname in fileList)
{
    if ( File.GetCreationTime(path + fname) <= dOlder)

You are prefixing the path when you do path + fname, which is going to result in an invalid path because fname already contains the path.
If the path includes a drive letter, such as C:\, then you'd end up with a path like C:\MyDir\C:\MyDir\MyFile.txt which will give you the error that you're seeing.
You just need to do File.GetCreationTime(fname) (and the same in File.Delete().
Comment: Yeah it worked! Thanks a lot.Could you find the problem in copyFile function?

The path is not a legal form


Ubercart: Attributes?

Question: I've got an existing cart and the inventory has separate products for different weights and they're separate entries. I want the varying weights to be combined and searched by attributes. What's the best way to do this with ubercart.
I'm using drupal 6 ubercart 2.
Answer: Ubercart 2.x has built in support for creating product classes with attributes. See the documentation for more information
Comment: When i create a class it creates a product type. that doesn't seem like what i wanted.
Comment: I don't suppose you read the documentation link I posted? It goes on to explain that after you create a class you can then create attributes. Attributes can be attached to classes. For instance, a clothing product class may have 'size' and 'colour' as attributes

Ubercart: Attributes?


Is this a way of defining "global variables" in C?

Question: Is this way of defining a "global variable" valid / a good approach?
While I would like this variable to be used whenever the header file is included to store program states.
/* global.h */
...
typedef struct {
    int some_count;
    ....
} ProgramState;

ProgramState *GetProgramState()
...

/* global.c */
...
#include "global.h"

ProgramState *GetProgramState()
{
    static ProgramState *prog_state = NULL;
    if (!prog_state) {
        prog_state = (ProgramState *) malloc(sizeof(ProgamState));
        *prog_state = (ProgamState) {
            .some_count = 1
        };
    }
    return prog_state;
}
...

/* main.c */
#include "global.h"

int main(void)
{
    GetProgramState()->some_count++;
    printf("%d\n", GetProgramState()->some_count);
    return 0;
}

While I know this way induced some overheads (while calling the method?), and there are ways like extern (using the extern way requires a specific initialize function).
Please let me know if there are other alternatives, thanks!
Comment: It's a viable technique, although you need locking as well as the static variable if you have multiple threads.
Comment: Looks OK to me. Resembles the "Singleton" design pattern
Answer: This is effectively an accessor. An accessor gives control over how a variable is accessed, allowing checks (e.g. validation) to be performed, and allowing the specific implementation of the variable to be changed. Using accessors is a common and perfectly acceptable programming paradigm.
As you mentioned, the alternative would be to access the variable directly. And while you could initialize it (contrary to what you said), it can only be initialized using a constant expression (e.g. NULL, but not malloc(sizeof(ProgamState))).
Comment: That `GetProgramState` is not able to control or check anything as it returns a pointer giving full access to the caller.
Comment: @Gerhardh You are mistaken. The caller can't change `prog_state` in the least. They can change `*prog_state`, sure, but that's not relevant to anything Isaid.
Comment: That is true if you assume it is all about `prog_state` inside that function. But from the given example I would say, it is about the data where it points to. This can be changed easily as demonstrated in `GetProgramState()->some_count++;`
Comment: Re "*That is true if you assume it is all about prog_state inside that function*". It is all about that, since that's all my answer mentioned. Anything else, such as what you are saying, is off-topic. Even the OP didn't ask for that.


sort nested struct single linked and double

Question: I have nested as:
typedef struct a{
    const char *        LongName;
    const char *        ShortName;
    int                 a;
    struct a    *       next;
}Level5;

typedef struct a1{
    const char *        LongName;
    const char *        ShortName;
    int                 frequency5;
    int                 id;
    Level5  *           linked;
    struct a1*          next_a1;
}Level4;

typedef struct a2{
    const char      *   Name;
    int                 frequency4;
    Level4      *       linked;
    int                 id;
    struct a2   *       next;
}Level3;

typedef struct a3{
    const char *        LongName;
    const char *        ShortName;
    int                 frequency3
    int                 id;
    Level3      *       linked;
}Level2;

typedef struct a4{
    const char *        LongName;
    const char *        ShortName;
    _Bool           top;
    int             id;
    int             frequency2;
    Level2      *   lined;
}Level1;

typedef struct cat{
    int         id;
const char  *   CatName;
Level1      *   linked;
}CAT;

CAT     total[256];

Now I want to sort the Linked nested structures structure as under:
 1. Level 5 -> LongName

 2. Level 4 -> ShortName

 3. Level 3 -> Name

 4. Level 2 -> Frequency3

               Level 1
                   |
                   | Level 2
     ====================================================
     | Level3         |Level3         |level 3
 =============
 |     next       next
level4 ->     lev4 ->   lev4
 |              |
 |                   =====================================
===============================       |
|       next        next           Level5 ->  level5  ->  level5
Level5  ->    Level5  ->  level5

Comment: Need clarification:  Are all items sorted by level first, then by specialty?
Comment: Are all level 5 items sorted by `LongName` even though they share common fields?
Comment: @ThomasMatthews First question answer is yes that is what I looking for. LongName is different in every structure. For install level5 abc then level4 def level3 ghi level2 jkl level1 xzy. Names may be same but values are different in each structure
Answer: Looks like you have the following data structure:
Level5 node --> Level5 node --> Level5 node
  |
  v
Level4 node --> Level4 node --> Level4 node
  |
  v
Level3 node --> level3 node --> Level3 node
  |
  v
Level2 node --> level2 node --> Level2 node

If this is the case, your data structure can be simplified:
struct Node
{
};

struct Node_Row
{
   unsigned int level;
   std::list<Node> nodes_in_row;
};

struct data_structure
{
   std::list<Node_Row> levels;
};

You should have one comparator function that sorts the rows and another that sorts the levels.
Also, since you tagged your question as C++, you should save yourself some troubles and use std::string instead of char *.  The std::string manages dynamic memory allocation and deallocation for you, whereas char * you have manage memory allocation and deallocation.
Comment: I have done some ascii art work to show the structures for better understanding


Let $X$ be the total number of heads and $Y$ be the difference between the total number of heads and the total number of tails. Find $\rho(X, Y )$

Question: A coin (with probability of getting head equal to $p$) is tossed twice. Let $X$ be the total number of heads and $Y$ be the difference between the total number of heads and the total number of tails. Find $\rho(X, Y)$.
Comment: Where are you stuck?
Comment: This cannot be: please indicate what you tried. (Or are you flatly using MSE as a site to quickly get fully written solutions to your homework? I hope not.)
Comment: Interesting: you flout spectacularly the rules of the site, you delete a previous comment of yours to which mine answered (better to erase your footsteps?), and you libel as *disturbance* my reminder... Let me note that **none** of your questions, so far, indicates **anything** about what you tried or what you know. Why is that?
Comment: Three comments by the OP now deleted by the OP.
Answer: If the coin is tossed twice, there are four possible outcomes, corresponding to the following values of $X$ and $Y$. (I take the definition of $Y$ to mean "number of heads (H) minus number of tails (T)")
<code>event  probability   X  Y
HH     pp            2  2
HT     p(1-p)        1  0
TH     (1-p)p        1  0
HH     (1-p)(1-p)    0  -2
</code>
To compute the correlation between $X$ and $Y$ (I assume that's what you mean by $\rho(X,Y)$), we observe that $E X = 2p^2+2p(1-p)=2p$, $E X^2 = 4p^2+2p(1-p)=2p(p+1)$ and thus
$$
\operatorname{Var} X = E X^2 - (E X)^2 = 2p(1-p).
$$
Similarly, one computes $E Y=2p^2-2(1-p)^2=2(2p-1)$, $E Y^2=4p^2+4(1-p)^2=8p^2-8p+4$, and thus
$$
\operatorname{Var} Y = E Y^2 - (E Y)^2 = -8p^2+8p=8p(1-p).
$$
One also computes that $EXY=4p^2$, and thus the covariance between $X$ and $Y$ is
$$
\operatorname{Cov}(X,Y) =E XY-E X EY = 4p^2 - 16p^2(1-p)^2.
$$
Finally, the covariance between $X$ and $Y$ becomes
$$
\rho(X,Y)=\frac{\operatorname{Cov}(X,Y)}{\sqrt{\operatorname{Var} X \operatorname{Var} Y}} = \frac{p \left(4p(2-p)-3\right)}{1-p}.
$$
Comment: I would have liked to comment to ask Bs11 what he has tried himself (herself), but my reputation doesn't seem to allow this. Hence the full answer. I agree that MSE should not be used to get full answers to homework questions.
Comment: Eckhard This is a friendly advice: when the OP forgets (or refuses) to show what they tried or what they know, one may prefer to provide hints rather than a full solution (I know, this is not always easy). To get the idea, you might wish to consult answers to other questions by same OP.


How to create UUID in JSNI of the input elements?

Question: How to create UUID in JSNI for each input element. Each time of call the id's of the input elements must change and new entries must be inserted in database with every new form.
Answer: Finally succeeded in doing so by getting the values directly in variable by
fname=a.value;
where a is the input box of jsni and fname is the variable where the value is being stored.


How do I enter these triplets into MuseScore?

Question:
I'm a total beginner with all things music theory, so I figured I'd ask.
I'm trying to enter this into MuseScore, but the triplets in the last two bars are confusing me. If I try to enter them I get these extra rests. What am I doing wrong?

Edit:
I am able to make desired triplets if I make some new measures in 2/2 and 4/4 time. But I'm wondering, why can't I make such a triplet in measure 52? 52 is in 2/2 time. All I can think of is that MuseScore doesn't like the staves changing time signatures separately. Any idea how to work around this? FYI: I am using MuseScore 3. I realize this is out of date, but I can't stand the way dynamics work in MuseScore 4.
Comment: I bet the problem has something to do with the fact that each staff changes time signature at a different moment.
Comment: I am equally confused. Entering these triplets should be straightforward: Select duraction 1/2 and press Ctrl+3 to enter a tuplet of total length 1/2. Then enter the first three notes. Then again select duration 1/2, press Ctrl+3, and enter the second group of notes. Could you possibly share with us step by step how you enter these tuplets, and when the problem starts to appear?
Comment: As Elements in Space implies, MuseScore may not be able to handle Strauss's unusual combination of time signatures. I wonder what Strauss thought he gained by writing the soprano in different time signatures from the orchestra here. (In the 2nd to 4th bars of the excerpt.)
Comment: That looks like what a less-than-smart DAW will do if the notes & score prefs aren't quantised
Comment: The software thinks you need an extra 1/16 + 1/64 + 1/256 + 1/1024 ≈ 1/12 of a measure in the "triplet tempo", which is equivalent to an extra 1/8 note in the "base tempo".  No idea why, though.
Comment: The problem seems to occur when you have two different time signatures at once and in one them, add a second voice (like you did in m. 51). For some reason the program allocates the wrong amount of "rest space" (perhaps confused by the time signature mix). Just play around a little and you should be able to correct the wrong spacing.
Answer: In short, this is a basic quarter-note triplet where the first two quarter notes of the triplet are combined into a single half-note value.
MuseScore's triplet function is based on making a triplet out of whatever note or rest value is currently highlighted. As such, because this is a triplet that takes up two quarter-note beats, you'll want to first highlight a half note (or half rest) before clicking the triplet option; note that the half rest is highlighted blue while I click triplet:

With the triplet now created, click on the half note to enter that first half note of the triplet:

The rest should be relatively straightforward to reach what you want:
Comment: I'm doing just that and it doesn't work. It works if I do that in a different measure, but for some reason not in the one I'm trying to do it in. Just to see what would happen, I tried making some measures in 4/4 and 2/2. When I made the triplets in those measures it worked perfectly. So I'm wondering, is the problem the fact that the staves in the score change time signatures at different times?
Comment: @AdrianD are you in note-inputted mode?


Telerik MVC Menu Control - Auto Width

Question: I am trying to use the Telerik MVC Menu control (as a button bar), but can't seem to be able to set the width to auto-generate.  What I mean is, the menu continues to the end of the DIV.  I would like the menu to only be as wide as the sum of the button widths.  Actually, the Telerik demo is doing the same thing as my menu is doing:
http://demos.telerik.com/aspnet-mvc/razor/menu/sitemapbinding
(Look at how the menu continues on to the right of "Other product lines").
Here is my menu:
    @{ Html.Telerik().Menu()
            .Name("case-history-button-menu")
            .ClientEvents(events => events.OnSelect("onCaseHistoryMenuBarSelect"))
            .Items(menu =>
            {
                menu.Add()
                    .Text("Add a Response").HtmlAttributes(new { id = "cases-history-addresponse" } ); @*Sets the ID HTML attribute so we can access it *@
                menu.Add()
                    .Text("Add a Comment").HtmlAttributes(new { id = "cases-history-button-addcomment" }); ;
                menu.Add()
                    .Text("Back to Cases").HtmlAttributes(new { id = "cases-history-button-back" }); ;
            })
            .Render();
    }

I do realize that I could just hard code my width ... but as I add or remove buttons (programatically) I want the menu to resize.
Answer: The Telerik MVC menu is rendered as an
 element. The latter has block display by default which means it occupies all the available space. You can override the display to "inline-block" and then the menu should be sized as you need it to:
   @{ Html.Telerik().Menu()
            .Name("case-history-button-menu")
            // set the display to inline-block
            .HtmlAttributes( new { style = "display: inline-block" } )
    }

Have in mind though that older versions of IE won't accept inline-block display. You may need "inline" if you must support older IEs.
Comment: @Atanas Korchev can you have  look at this question http://stackoverflow.com/q/7414387/413670

Telerik MVC Menu Control - Auto Width


Which family-wise correction is needed for one-sided t-tests in a randomized controlled trial with several independent measures across groups?

Question: I conducted a randomized controlled experiment with groups $A$, $B$, $C$, and $D$, each containing around $40$ human participants who saw one of four variants of a website. Group $A$ saw a baseline, and the other groups saw that baseline with a single additional component: $B$ saw an extra slider to pick values, and $C$ and $D$ saw that slider with one of two additional components. The rationale of the experiment was to study how users' perceptions and behaviours were affected. Therefore, participants filled out $4$ Likert scales in a post-study questionnaire (measuring constructs such as trust), and I logged $4$ additional metrics (e.g., chosen slider values).
Now I want to test whether these $8$ measurements differ across groups. Based on theory and qualitative studies, my hypotheses were:

For 4 measurements: $\mu_A<\mu_B$, $\mu_B<\mu_C$, and $\mu_B<\mu_D$;
For 1 measurement: $\mu_A=\mu_B$, $\mu_B<\mu_C$, and $\mu_B<\mu_D$;
For 1 measurement: $\mu_A<\mu_B$, $\mu_B=\mu_C$, and $\mu_B=\mu_D$;
For 2 measurements: $\mu_B<\mu_C$, and $\mu_B<\mu_D$.

After checking assumptions, I applied one-sided $t$-tests and $8$ out of the $19$ tests were significant: some are of order $p=0.01-0.03$, others $p<10^{-5}$. Given these results and the domain-specific consensus that $p<0.05$ is significant, I have two questions:

Should I correct the $p$-values? I am aware of the debate about whether post-hoc correction methods such as Bonferroni are necessary in the first place (e.g., How many p-value observations do you think are required before doing FDR correction), but am unsure whether my experiment should be considered exploratory or confirmatory.
If necessary, how should I correct the $p$-values? It is unclear to me whether corrections are only required for multiple comparisons against the same baseline (e.g., $\mu_B<\mu_C$ and $\mu_B<\mu_D$). Furthermore, should I correct the $p$-values measurement-by-measurement or for all measurements at once?
Comment: Please explain what the measured variables are and what your groups represent. From your hypotheses it seems that the groups could be of ordinal nature? If this is an RCT, what is the treatment, how does it differ between groups?
Comment: @jkd Thanks for following up. I have updated my question to explain the treatment and measurements better.
Comment: What do you mean they each have 40 samples? Do you mean each group has 40 participants?
Comment: @ShawnHemelstrand Yes, I meant participants and have edited my question.
Comment: Based on your hypotheses, you might have a look at both intersection -union tests and bioequivalence tests.
Answer: You do not supply any context for this study and so it is not possible to even say if multiple comparisons 'corrections' are relevant to your inferential objectives.
Questions about multiple comparisons 'corrections' appear on this site all the time and so there are many answers that are likely to help you already in place. I, of course, prefer my own answers so I suggest that you have a look at these:
How many p-value observations do you think are required before doing FDR correction
p value correction in multiple outcomes study
Comment: Context that you will be able to glean from the answers that I've linked.
Comment: Sorry for the delay and thanks for following up @Michael Lew. I have updated my question and hope it now provides enough details. I read your previous answers and your chapter "A Reckless Guide to P-values".
Comment: It sounds like a preliminary, hypothesis generating study, so do not do any 'correction' for multiplicity. Instead, discuss the results and say which of the supported hypotheses are most worthy of follow-up experimentation.
Comment: Thanks for your answer, Michael. What kind of extra context would be necessary?


Meaning of the notation $ \mathbb{E}_{x\sim \mu_{\text{ref}}, y\sim \mu_D(x)}[\ln y] $ in GAN framework

Question: A very naive question about notations used in mathematical framework for generative adversarial network (GAN). What is precise mathematical definition of terms like
$$  \mathbb{E}_{x\sim \mu_{\text{ref}}, y\sim \mu_D(x)}[\ln y]  $$
as appearing in wiki intro.
In generally, if $X: \Omega \to \mathbb{R}$ is a random variable on probability space $(\Omega, P)$ with density function $f_X$ and $g: \mathbb{R} \to \mathbb{R}$, then $  \mathbb{E}[g(X)]= \int g(X) dP_X= \int g(x) f_X(x)dx $ by definition.
My question is what means purely mathematically this expected value looking like object
$  \mathbb{E}_{x\sim \mu_{\text{ref}}, y\sim \mu_D(x)}[\ln y]  $ with the bottom notation $x\sim \mu_{\text{ref}}, y\sim \mu_D(x)$ in the expression above? Is this bottom notation just an additional reminder that the expected value is formed as before $\mathbb{E}[\ln y]$ with respect to two random variables $x$ and $y$, where the former has density function $ \mu_{\text{ref}}$ and the latter $\mu_D(x)$? Right, of does it mean something different?
Note, that $\mu_D$ is valued in probability measures, therefore
$  \mathbb{E}_{x\sim \mu_{\text{ref}}, y\sim \mu_D(x)}[\ln y]  $ should probably better considered as "parameterized family of distributions". But I do not understand how this object looks to be explicitly written out?
Maybe the question is trivial, but in classical stochastics I'm a little bit familiar with I never came across such bottom notation for expected values, so seems to be nonstandard "GAN specific" terminology, therefore I would like to clarify it's precise mathematical meaning.
Answer: Though not standard it's common to see the bottom notation of expectation in the expression above as discussed in this post.
Specifically in this part of GAN's loss function, you are essentially considering an expectation over the conditional distribution of assessment samples $\mu_D(x)$ as they vary with different $x$ drawn from the reference distribution $\mu_{\text{ref}}$. Thus you're right that it should be considered as an expectation over a parameterized family of distributions and it's a way to express the expectation over both the randomness in choosing $x$ from the real data distribution and the randomness in generating $y$ from the discriminator network. The GAN training process involves adjusting the parameters of $\mu_D(x)$ to minimize or maximize its entire loss function aimed by the generator and the discriminator, respectively.

Comment: Yes you're right since in GAN here the r.v. $y$ is conditioned on the r.v. $x$ which follows the ref distribution, so essentially the law of total expectation applies here.
Comment: ok so just to sum up: For any fix random variable $X$ with distribution function $f_X$ the expectation with bottom notation $\mathbb{E}_{X \sim f_X}(g(X)]$ and the "standard" notation for expectation $\mathbb{E}(g(X)]$ (by def $:= \int g(x)f_X(x)dx$) are the same, right? And specifically in the context on GAN formalism $\mathbb{E}_{x\sim \mu_{\text{ref}}, y\sim \mu_D(x)}[\ln y]$ means written out  $E(x):= \int \ln(y)\mu_D(x)$, so in english a function with argument $x$ where $x \in S$ is an picked element in the target
Comment: of random variable $X: \Omega \to S$ with distribution $\mu_{\text{ref}}$, right?


One to one correspondence between all $F[x]$-module $V$ and all linear transformations $T\colon V\to V$, $V$ being a vector space over $F$.

Question: I am fairly a beginner in module theory. While discussing the $F[x]$-modules, my text book (Dummit & Foote) describes:
$\left\{
    V \text{ an } F[x] \text{-module}
\right\}\longleftrightarrow \left\{
\begin{aligned}
    V \text{ is a vector space }\\
    \text{               and               }\\
T\colon V\to V \text{ a linear transformation }\end{aligned}
\right\}\tag*{}$
given by
$\text{ the element } x \text{ acts on } V \text{ as the linear transformation } T\tag*{}$
This is saying that we can't find any $F[x]$-module without specifying the linear transformation $T$ .
But how can we exclude the possibility of having some other $F[x]$-module which can be obtained without the help of the linear transformation $T\colon V\to V$?
Is it the case that if $x$ acts on the vectors  $v\in V$, then it must be a linear transformation? If it is the case, how can I prove it?
Answer: If $V$ is a $k[x]$-module, then multiplication with $x$ defines a linear transformation $T: V \to V, v \mapsto x v$.
Conversely, if $V$ is a $k$-vector space and $T:V \to V$ is a linear transformation, then you can define a $k[x]$-module structure by letting a polynomial $p \in k[x]$ act on $V$ by
$$ p \cdot v = p(T)(v) $$
The point is that no matter what you start with (a $k[x]$-module structure or a linear transformation) you always get the other thing for free.
Comment: @ArjunBanerjee Nono, in this scenario, you are given an $F[x]$-module $V$. Ok, using constant polynomials we can multiply elements of $V$ by 'scalars' (elements of $F$), therefore $V$ carries an $F$-vector space structure. Moreover, we are also given how to multiply by the indeterminant $x$, and that gives an $F$-linear transformation $V\to V$.
Comment: Multiplication with $x$ always gives you a linear transformation. There is nothing you can do against it.
Comment: There are two kinds of data: 1. An $F$-vector space together with a fixed linear transformation and 2. An $F[x]$-module. My answer provides a way to switch between these two (from 1. to 2. by defining an $F[x]$-module structure given a linear transformation and from 2. to 1. by defining a linear transformation given the $F[x]$-module structure) and these procedures are inverse to each other.
Comment: Sorry but I still didn't get the point. Why there is no other $F[x]$-module? And why there is no other way to get $F[x]$-modules?
Comment: I apologize, but Im still confused. We define the action of $x$ on a vector $v\in V$ in that way. Why can't we define it in another way?Why the collection exhausts all $F[x]$-modules?
Answer: If $S$ is a subring of a ring $R$ and $M$ is a (left) $R$-module, then $M$ becomes in a natural way a (left) $S$-module by "restriction of scalars".
I'm not saying that $M$ (keeping the same addition) can be endowed with the structure of $S$-module in only this way. But this structure of $S$-module can be defined.
Suppose $V$ is an $F[x]$-module. Then it can be considered an $F$-module (that is, vector space over $F$): the action of $F$ on $V$ is "multiplication by constant polynomials".
Now consider the map $T\colon V\to V$ defined by $T(v)=xv$. This is obviously $F$-linear when $V$ is considered an $F$-vector space. Note that with this linear map we are able to reconstruct the action of $F[x]$ on $V$; namely,
$$
(a_0+a_1x+\dots+a_nx^n)v=a_0v+a_1T(v)+\dots+a_nT^n(v)
$$
Just compare the two sides of the stated equality.
Conversely, given an $F$-vector space $V$ and a linear map $T\colon V\to V$, we can define an $F[x]$-module structure on $V$, by defining
$$
xv=T(v)
$$
and using linearity to complete the definition. Note here that the map induced on $V$ by multiplication by $x$ is exactly the linear map $T$.
Thus we have the required bijection.
There may certainly be different ways to define an $F[x]$-module structure on an abelian group $V$. However, as shown above, any $F[x]$-module structure can be defined via a (unique) linear map. That's what the theorem is about, nothing else.
Answer: Let us take any $F[x]$-module V. We shall prove this module is obtained from a Linear Transformation $T\colon V \rightarrow V$.
We consider the action of $x$ on $V$.
Let $v,w \in V$ then from the definition of module we have, $$x.(v+w)=x.v+x.w,.......(1)$$
Again let $p \in F \subset F[x]$ then from the definition of modules, we have,
$$x.(p.v)=(xp).v=(px).v=p.(x.v),.......(2)$$
$(1)$ and $(2)$ show the action of $x$ is linear, so this induce a linear transformation.
Hence we show that any action of $F[x]$ on V is obtained from a linear transformation.
I think from this it will be clear to you that why we exclude the possibility of having some other $F[x]$-module which can be obtained without the help of the linear transformation $T\colon V\to V$.


How to post trigger firebase cloud functions with express.js

Question: What i am trying to do is send data(inputs) from client to firebase cloud function with post trigger using express.js  and use that data to create a new user.
this is the cloud function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});

admin.initializeApp(functions.config().firebase);

exports.registeration = functions.https.onRequest((req, res) => {

 res.status(400).send({
      message: 'error',
      message2:req,
      message3:req.body
  });
  res.send({
      message: 'success'
  });
});

So how do i write client part with express.js
Answer: Maybe something like this :
const express = require('express');

// Create the server
const app = express();

app.use((err, req, res, _next) => {
  console.log('Error handler', err);
  if(err){
    res.status(400).send({
      message:'error',
      message2:req,
      message3:req.body
    });
  } else {
    res.send({
      message: 'success'
    });
  }
});

exports.registeration = functions.https.onRequest(app);


MAMP server starts but website won't load

Question: Today I started my MAMP local server and my Wordpress installation would not load. It will attempt to load for 15-20 seconds and then give me an ERR_CONNECTION_TIMED_OUT error. Yesterday everything worked fine, and I made absolutely no changes to MAMP or my website's files to cause this issue, so this issue is really frustrating and mysterious to me.
I don't think that the actual MAMP server is an issue because when I start up the server I can click 'Open WebStart page' and it will load fine, it is only my website itself that won't load.
I also tried to change the ports from the default 8888 & 8889 to 80 & 3306 as was suggested by someone in a forum but that made no difference either.
Like I said, I am using the same ports as yesterday and the same IP that I was using to connect to my localhost, but today for some reason it won't load. Does anyone know what could possibly be causing this?
Answer: I found the problem which involved a corrupt Wordpress database. The problem ended up having nothing to do with MAMP. I ended up fixing the issue by restoring my Wordpress installation from a backup which I luckily had thanks to Updraft Plus. If anybody else is having this problem consider the possibility that your database may be corrupt.


Preencher uma textbox com elemento de uma combobox

Question: Eu tenho uma combobox conectada a um textbox por uma função. Funciona assim: ao passo que a pessoa digita algo na textbox, é automaticamente realizado uma espécie de 'filtro' na combobox, que mostra algo que poderia corresponder ao que a pessoa deseja informar (no caso, uma cidade).

<meta charset="UTF-8">
<title>Title</title>

<form name="form">
<input type="text" name="texto" onkeyup="trocaOpcao(this.value, document.form.cidade);">

<select disabled name="cidade">
    <option selected>Sua Cidade</option>
    <option>sao paulo</option>
    <option>rio de janeiro</option>
    <option>vitoria</option>
    <option>belem</option>
    <option>recife</option>
    <option>santa luzia</option>
    <option>santa cruz</option>
    <option>santarem</option>
</select>
</form>

Eu gostaria de saber como preencher o conteúdo da textbox automaticamente com o conteúdo filtrado da combobox ao dar 'enter' ou 'tab'.
Desde já, agradeço.
Answer: Creio que se eu entendi o jQuery pode lhe atender

<meta charset="UTF-8">
<title>Title</title>

<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/themes/black-tie/jquery-ui.css">

<form name="form">
<input type="text" id="descricao" />
<input type="hidden" name="idQueVaiParaSeuBackEnd" id="id" />
</form>

Teste preenchendo : rio ou sao
Eu gosto muito de utilizar jQuery nas minhas aplicações, facilita muito até mesmo o entendimento do Javascript !
Espero ter lhe ajudado.
Comment: Muitissimo obrigada!!!
Comment: Pode votar na minha resposta como solução? rsrs obrigado !
Answer: Eu sugiro o uso do elemento <datalist>.
Ele adiciona o recurso de autocompletar ao input de forma nativa.
A página no w3schools tem um exemplo funcional: https://www.w3schools.com/tags/tag_datalist.asp
Exemplo, extraído do link acima:

Choose your browser from the list:
<input list="browsers" name="browser" id="browser">

<datalist id="browsers">
  <option value="Edge">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

No seu caso, o código ficaria assim:

<input type="text" list="cidade" name="texto">
<datalist id="cidade">
    <option>sao paulo</option>
    <option>rio de janeiro</option>
    <option>vitoria</option>
    <option>belem</option>
    <option>recife</option>
    <option>santa luzia</option>
    <option>santa cruz</option>
    <option>santarem</option>
</datalist>

Veja que temos aí, ao invés de um <select> temos um <datalist> que tem o ID configurado como "cidade" e no <input> temos o parâmetro list="cidade", que é responsável por referenciar qual o datalist a ser usado.
Edit: só após postar a resposta foi que notei que a questão é de 2016! Mas fica aqui o registro de uma resposta atualizada com outras opções que existem agora.
Comment: Para melhorar a qualidade da resposta, editei para incluir o exemplo diretamente aqui.


Alterar nome de usuário no Ubuntu

Question: Formatei meu ubuntu e digitei errado o nome.
Tentei consertar alterando os arquivos /etc/hostname e /etc/hosts mas ainda não consegui o que quero.
Quando abro o terminal aparece assim:

daneil@daniel:~$

Preciso de:

daniel@daniel:~$

O nome (antes do @) está errado, como consertar?
Comment: @Renan O fato de um comando como `usermod` poder ser usado num script não torna a pergunta sobre scripts.
Comment: Não sei se isso está dentro do escopo definido pela comunidade.
Comment: @Patrick, acredito que não. Sistemas operacionais não são ferramentas primárias para programadores. Acho que seria muito genérico aceitar isso. E acabaria tornando esse site uma mistura entre o [su] e o [pt.so].
Comment: @bfavaretto ok, concordo. Se alterarmos a pergunta para algo do tipo "como mudo o nome do (usuário/host)" com shellscript, a pergunta ficaria mais em tópico?
Comment: @Renan, eu acho que não, porque a resposta não muda muito, certo? É uma maneira artificial de "encaixar" a pergunta. Se você acha que devemos aceitar perguntas sobre uso de linha de comando no estilo [su], não quer abrir uma discussão no meta?
Comment: Feito ([de certa forma](http://meta.pt.stackoverflow.com/questions/264/quais-assuntos-devem-fazer-parte-do-nosso-foco-on-topic/1880#1880)).
Answer: Tente:
<code>usermod -l nomeNovo nomeAntigo
</code>
Comment: Resolvido:
mv /home/nomeAntigo /home/SeuNome
usermod --home /home/SeuNome NomeDoUsuário
Comment: Vale lembrar que precisa de estar logado como outro usuário (de preferência o root) e que também deve mudar a pasta do usuário para o novo nome.
Comment: Obrigado, funcionou certinho, criei outro user admin para poder executar o comando, alterei e deletei o user novamente.
Obrigado. Boa noite.
Comment: Somente alterar o nome da pasta do usuário que não funcionou, quando alterei ele não entra no modo gráfico, aí tive que voltar no nome antigo da pasta, o que poderia ser?

Alterar nome de usuário no Ubuntu


Redirects aren't working, is there a conflict with the rules or order of them?

Question: I need to redirect any incoming traffic that is not www or https, to www and https.
The one issue is trying to add one more rule that would handle all traffic that used to be at rootdomain.com/blog/rest-of-url-title and send that to the subdomain https://blog.rootdomain.com/rest-of-url-title
This is what I have in my root domain htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^/blog/(.*)$ https://blog.rootdomain.com/$1 [R=302,L]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=302]
</IfModule>

Then within the blog subdomain directory htaccess I have this (to redirect any non https to https and the rest is Wordpress based)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

When trying to hit any url that is rootdomain.com/blog/rest-of-url-title it redirects to
https://www.rootdomain.com/index.php
Instead of redirecting to the blog subdomain, it just goes to www and since that url title doesn't exist for www i just get 404.
Answer: I had to go with mod_alias redirectmatch to get it working how i wanted
RedirectMatch 302 ^/blog/(.*)$ https://blog.rootdomain.com/$1

It's odd because the mod_rewrite line in my original htaccess in root had this:
RewriteRule ^blog/(.*) https://blog.rootdomain.com/$1 [R=302,L]

Which did not work on this particular server, but worked fine on any other servers I tested on. Maybe because of a subdomain/directory mapping issue?
Regardless, I know it's not good practice to mix mod_rewrite and mod_alias, this final worked for me:
RedirectMatch 302 ^/blog/(.*)$ https://blog.skodaminotti.com/$1
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=302]
</IfModule>

Would still love to hear if anyone knows why the rewriterule wouldn't work.


Sort data from structures in alphabetical order

Question: I'm a bit annoyed. I can't find any solution that I could sort data from structures. Look, this is my code. I'll explain what's happening and what I'm trying to do:
(I had to translate the code from my native language to English so... if you find any weird words notice me.)
I'm trying to sort this structure of countries. But my mistake is that the only thing I'm sorting is the list of country names.. so the data will mess up. Can you help me with a good algorithm for this?
<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int n;

struct Countries{
    char country_code[20];
    char country_name[20];
    float country_area;
    int country_people;
    float global_income;
}*countries;

void menu();
void read();
void display();
void sort();
void exit();

int main(){
    printf("Enter no of countries: "); scanf("%d", &n);
    countries = malloc(n * sizeof(*countries));
    menu();
}

void menu(){
    int op;
    printf("[1] Read;\n[2] Display;\n[3] Sort;\n[4] Exit.\n");
    printf(">> "); scanf("%d", &op); fflush(stdin);
    switch(op){
        case 1:
            read();
            break;
        case 2:
            display();
            break;
        case 3:
            sort();
            break;
        case 4:
            exit();
            break;
        default:
            break;
    }
}

void read(){
    printf("\n\n\n______READ______n\n\n");
    int i;

    for(i=0; i<n; i++){
        printf("Country code #%d: ", i+1); gets(countries[i].country_code); fflush(stdin);
        printf("Country name: "); gets(countries[i].country_name); fflush(stdin);
        printf("Area: "); scanf("%f", &countries[i].country_area); fflush(stdin);
        printf("No of people: "); scanf("%d", &countries[i].country_people); fflush(stdin);
        printf("Global Income: "); scanf("%f", &countries[i].global_income); fflush(stdin);
        printf("\n\n\n");
    }
    menu();
}
void display(){
    printf("\n\n\n______DISPLAY______n\n\n");
    int i;

    for(i=0; i<n; i++){
        printf("Country code #%d: ", i+1); puts(countries[i].country_code);
        printf("Country name: "); puts(countries[i].country_name);
        printf("Area: "); printf("%.2f", countries[i].country_area);
        printf("\nNo of people: "); printf("%d", countries[i].country_people);
        printf("\nGlobal Income: "); printf("%.2f", countries[i].global_income);
        printf("\n\n\n");
    }
}

void sort(){
    int i, j;
    char temp[20];
    /* countries sorted in alphabetical order */
    for(i=0; i<n; i++){
        for(j=i+1; j<n; j++){
            if(strcmp(countries[i].country_name, countries[j].country_name)>0){
                strcpy(temp,countries[i].country_name);
                strcpy(countries[i].country_name, countries[j].country_name);
                strcpy(countries[j].country_name, temp);
            }
        }
    }

    for(i=0; i<n; i++){
        printf("\n\nCountry: "); puts(countries[i].country_name);

        printf("Population density: ");
        printf("%.2f", ((float)countries[i].country_people)/((float)countries[i].country_area));

        printf("\nIncome per people: ");
        printf("%.2f", ((float)countries[i].country_people)/((float)countries[i].global_income));
    }
}

void exit(){
    free(countries);
    getch();
}
</code>
Comment: So as you swap country data same thing do for other elements of structure. or simply copy whole structure.
Answer: In your sort function, copy all of the structure rather than just the name
<code>void sort(){
    struct Countries temp;
</code>

<code>            if(strcmp(countries[i].country_name, countries[j].country_name)>0){
                //strcpy(temp, countries[i]);
                //strcpy(countries[i], countries[j]);
                //strcpy(countries[j], temp);
                temp = countries[i];
                countries[i] = countries[j];
                countries[j] = temp;
            }
</code>
Comment: @CristianOnescu If you have structs use the assign operator, that is: `=`
Comment: I was looking for an algorithm. The ideea was good but.. what function should I use instead of strcpy? (which is for strings :D)
Comment: Sorry, my bad. Just use plain assignment; post edited.


turn off roads overlay on google maps

Question: I would like to turn off road/highway markings on google maps.  I looked at https://developers.google.com/maps/documentation/javascript/reference#MapTypeStyleFeatureType and played with the wizard at http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html.  However, any options I chose didn't turn off the road/highway markings.  Ideally I would like to add my own paths (e.g. Airline flights) but the road markings throw them off.
Using the wizard, I got this:  http://maps.googleapis.com/maps/api/staticmap?center=42.629586,-83.822497&zoom=9&format=png&sensor=false&size=640x480&maptype=roadmap&style=feature:administrative.country|visibility:on&style=hue:0x0099ff&style=element:labels|hue:0xff0000.  I like this but I want to turn off all the road marking.  Anyone know how to turn do this.
Thanks, BillN
Answer: You can remove roads or roads labels using the style generator.  If you are using the V3 javascript api.  The style JSON would look like
<code>[ { featureType: "road", stylers: [ { visibility: "off" } ] },{ } ]
</code>
Here's a static link with no roads.
http://maps.googleapis.com/maps/api/staticmap?center=45.95115,-113.884277&zoom=7&format=png&sensor=false&size=640x480&maptype=roadmap&style=feature:road|visibility:off
Comment: This link no longer works.  Does anyone have an update?

turn off roads overlay on google maps


Format date field in twig

Question: Date field having multiple values. Need to format the output.
{% for item in items %}

{{ item.content|date(format="F j, Y") }}

{% endfor %}

item.content showing the date as updated. But not able to format the result. Got the below error,

TypeError: DateTime::__construct() expects parameter 1 to be string,
  array given in...

Please suggest on this issue.
Comment: Use the field formatter date options in the admin configuration of this content type.
Answer: In Twig, drill down to the timestamp value:
node.html.twig:
{{ content.field_name['#items'].value | date('F d, Y') }}

For a loop, do:
{% for items in content.field_name['#items'] %}
  {{ items.value | date('F d, Y') }}
{% endfor %}

field.html.twig:
{% for item in items %}
  {{ item.content["#markup"] | date('F d, Y') }}
{% endfor %}

Note: Set field format display option to plain or custom if using the field template. This field option can break your site just by someone changing the format option for the field, so use caution.
Comment: Thanks. I'm using that code in twig field template : `field--node--field-date--calendar-event.html.twig` (`field--node--[field-name]--[content-type].html.twig`). So, I tried `content.field_date` in the loop instead of `content.field_date_field`. But didn't get any result. Please advise.
Comment: Added a field template option to the answer.
Comment: The date field does have a custom format option as well that allows custom formatting of the field value.
Comment: Thanks @Prestosaurus I just did it using **preprocess** function based on content type.

Format date field in twig


How to sort TCP fragments

Question: I have 10 unsorted TCP segments (A-J) and I want to sort them temporarily.
The information I have from each one:

A:{Sequence number: 43 4a 6f bd, Acknowledgment number: 66 6e b6 f4,
Flags: ACK}.
B:{Sequence number: 43 4a 6e 71, Acknowledgment number: 66 6e b2 53,
Flags: ACK}.
C:{Sequence number: 43 4a 6e 70, Acknowledgment number: 00 00 00 00,
Flags: SYN}.
D:{Sequence number: 66 6e b6 f3, Acknowledgment number: 43 4a 6f bd,
Flags: ACK+FIN}.
E:{Sequence number: 66 6e b2 52, Acknowledgment number: 43 4a 6e 71,
Flags: ACK+SYN}.
F:{Sequence number: 66 6e b2 53, Acknowledgment number: 43 4a 6f bd,
Flags: ACK+PSH}.
G:{Sequence number: 66 6e b2 53, Acknowledgment number: 43 4a 6f bd,
Flags: ACK}.
H:{Sequence number: 66 6e b3 a4, Acknowledgment number: 43 4a 6f bd,
Flags: ACK+PSH}.
I:{Sequence number: 43 4a 6e 71, Acknowledgment number: 66 6e b2 53,
Flags: ACK+PSH}.
J:{Sequence number: 43 4a 6f bd, Acknowledgment number: 66 6e b6 f3,
Flags: ACK}.

As far as I know the first one should be C and the second one E, but I have no idea how to arrange the other segments.
Thanks
Comment: Sort them by sequence number, of course. That's what it's for.
Comment: @EJP the fragments belongs to a communication between two devices, I need to sort them temporarily, i.e. First the Device1 sent segmentC, then Device2 answered by sending segmentE, so on.
Comment: Sort them by source ip:port, destination ip:port, sequence number. I assumed you were capable of distinguishing the flows in each direction.
Comment: I know that @EJP , but for example, F and G have the same sequence number, that's what I dont understand.
Comment: If that's your question why doesn't it appear in your question? Clearly F didn't contain any data, so it didn't advance the sequence number for the next segment.
Comment: @EJP then, F is sent before G?
Answer: For sorting more accurate, you need to have each packet's payload size (in order not to miss the order of segments which have overlap with their previous segment).
But if you're sure that there is no segment with some overlapped data, you can sort packets by comparing their sequence and acknowledgment numbers (and also considering control flags).
It's better to sort packets in each direction independently at first:
Request side: C, B, I, J, A.
Response side: E, G, F, H, D.
In choosing between F and G, we consider that F's PSH flag is set; So it contains data and advances the sequence number. Therefore, it should come after G since G seems not to contain any data.
Now we can merge by comparing each side's first packet:

C: SYN
E: SYN + ACK
B: ACKs E
I: G's acknowledgment number is greater than I's sequence number.
G: J's acknowledgment number is greater than G's sequence number.
F: J's acknowledgment number is greater than F's sequence number.
H: J's acknowledgment number is greater than H's sequence number.
J: J is before D since it doesn't ACK D. (D's FIN control flag is set; So it advances the sequence number.)
D: A's acknowledgment number is greater than D's sequence number.
A

How to sort TCP fragments


How this formula return intersection between circle and line?

Question: circle line intersection
as you can see in the picture, the writer said
the horizontal = radius * sin(theta)
the vertical = 1 - radius * cos(theta)
i know x = rcos(theta), y = rsin(theta) but I can't understand where this formula came from.
and the method is
<code>private bool SimulateSphereCast(Vector3 groundNormal, out RaycastHit hit)
        {
            float groundAngle = Vector3.Angle(groundNormal, controller.up) * Mathf.Deg2Rad;

            Vector3 secondaryOrigin = controller.transform.position + controller.up * Tolerance;

            if (!Mathf.Approximately(groundAngle, 0))
            {
                float horizontal = Mathf.Sin(groundAngle) * controller.radius;
                float vertical = (1.0f - Mathf.Cos(groundAngle)) * controller.radius;

                // Retrieve a vector pointing up the slope
                Vector3 r2 = Vector3.Cross(groundNormal, controller.down);
                Vector3 v2 = -Vector3.Cross(r2, groundNormal);

                secondaryOrigin += Math3d.ProjectVectorOnPlane(controller.up, v2).normalized * horizontal + controller.up * vertical;
            }

            if (Physics.Raycast(secondaryOrigin, controller.down, out hit, Mathf.Infinity, walkable, triggerInteraction))
            {
                // Remove the tolerance from the distance travelled
                hit.distance -= Tolerance + TinyTolerance;

                return true;
            }
            else
            {
                return false;
            }
        }
    }
</code>
And whole articles is here
Answer: The formula in the figure is wrong.
It should say $(1 - \cos (\theta)) \times \mathop{radius}.$
It is $1 - \cos(\theta)$ because the distance is measured from the bottom of the circle, not from the center.
The vertical distance of that point from the center of the circle is
indeed $\cos(\theta)\times \mathop{radius}.$
The vertical distance from the center to the bottom of the circle is
$\mathop{radius}.$
The vertical distance shown in the figure is the remaining vertical distance to the bottom after you have already come down a distance $\cos(\theta)\times \mathop{radius}$ from the center of the circle.
This remaining distance is
$$ \mathop{radius} - \cos (\theta) \times \mathop{radius}
=(1 - \cos (\theta)) \times \mathop{radius}.$$
Comment: Ahh,, you are right.. Thank you so much..!!


Quadratic second-order differential equation involving tan x

Question: Is there a way to exactly solve the following differential equation:
$$\left(\frac{dx}{dt}\right)^2 = -\tan x \frac{d^2x}{dt^2} $$
Comment: The equation would be easier to read if you used [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Answer: Hint
The equation being
$$(x')^2+\tan(x) x''=0$$ make
$$\cos(x)=z \implies x=\cos ^{-1}(z)\implies x'=-\frac{z'}{\sqrt{1-z^2}}\implies x''=\frac{\left(z^2-1\right) z''-(z')^2}{\left(1-z^2\right)^{3/2}}$$ as well as $\tan(x)=\frac{\sqrt{1-z^2}}{z}$.
You should get something very simple.
Answer: Rewrite
$$ -(\cot x)x' = \frac{x''}{x'} $$
Integrate both sides
$$ \ln(x') = -\ln(\sin x) + C $$
$$ \implies x' = \frac{A}{\sin x} $$
Separate and integrate again
$$ (\sin x)x' = A $$
$$ \cos x = B-At $$
Final solution
$$ x(t) = \arccos(B-At) $$


List all the nodes with the same menu parent ID

Question: I have the following menu in my system.

The parent menu-link connects to a node whose ID is 58. All the sub menu-links have a parent ID equal to 58.
I need to find the main and the sub-menus using 58, but I have been unsuccessful at locating the a table that contains that information.
How can I list the nodes that share a particular menu ID?
Comment: Are you actually trying to find just the nodes that are children of a particular parent menu item and do something with them? or are you just trying to display all of a particular menu item's children (whether the child menu items point to nodes or other)?
Comment: Yes. I'm trying to get the nodes to do something with them The parent and offspring node IDs will go into some logic else where on the site.
Comment: @sisko did you have a chance to try my suggested answer?
Answer: The menu_link_content entity definition contains information related to your question; namely, the database table that contain the parent-child relation would be menu_link_content_data.
Below is a code sample that would deliver an array of node ids given a parent node, provided that there is a menu link attached to the node.
This code uses Drupal's APIs instead of SQL queries.
<?php

// Get the root based on a given node, e.g. node 58.
$menu_link_root_entities = \Drupal::entityTypeManager()
  ->getStorage('menu_link_content')
  ->loadByProperties([
      'link'  => [
        'uri' => 'entity:node/58'
      ],
    ],
);
$menu_link_root = reset($menu_link_root_entities);

// Need to call this in order to instantiate the tree_storage service.
$menu_tree = \Drupal::menuTree();
// Get menu link content entities based on their parent property.
$menu_links = \Drupal::service('menu.tree_storage')->loadByProperties([
    // Need a filter value like menu_link_content:8031d182-7a0b-4798-839a-6c66bdd1f27b
    'parent' => 'menu_link_content:' . $menu_link_root->uuid(),
]) ?: [];

$node_ids = array_map(function($v){
    return $v['route_parameters']['node'];
}, $menu_links);

Hope this helps, good luck!
Comment: This works fine in drupal 9.5 but I couldn't get it to work in drupal 10.1. I get the following error message "Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "menu.tree_storage". in Drupal\Component\DependencyInjection\Container->get() (line 157 of core/lib/Drupal/Component/DependencyInjection/Container.php)."


proof of modular congruencies

Question: Is it possible to show that given $a,b,d,n \in \mathbb{N}$, if $a \equiv b \pmod{m}$ and $d\mid n$, then $a \equiv b \pmod{d}$?
I'm able to see it computationally by checking numbers but can't seem to formulate a proof so I'm not sure if I'm just picking lucky numbers that work out?
I'm trying to use this as a intermediate step in a larger proof but am unsure if it's valid.
Answer: A divisor of a divisor is a divisor, so
$$a\equiv b\mod n\iff n\mid a-b\implies d\mid a-b\iff a\equiv b\mod d.$$
Comment: oh wow that was far more trivial than i was making it. thanks.
Comment: Beginners often  tend make things more complex than what they really are. In my opinion, the first line would be enough.

proof of modular congruencies


Disable controllers in certain API version

Question: We are developing a new API version in our application, so that we basically have a
namespace Bla.V1.Controllers
[ApiController]
[ApiVersion("1")]
public partial class SampleController : ControllerBase {}

and a
namespace Bla.V2.Controllers
[ApiController]
[ApiVersion("2")]
public partial class SampleController : ControllerBase {}

We've also configured API versioning (AddApiVersioning), so that when somebody tries to access e.g. api/v3/sample/action, he will get a version not supported error response, provided by the API versioning middleware.
Now the V2 version is in development and we want to make it available only for the development stage. The controllers code will be deployed to production, we want however to disable the V2 version for production.
We would do it with a feature flag, but what should be done to hide the V2 controllers?
I was thinking:

Somehow do not register the V2 controllers. Didn't find a suitable option in AddControllers()
Set maximum version to V1 in the API versioning middleware. This works only for headers, doesn't block access to V2 controllers

I'm currently thinking about writing an authorization attribute that would deny access based on the feature flag status and apply it to V2 controllers. Is there a better and more elegant way to do this?
Comment: If the `ApiVersioning` package doesn't do it by default (I've not looked), your approach would be my first thought too.  Could you create an attribute that inherits the `ApiVersionAttribute` and override the functionality?
Answer: Well, in case somebody is interested at some point. Our controller code is autogenerated from a Swagger definition. So I added the following code to the generation template, which gets invoked in each controller method:
if (!this.IsV2Enabled())
            {
                var protocol = this.Request.IsHttps ? "https" : "http";
                return this.BadRequest(new
                {
                    error = new {
                        code = "UnsupportedApiVersion",
                        message = $"The HTTP resource that matches the request URI '{protocol}://{this.Request.Host}{this.Request.Path}' does not support the API version '1'."
                    }
                });
            }


Creating an automated command to pull data from Knoema in R

Question: I'm attempting to create an automated way of pulling data from the Knoema API in R. So far, I have this code which works fine.
library(Knoema)

Knoema('WLDGVTBOND2017',
       list('timerange' = '01/01/2021-01/31/2021', 'frequency' = 'D',
            'Bond' = '3MONTH;2YEAR;3YEAR;5YEAR;6YEAR;10YEAR;15YEAR;20YEAR;25YEAR;30YEAR',
            'Country' = 'ZA', 'Indicator' = 'KN.I1'), type = 'DataFrame')

For the timerange argument, I would instead like to pass through an object which automatically pulls data from the last two months. Something like this.
library(lubridate)
library(Knoema)

range <- paste0(format(Sys.Date() - months(2),"%d/%m/%Y"),"-",format(Sys.Date(),"%d/%m/%Y"))

Knoema('WLDGVTBOND2017',
       list('timerange' = range, 'frequency' = 'D',
            'Bond' = '3MONTH;2YEAR;3YEAR;5YEAR;6YEAR;10YEAR;15YEAR;20YEAR;25YEAR;30YEAR',
            'Country' = 'ZA', 'Indicator' = 'KN.I1'), type = 'DataFrame')

However when I run that, I get the following error
Error: Client error: (400) Bad Request

Any way to overcome this issue?
Answer: The format required is mdy what you have is dmy :

library(lubridate)
library(Knoema)

range <- paste0(format(c(Sys.Date() - months(2), Sys.Date()), '%m/%d/%Y'), collapse = '-')

Knoema('WLDGVTBOND2017',
            list('timerange' = range, 'frequency' = 'D',
            'Bond' = '3MONTH;2YEAR;3YEAR;5YEAR;6YEAR;10YEAR;15YEAR;20YEAR;25YEAR;30YEAR',
            'Country' = 'ZA', 'Indicator' = 'KN.I1'), type = 'DataFrame')


Two-dimensional list comprehension Python 2

Question: I'd like to know how I can convert the strings in a list to integers.
For example:
Input:
data = [
['1', '-160'],
['2', '-3000'],
['4', '-2'],
['5', '0.27'], ]

data = [int(a) for a in data[0]] #This converts only the first row of the list - I need the whole list converted

print(data)

Output:
[[1, -160], [2, -3000],[4, -2],[5, 0.27]]

The reason to do this is because I want to sort the list but that doesn't work when the numbers have the apostrophes.
I hope anyone can help me :)
Answer: This would be the correct list comprehension:
[[float(c) for c in row] for row in data]

Please note that I have changed int(...) to float(...) to handle the floating numbers in your input. This gives as output:
[[1.0, -160.0], [2.0, -3000.0], [4.0, -2.0], [5.0, 0.27]]

As per your comment, if you have letters in your list, you can also add an if statement to your list comprehension:
[[float(c) if c.lstrip('-').isdigit() else c for c in row] for row in data ]

Comment: Ok, found a solution by myself. [[float(c) if c.lstrip('-').isdigit() else c for c in row] for row in data ]
Comment: Thanks for your help!
What can I do if I have letters in my list?
For example:
data = [
['A', '-160'],
['B', '-3000'],
['C', '-2'],
['D', '0.27'], ]
How can they be ignored?
Comment: The problem with this solution is that all negative numbers are ignored. Do you have a solution for that as well?
Thanks for your great help!!
Answer: data = [
['1', '-160'],
['2', '-3000'],
['4', '-2'],
['5', '0.27'], ]

print [[int(i), float(j)] for i, j in data]

Result:
[[1, -160.0], [2, -3000.0], [4, -2.0], [5, 0.27]]

Answer: I think this would solve your issue (given that you want all values to be integers):
import math
...
result = [[math.floor(float(y)) for y in x] for x in data]

Result
[[1, -160], [2, -3000], [4, -2], [5, 0]]


Character Tables of $D_{4}$ and $Q_{8}$

Question: Is there an intuitive reason that the Quaternion group and the Dihedral group on four vertices have the same character table? Does this indicate something special about the two groups? Or is it more of a coincidence the tables are the same?
Answer: Suppose $G$ is a non-abelian group of order $8$.  If its irreps. are of dimensions $n_i$, then from the formula $\sum n_i^2 = 8$ (and remembering that we have at least one $n_i = 1$, since there is the trivial representation, but not all $n_i =1$, since $G$ is non-abelian), we find that the $n_i$ are equal to $1,1,1,1,2$.
The abelianization of $G$ is necessarily the Klein $4$-group (since if the abelianization of $G$ were cyclic, then $G$ would be generated by $[G,G]$ --- or order $2$ and normal --- and a lift of the generator of $G/[G,G]$, and hence would
be abelian, contradicting the assumption that it is non-abelian).
This already forces a fair bit of information about the $4$ one-dimensional characters.
Since $G$ has a unique $2$-dimensional representation, it is isomorphic to
its twist by any of the one-dimensional characters.  This forces more information about the character table.
In fact, if my back-of-the-envelope computation is correct, this completely determines the character table.
So, essentially, for a non-abelian group of order $8$ the constraints are just too tight for there to be more than one possible character table.

Character Tables of $D_{4}$ and $Q_{8}$


Pick a random item with the help of an array of cumulative probabilities

Question: I have to implement a genetic algorithm and therefore select the "fittest" of all possible members of a generation.
I have the following arrays of fitnesses, their weighed equivalents and a cumulative array.
<code>Fitnesses: [0.2, 0.0, 0.2, 0.0, 0.0, 0.0]
Weighed Fitnesses: [0.5, 0.0, 0.5, 0.0, 0.0, 0.0]
Cumulative Fitnesses: [0.5, 0.5, 1.0, 1.0, 1.0, 1.0]
</code>
Now I have to choose five new members, with a higher probability of the chosen member being fitter than the others, i.e. the probability of being chosen proportional to the fitness.
How would I go about doing this by using a random number?
Comment: Generate a random float _x_ in the interval (0,1) and perform a binary search of the cumulative fitness array, finding the first entry that equals or exceeds _x_.  Its index denotes the chosen fitness.
Answer: Whuber answer is of course very good and simple, but if You are looking for something faster (binary search approach needs $O(logn)$ steps) then You can look at Walker's alias method, it is described well in Knuths Art of Computer Programming, unfortunatelly I can't tell You the exact page because I have only Polish version of this book. You can also read this article. These method allows to draw a random number from any finite discrete distribution in constant time.
Comment: I'ts also in Knuth's Graphbase book, p. 392. For a Python recipe, see http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/


Glissando without a final note too long

Question: I've tried different methods to have a glissando without a final note. The problem is that the glissando sign is too long whatever the hidden note is. I need a short glissando sign. Is that possible?
Here is a minimal code:

\version "2.22.1"
\language "english"

\header {
  % Remove default LilyPond tagline
  tagline = ##f
}

\layout {
  \context {
    \Score
    \remove "Bar_number_engraver"
  }
}

global = {
\key gf \major
  \override Glissando.style = #'trill
  \hide Staff.BarLine
}
\relative c' {
\global
ef8 ef4 f8 f4 ef8 f8
gf2 \glissando
af2. \glissando
gf4.. gf16
gf2. \glissando \hideNotes d16 \unHideNotes
\bar "||"
}
Comment: Can you provide a snippet of the code you are using?  Is the glissando too long horizontally, vertically, or both?
Comment: I added the code
Comment: In addition to the above, please indicate the instrument(s) involve.
Answer: It's hard to know what you are trying to achieve without some kind of image/drawing.
I guess that you want the final note to take up no metrical time in the bar, if so you probably want to use a hidden grace note:
<code>    \afterGrace gf2\glissando { \hideNotes af8 \unHideNotes }
</code>
Update
Now that you have posted the code that you are working with, it seems like there is a problem with the timing translator.  I think you should be using a cadenza instead of just hiding the bar lines.
Try something like this:
<code>    \cadenzaOn
    ef8 ef4 f8 f4 ef8 f8
    \afterGrace gf2\glissando { \hideNotes af8 \unHideNotes }
    \afterGrace af2.\glissando { \hideNotes gf8 \unHideNotes }
    gf4.. gf16
    \afterGrace gf2.\glissando { \hideNotes d8 \unHideNotes }
</code>
Answer: Add a note in a hidden voice to anchor the end of the gliss.
Comment: From the OP: "the glissando sign is too long whatever the hidden note is"

Glissando without a final note too long


Very fast memory write (Windows)

Question: I am using in C++:
<code>While(1){
WriteProcessMemory(hProc, (LPVOID)value, &newValue, (DWORD)sizeof(newValue), NULL);
}
</code>
Is there faster way to write to memory (in Windows)?
Comment: What's the point of writing the same data to memory in a loop? What do you want to achieve? How many bytes are you writing? If it's only 4 bytes, a variable assignment may be faster.
Comment: I will use sizeof(byte), thanks Thomas. I have another program which is very quickly writing another variable to that address, and I want to "freeze" it to earlier state.
Comment: Ok, then `hProc` refers to a different process and a simple variable assignment is not possible. Looks fine to me, don't have a better idea.
Answer: The only way to do this faster is to make a DLL which modifies that memory address and inject it into the target process.  WriteProcessMemory() requires the overhead of calling into the kernel while de-referencing the memory locally is done with just a couple assembly instructions.

Very fast memory write (Windows)


Animate custom vector shape

Question: I'd like to animate the following vector shape, unfortunately due to the edges converting it into a path is not possible. (If anyone knows a way to preserve the shape as a path, kudos for that!)

The goal would be to have an animation that follows the shape:

I was playing around with SVG animations, but it seems to be not possible to animate a shape. Path animations are possible. My question is, is it possible to use a <canvas> element like in the attached fiddle and animate it there?
http://jsfiddle.net/Na6X5/
Comment: Why couldn't you convert the shape into an SVG path? To answer your questions, yes... you could make it in a canvas.
Comment: Just thinking out loud... What about overlaying your shape with a path with a white stroke color and animate that?
Comment: @jcaron Conversion is not possible due to the different angles (round/square) Getting it into a  is simple, but I couldn't find anything with regards to animating it. (Except moving it around, which won't help.) Or is your idea to actually animate something on top?
Comment: Actually, @FirstLegion is quite right, `stroke-linejoin="round"` will have the path look exactly like your picture...
Comment: https://jsfiddle.net/vbebd1xd/
Comment: Well, it's close, but not exactly the same (radius of the corners). Not sure how precisely you need to match your picture. In any case, the solution with the white overlay in my comment above should be usable.
Comment: You could try this one with paths... https://jsfiddle.net/1Lg0u9af/
Comment: My answer below is due to me procrastinating uni assignments lol. I hope it helps!
Answer: I recreated the shape in Illustrator so it's not quite perfect, but it's very close. I then saved it as an SVG path.
Here is the working code to do what I think you want.
SVG Shape:
<?xml version="1.0" encoding="utf-8"?>
<svg id="myshape" version="1.1" id="Layer_1" xmlns="http://www.w3.org  /2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 571.1 437.5" style="enable-background:new 0 0 571.1 437.5;" xml:space="preserve" stroke="#000" stroke-width="90" stroke-miterlimit="10">
<g>
  <path id="mypath" d="M519,300.4l-76.4,75.9c-14,13.9-36.7,13.9-50.7-0.1l-83.5-83.5c-13.2-13.2-34.6-13.3-48-0.2
    l-93.9,92.1c-11.2,11-29.4,10.4-39.9-1.4l-73.5-82.6c-11.4-12.8-10.8-32.2,1.3-44.3L255.7,55.5c14-14,36.6-14,50.7-0.1l212.5,210.7
    C528.5,275.6,528.5,291,519,300.4z" />
</g>
</svg>

JavaScript
drawTime = 2000; //2 seconds
path = document.getElementById("mypath");
length = path.getTotalLength();
path.style.strokeDashoffset = length; //starting position
path.style.strokeDasharray = length + ', ' + length;
path.style.fill = "none"; //make it have no fill to begin with
path.style.transition = path.style.WebkitTransition = 'none';
path.getBoundingClientRect();
path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset ' + (drawTime / 1000) + 's ease-in-out';
path.style.strokeDashoffset = '0'; //finishing position

JSFiddle (pure JavaScript): https://jsfiddle.net/900nayr2/4/
JSFiddle (with my jQuery plugin I wrote): https://jsfiddle.net/vL5bz5mn/1/
For the jQuery one... I wrote the DrawSVG plugin approximately a year ago for jQuery 1.10 or something like that. I hope this helps! You could just use the JavaScript one if you like.
Comment: Thanks, this is amazing!
Comment: No worries, let me know if you want to move the starting position of the shape. It's all to do with the coordinates of the SVG.

Animate custom vector shape


What does it mean for the training data to be generated by a probability distribution over datasets

Question: I was reading the Deep Learning book and came across the following para (page 109, second para):

The training and test data are generated by a probability distribution over datasets called the data-generating process. We typically make a set of assumptions known collectively as the i.i.d. assumptions. These assumptions are that the examples in each dataset are independent from each other and that the training set and test set are identically distributed, drawn from the same probability distribution as each other. This assumption enables us to describe the data-generating process with a probability distribution over a single example.The same distribution is then used to generate every train example and every test example. We call that shared underlying distribution the data-generating distribution, denoted $p_{\text{data}}$. This probabilistic framework and the i.i.d. assumptions enables us to mathematically study the relationship between training error and test error.

Can somebody please explain to me the meaning of this paragraph?
On page 122 the last paragraph, it also gives an example

a set of samples $\{x(1), \dots, x(m) \}$ that are independently and identically distributed according to a Bernoulli distribution with mean $\theta$.

What does this mean?
Here are a few more specific questions.

The probability distribution over datasets: What are the datasets? How is the probability distribution generated?
The examples are independent of each other. Can you give me an example of where the examples are dependent?
Drawn from the same probability distribution as each other. Suppose the probability distribution is Gaussian. Does the term "Same probability distribution" mean that all the examples are drawn from a Gaussian distribution with the same mean and variance?
"This assumption enables us". What does this mean?
Finally, for the last paragraph of page 122, it is given that the samples follow Bernoulli distribution. What does this mean intuitively?
Comment: Thank you. Your edits do clarify matters. It's still a rather broad question, but @sww's answer is already quite to the point.
Comment: The third sentence in the paragraph you quote is the key one. Can you tell us more specifically what is unclear about it?
Comment: @StephanKolassa Added details to the question.
Comment: I still don't understand this: "probability distribution over datasets". Over what datasets? Could someone give an example? Thank you
Answer:

Probability distrubution over datasets: What are the datasets? How is the probability distribution generated?

Once we can estimate the underlying distributions of the input data, we essentially know how they are picked and can do good predictions. (generative model). Normally, we can assume an underlying distribution according to what we believe (inductive bias). For example, if we believe that there is a high probability that values are close to zero, we can take a Gaussian distribution with mean $0$ and tune the parameters like variance when we train. Datasets are, for example, set of all coin tosses and the distribution assumed will be binomial. When we do say maximizing log-likelihood for the actual data points, we will get those parameters which make the dataset fit into the distribution assumed.

The examples are independent of each other. Can you give me an example of where the examples are dependent?

For example, we toss a coin and if we have a head we toss another otherwise we do not. Here there is a dependence between subsequent tosses

Drawn from the same probability distribution as each other. Suppose the probability distribution is Gaussian. Does the term "same probability distribution" mean that all the examples are drawn from a Gaussian distribution with the same mean and variance?

"This assumption enables us". What does this mean?

Yes. That is why (4) is said. Once you have a probability distribution from one example, you do not need other examples to describe the data generating process.

Finally, for the last paragraph of page 122, it is given that the samples follow Bernoulli distribution. What does this mean intuitively?

It means that each example can be thought of as a coin toss. If the experiment was multiple coin tosses, you would have each coin toss independent with a probability of head to be $\frac{1}{2}$. Similarly, if you choose any other experiment, the result of each example can be thought of as a coin toss or an n-dimensional dice.
Generating examples means getting a distribution closest to what we see in the dataset for training. That is got by assuming a distribution and maximizing the likelihood of the given dataset and outputting the optimum parameters.
Comment: Thanks a lot. Can you please explain how is the training and test data generated from the data generated process? Once we have the probability distribution from one example, we know the probability distribution of other examples. But how are the examples actually generated?
Comment: @rjmessibarca It doesn't matter who or what generated the examples but it is the examples we are given or can get which are generated following some distribution  known to us(optimization scenario) or unkown to us(machine learning issue).
Comment: What do you mean by "high probability"? Does it mean confidence level? And I notice this terminology comes out very often in machine learning theory. Such as something holds with "high probability". Looking foward to your response. Thanks


Resultados das requisições desordenados

Question: Tenho 1 textarea com varias linhas, a cada linha desse textarea tenho dados para efetuar uma requisição post em uma unica url, ele checa cada linha e me manda o resultado na tela via jquery, o problema e que os resultados que sao printados na tela não estam ordenados conforme os dados colocados no textarea, devia imprimir os resultados em forma de lista das linhas 1, 2, 3, 4 do textarea em sequencia, porem ele printa isso desordenadamente 4, 2, 1, 3 ele checa se um proxy e a porta funcionam exemplo 292.168.391.34|8080  e feita a requisição em uma pagina colocando os dados antes do separador | no input do proxy e apos o separador em outro input da porta, e com preg_match capturo a mensagem de conectado e com um if faço printar na tela a mensagem se foi bem sucedido ou nao juntamente ao lado da liinha testada, mais sempre os resultados voltam desordenados não batendo conforme a sequecia no textarea como resolvo isso  ?
Answer: Você precisa observar que o ajax é assíncrono então ele pode te dar a resposta de uma requisição que foi feita depois antes de uma que foi feita antes. Então para resolver isso você poderia fazer a primeira requisição e depois na função de callback dessa realizar a outra e assim por diante, na ordem que voce precisa. Não sei a sintaxe do jquery mas vai um exemplo:
<code>function callback2 () {
    ajax3(callback3);
}
function callback1 () {
    ajax2(callback2);
}
ajax1(callback1);
</code>

Resultados das requisições desordenados


NSUserDefaults deleting keys when close the app

Question: I need to delete keys when application will close. So what should I do?
Comment: If you need to delete these keys when the app closes, why are you putting them in the defaults system in the first place?
Answer: Delete keys from NSUserDefaults using the following code
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"yourKey"];

in your ApplicationDelegate method following which state are you meaning by "close the app":
- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application
- (void)applicationWillTerminate:(UIApplication *)application

Answer: Look in the documentation
- removeObjectForKey:

Removes the value of the specified default key in the standard application domain.