meu bubble sort nao funciona de jeito nem um

Question: Código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            int q = Convert.ToInt32(Console.ReadLine());
            string arrays = Console.ReadLine();
            string[] arraysint = new string[q];
            arraysint = arrays.Split(' ');
            int[] numbers = Array.ConvertAll(arraysint, int.Parse);
            int i;
            int save = 0;
            int j;
            int temp;
            int current = q - 1;
            int[] maior = new int[1];
            //int[] numbers = new int[q];
            for (j = 0; j < q; j++)
            {
              for (i = 0; i < current + 1; i++)

                {
                        if (current == 1)
                    {
                        goto final;
                    }
                    if (i == current)
                        {
                      if (current == save)
                        {
                            current--;
                        }
                        if (current < q - 1)
                        {
                            if (maior[0] == numbers[current] && maior[0] != 0)
                            {
                                current--;
                            }
                        }
                        temp = numbers[current];
                        numbers[save] = temp;
                     numbers[current] = maior[0];
                    current--;
                    }

               if (maior[0] < numbers[i])
                {
                        save = i;
                    maior[0] = numbers[i];
                }

            }
                maior[0] = 0;
            }
        final:
            Console.Clear();
            for (i = 0; i < q; i++)
            {
                Console.Write(numbers[i] + " ");

            }
            Console.ReadKey();
        }
    }
}

input:
5
5 4 3 2 1

Output:
1 3 2 4 5

Já fiz de tudo, mas não consigo resolver. Alguém me ajuda ai?
Comment: Você complicou bastante, tendo em conta que *bubble sort* são 2 `for` e 1 `if` com um `swap`, literalmente 6 linhas de código. Varias coisas que não fazem muito sentido, como por exemplo utilizar um array com uma casa para o `maior` quando pode utilizar uma variável normal. Mesmo a noção de `maior` para este algoritmo não é necessária. O mesmo se pode dizer em relação ao `goto`, que dificulta a visualização do fluxo do programa. Eu pessoalmente aconselhava a começar de novo, com calma e pensar na lógica necessária para o algoritmo, que é bem mais simples do que tem no momento.
Answer: Conforme nosso amigo @Isac comentou, você complicou bastante a lógica do bubble sort. Vou deixar abaixo uma classe que efetua a ordenação Bubble Sort, avalie o funcionamento dela e tente refazer seu exercício estudando cada ponto do algoritmo.
///
/// Classe responsável pelas técnicas de ordenação Bubble Sort
///
public class BubbleSort
{
    ///
    /// Ordena um vetor de números inteiros utilizando o algoritmo de Bubble Sort
    ///
    /// <param name="vetor">Vetor que será ordenado</param>
    /// <returns>Vetor ordenado</returns>
    public static int[] Ordernar(int[] vetor)
    {
        //Variável auxiliar que irá armazenar temporariamente um valor do vetor
        int numeroAuxiliar = 0;
        //Variável para informar se houve alguma troca no algoritmo, caso não houver troca significa que o vetor já está ordenado, então não precisamos continuar o processamento.
        bool trocou = false;

        // i determina o número de etapas para a ordenação
        for (int i = 0; i < vetor.Length - 1; i++)
        {
            trocou = false;

            // j determina o número de comparações em cada etapa e os índices a serem pesquisados para a comparação.
            for (int j = 0; j < vetor.Length - (i + 1); j++)
            {
                if (vetor[j] > vetor[j + 1])
                {
                    trocou = true;
                    numeroAuxiliar = vetor[j];
                    vetor[j] = vetor[j + 1];
                    vetor[j + 1] = numeroAuxiliar;
                }
            }

            //Se não houve troca podemos parar a execução do algoritmo de ordenação para evitarmos o processamento desnecessário
            if (!trocou)
                break;
        }

        return vetor;
    }

Para fazer a chamada do método de ordenação Bubble Sort basta fazer o seguinte:
//Exemplo da chamada do método de ordenação
int[] vetor = {5, 4, 3, 2, 1};

BubbleSort.Ordernar(vetor);

Comment: valeu eu refiz ele e dai funcionou meu erro era que eu estava so colocando o maior numero por ultimo ao invez de testar cada um
            `for (j = 0; j < q; j++)
            {
                for (i = 0; i < q; i++)
                {
                    if (i < 4)
          {
                        if (numbers[i] > numbers[i + 1])
                  {
                            temp = numbers[i];
                            numbers[i] = numbers[i + 1];
                            numbers[i + 1] = temp;
}
}
}
}
            Console.WriteLine(string.Join(" ", numbers));`
Comment: Por nada, que bom que conseguiu. Abraço!


Is this algebraic deduction true?

Question: Since $v_{1}^2 - 2v_1v_2 + v_{2}^2 > 0$ because $(v_{1} - v_{2})^2 > 0$, and
since $v_{1}^2 + 2v_1v_2 + v_{2}^2 > 0$ because $(v_{1} + v_{2})^2 > 0$.
Can we deduce that $v_{1}^2 - v_1v_2 + v_{2}^2 > 0$ because $(v_{1} - v_{2})^2$ $<$ $(v_{1}^2 - v_1v_2 + v_{2}^2)$ $<$ $(v_{1} + v_{2})^2$, for every real number $v_{1}$ and $v_{2}$.
Comment: The basic idea is correct. As SampleTime mentioned you need to fix the < and > to $\le$ and $\ge$. And as amWhy mentions, you need to consider the inequality switching around when $v_1v_2<0$ as opposed to $v_1v_2>0$. $v_1^2-v_1v_2+v_2^2$ remains in the middle so you can still conclude it is $\ge 0$
Comment: I guess you mean $v_1^2 - v_1 v_2 + v_2^2 \geq 0$ for every real $v_1, v_2$ ($\geq$ instead of $>$) because otherwise your inequality is wrong for $v_1 = 0, v_2 = 0$.
Comment: In the last expression, if $v_2 \lt 0,$ and $v_1 \geq 0$, then $(v_1+v_2)^2 \lt (v_1-v_2)^2$
Answer: The deduction is wrong: set $v_2 = -v_1$ your last inequality
$$
(v_1 - v_2)^2 < (v_1^2 - v_1 v_2 + v_2^2) < (v_1 + v_2)^2
$$
becomes
$$
4 v_1^2 < 3 v_1^2 < 0
$$
which is obviously wrong even if you replace the "$<$" signs with "$\leq$" signs.
You can instead rewrite your expression:
$$
v_1^2 - v_1 v_2 + v_2^2 = \begin{pmatrix} v_1 & v_2 \end{pmatrix} \begin{pmatrix} 1 & -0.5 \\ -0.5 & 1 \end{pmatrix} \begin{pmatrix} v_1 \\ v_2 \end{pmatrix}
$$
The matrix is positive definite so $v_1^2 - v_1 v_2 + v_2^2 > 0$ if $v_1 \neq 0, v_2 \neq 0$.

Is this algebraic deduction true?


Why does this proof that a dual space isomorphic to the original space work?

Question: I am extremely new to the concept of dual space and the notation $\mathcal{L}(V,W)$ which denotes the set of all linear transformations from $V\to W$. I read that the dual space $V^*=\mathcal{L}(V,\Bbb{K})$ is isomorphic to $V$, where $V$ is some vector space defined over $\Bbb{K}$. The "proof" (or perhaps intuition) that was given to me was that $\dim\mathcal{L}(V,\Bbb{K})=\dim(V)\dim(\Bbb{K})=\dim(V)$.
Two questions:

Rigorously, and I apologise if this is naïve but as I say I have never seen these concepts until approximately five minutes ago, why is $\dim\mathcal{L}(A,B)=\dim(A)\dim(B)$?

How is it a complete proof to just show that the dimensions of $V^*$ and $V$ are the same? Surely some more work needs to be done to show isomorphisms? For context, I have never actually seen a proof of isomorphism and do not know what proving an isomorphism in an abstract context like this entails.
Answer: It's important that we're talking about finite-dimensional vector spaces here.  If $\dim(A)=n$ and $\dim(B)=m$, then there's a $1$-$1$ correspondence between linear transformations $f:A \to B$ and $m \times n$ matrices.  That's because any such transformation is determined by its values on a basis for $A$, and those values in turn are determined by a column vector with $m$ components.  The dimension of the space of $m \times n$ matrices is $mn$.
It's also a theorem that any two finite-dimensional vector spaces over the same field with the same dimension are isomorphic to one another.  Choose a basis for each and map element $k$ of the basis for $A$ to element $k$ of the basis for $B$.  That results in a linear map that is onto a basis of $B$, and therefore is onto $B$, and that has trivial kernel.
Comment: Thank you for the clarification
Comment: Does this notion of a "vector" being a linear combination of the basis hold even when the "vector" space in question is something more abstract, such as a function space?
Comment: Yes, but such spaces are pretty likely to be infinite-dimensional, which adds complications.  The basic results still hold but you start needing things like the Axiom of Choice to prove them.  In that context, it's important to note that a vector is a linear combination of a *finite number of elements* from your basis.


Best technology for keywords to features mapping

Question: Source data = free text ("It's fresh and juicy and sweet")
Pre-defined "knowledge" =

"fresh" -> quality of a fruit
"juicy" -> quality of a fruit
"sweet" -> quality of a fruit
"sweet" -> quality of a candy

Which approach/technology would analyse the source data and assign the classes above (fruit/sweet) based on the keywords?
The goal is to later match the classified pieces of source data to user input (based on similarities).
Thank you!
Answer: One suggestion from Mahout IRC channel was NLTK:
http://www.nltk.org/book/ch07.html


Import swagger-codegen project into existing Android project

Question: Im trying to integrate a "module"-project generated by swagger-codegen, into my Android project.
Haven't worked that much with gradle before and the swagger-codegen creates a quite messy build.gradle from my point of view.
I have a hard time finding documentation on how to do this. And I feel a bit lost.
I used this method described in the FAQ
mvn clean package
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
 -i http://petstore.swagger.io/v2/swagger.json \
 -l java --library=okhttp-gson \
 -o /var/tmp/java/okhttp-gson/

So fare I tried to copy the source from the project that was generated by swagger-codegen and merge the two gradle build files. I removed the Junit tests because I couldn't get the Junit dependency working (Implementing Swagger-codegen project - Error:(23, 17) Failed to resolve: junit:junit:4.12). But then I got stuck with some conflict between the plugins?
The 'java' plugin has been applied, but it is not compatible with the Android plugins.

Here's the build.gradle:
import static jdk.nashorn.internal.runtime.regexp.joni.ApplyCaseFold.apply

apply plugin: 'idea'
apply plugin: 'eclipse'

group = 'io.swagger'
version = '1.0.0'

buildscript {
   repositories {
       jcenter()
   }
   dependencies {
       classpath 'com.android.tools.build:gradle:2.1.2'
       // classpath 'com.android.tools.build:gradle:1.5.+'
       classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
   }
}

repositories {
   jcenter()
   maven { url 'http://repo1.maven.org/maven2' }
}

if(hasProperty('target') && target == 'android') {

   apply plugin: 'com.android.library'
   apply plugin: 'com.github.dcendents.android-maven'

   android {
       compileSdkVersion 23
       buildToolsVersion '23.0.2'
       defaultConfig {
            minSdkVersion 14
            targetSdkVersion 23
       }
        compileOptions {
           sourceCompatibility JavaVersion.VERSION_1_7
           targetCompatibility JavaVersion.VERSION_1_7
       }

       // Rename the aar correctly
       libraryVariants.all { variant ->
           variant.outputs.each { output ->
               def outputFile = output.outputFile
               if (outputFile != null &&    outputFile.name.endsWith('.aar')) {
                    def fileName = "\u0024{project.name}-  \u0024{variant.baseName}-\u0024{version}.aar"
                output.outputFile = new File(outputFile.parent, fileName)
            }
        }
    }

    dependencies {
        provided 'javax.annotation:jsr250-api:1.0'
    }
}

afterEvaluate {
    android.libraryVariants.all { variant ->
        def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
        task.description = "Create jar artifact for ${variant.name}"
        task.dependsOn variant.javaCompile
        task.from variant.javaCompile.destinationDir
        task.destinationDir = project.file("${project.buildDir}/outputs/jar")
        task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
        artifacts.add('archives', task);
    }
}

task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier = 'sources'
}

artifacts {
    archives sourcesJar
}

} else {

apply plugin: 'java'
apply plugin: 'maven'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

install {
    repositories.mavenInstaller {
        pom.artifactId = 'XxxxXxxx'
    }
}

    task execute(type:JavaExec) {
       main = System.getProperty('mainClass')
       classpath = sourceSets.main.runtimeClasspath
    }
}

dependencies {
    compile 'io.swagger:swagger-annotations:1.5.8'
    compile 'com.squareup.okhttp:okhttp:2.7.5'
    compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'joda-time:joda-time:2.9.3'
   // testCompile 'junit:junit:4.12'
}

Am I doing something complete wrong here? What is the correct way to implement swagger-codegen code into my project?
Answer: The swift way to import it was to compile the swagger generated project then copy the .jar file to my android project and add its as a library.
Comment: Generating the .jar (and importing later) file after opening the Swagger project worked for me, thanks!
Answer:
I have a hard time finding documentation on how to do this. And I feel a bit lost.

You could clone the Android swagger-codegen example.
(which does use Junit, so I'm not sure what error you got)
Unless that's what you mean by

So far I tried to copy the source and merge the two gradle build files

To which, I ask, what two Gradle files? It looks like you merged an Android Gradle file with a Java Gradle file, which seems to causing more issues because you are getting...

The 'java' plugin has been applied, but it is not compatible with the Android plugins.

Which seems pretty self explanatory when you have this line
apply plugin: 'java'

It's not too clear what you are trying to do here other than check the build target
if(hasProperty('target') && target == 'android')

Comment: I see. I looks like you generated a Java one, though, not an Android one
Comment: I would agree with you, but I'd need to read into Swagger-codegen more to give a definite answer
Comment: Thanks for the great hints! I clarified the question a bit about what I meant by the source. But I shall take a look at the example source.
Comment: The two build gradle files I mean is the one that is found in the project that swagger-codegen generated and the one that is in the original Android project
Comment: Maybe I generated the code wrong In some way? Maybe that's why it wan'ts to use apply plugin:  'java'?
Comment: Yeah that's probably it!
Comment: In the FAQ it says "The Java SDK is also compatible with Android." and they recommend to generatet it with "-l java".


The probability that the size of a set is N after observing M unique elements from a sample of X (with replacement)

Question: Problem
Given a set of unknown size, X elements are sampled with replacement. Of these sampled elements, M elements are unique, meaning (X - M) elements were chosen more than once. Knowing this, what is the probability that the set has size N?
Related question on SE
If a set has n elements and x elements are selected with replacement, what is the probability that m unique elements are selected? answer
Answer: We require the probability $\operatorname{Pr}\left(N = n\middle| M = m\right)$ after observing $m$ unique elements sampled from a sample size of $X$. By Bayes' theorem (where $X$ has been suppressed in the notation):
$$ \operatorname{Pr}\left(N = n\middle| M = m\right) = \dfrac{\operatorname{Pr}\left( M = m\middle|N = n\right)\operatorname{Pr}\left(N = n\right)}{\operatorname{Pr}\left( M = m\right)}$$
From this it appears that the problem is ill-defined without knowledge of the prior distribution $\operatorname{Pr}\left(N = n\right)$. However if we proceed with the mindset that '$N$ is equally likely to be anything' (in the positive integers), then we could choose the improper prior that $\operatorname{Pr}\left(N = n\right) \propto 1$. This allows us to take
$$ \operatorname{Pr}\left(N = n\middle| M = m\right) \propto \operatorname{Pr}\left( M = m\middle|N = n\right) $$
where the right-hand side is the same probability as from the related question. Hence this expresses that the desired probability is proportional to the likelihood, and we can obtain a valid figure for the probability through normalisation:
$$ \operatorname{Pr}\left(N = n\middle| M = m\right) = \dfrac{\operatorname{Pr}\left( M = m\middle|N = n\right)}{\sum_{i = m}^{\infty}\operatorname{Pr}\left( M = m\middle|N = i\right)} $$


Examples containing all generality

Question: As Paul Halmos said:

...the source of all great mathematics is the special case, the concrete example. It is frequent in mathematics that every instance of a concept of seemingly great generality is in essence the same as a small and concrete special case.

This quote is similar to one of Hilbert:

The art of doing mathematics consists in finding that special case which contains all the germs of generality.

I want to know: What are some good examples of special cases containing all generality?
One answer per post. Community wiki?
Answer: In some sense, the theory for the classification of finite-dimensional complex simple Lie algebras and their linear representations is to a large extend given by understanding the theory for the special case of the Lie algebra $\mathfrak{sl}_2(\Bbb C)$.

Examples containing all generality


Access build config extra properties set using kotlin DSL

Question: In my android application I am setting some extra properties which I should be able to get via build config.
android {
extra.apply {
    set("version", "AN-1.15")
}
//...rest config
}

The build config file I get is
public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String LIBRARY_PACKAGE_NAME = "com.oads";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "dynamicNativeExoplayerSsaiCommon";
  public static final String FLAVOR_exoplayerVersion = "exoplayer";
  public static final String FLAVOR_common = "common";
}

I don't see the version tag in build config.
Answer: I don't think those properties come from project properties (which is what you're setting using extra). In my project (which is old, so this might have changed), we set them using:
android {
  buildTypes {
    debug {
      buildConfigField("String", "version", "AN-1.15")
    }
  }
}


How can I embed a node inside on another node?

Question: In Drupal 7 I have a content type created by admin (say content type X), And the other part i have a content type created by users (say content type Y).
Now that is what I do when a user creates content type Y, he can select a node of content-type X to embed node x in node Y.
Without link title node by "References Module" or coding html by "node_embed Module".
Comment: Welcome to Drupal Answers! Your question is not quite clear. Can you try to re-phrase it to make it easier to understand what you want and where you fail? Also, please include information about what you have already tried or what resources you have used so far to try to solve your problem. This will make it easier for others here to provide an answer to your question.
Answer: You can use entityreference together with display suite and have the display of the entityreference field set to rendered entity. Using rendered entities you can can render any entity with a view mode you need for your display. See this question if you want to create a custom template for the output of that node: How to provide template for particular view mode?
Comment: AFAIK entity reference or node reference should be just fine. You don't need the quite heavy Display Suite for that.


Are clusters in social sciences globular?

Question: Many clustering algorithms require globular (gaussian) clusters. Main example is k-means. If clusters are not globular, these methods can bring wrong results.
In social sciences, data is often clustered by these algorithms (market segmentation is very common example). My question then is whether there are some reasons why we should regard clusters from social surveys as globular (and therefore appropriate for methods like k-means).
An example of social data that could be clustered is mentioned in my previous question. I asked my students to rate selected interest (1-5 scale) and the task then could be to cluster students according to similar interests.
Comment: Many clustering methods indeed prefer to create spherical clusters, but far not all. Clusters in social sciences are usually assumed to be ellipsoid, not necessarily spherical. (In other domains, such as image recognition for instance, clusters often are curved.) The issue of shape, however, implies that the data exist in euclidean or similar metrical space. In social sciences we often deal with categorical data for which such space is inappropriate, so we won't speak of shape.
Comment: It is not necessarily the case that Likert scaled items are Euclidean; change the coding from 1-2-3-4-5 to 1-4-5-6-7 and you change the distance, and that's OK if they are only ordinal.
Comment: You may be disappointed, but one of the main reasons for k-means' popularity is its simplicity, not necessarily its theoretical justifications. k-means is known to have several important flaws.
Comment: @ttnphns, categorical data are also used in social sciences, but in this question, I speak only about numerical data. For example, when factors are created from likert items and then data is clustered.
Comment: With likert-type items much depends on how subjects perceive the task. If they feel the survey is "normative" or "formal" they are likely to narrow the range they use on the scale, so if they think in terms of prototypes on some items and not other items there will be spherical clusters in the data. But if they feel the survey is "personal" and asks their subjective expertise they will use all the range of the scale for those items where they don't think in terms of prototypes, and the clusters will be oblong.
Answer: Technically, the clusters in k-means are not globular, but Voronoi cells. It's repeated over and over in books; and indeed there are good reasons why k-means works best when the clusters are spherical and of the same extend.
But: does the clustering actually need to be perfect?
In many use cases, there is no such thing as a "correct" clustering. Most often anything better than random will do.
k-means is then very convenient, because it not only partitions your data into a guaranteed low number of clusters (i.e. k) much better than random. But also these clusters are convex (i.e. of relatively simple shape), exhaustive (all objects are clustered, not "outliers" remain), don't overlap (more advanced techniques may produce overlapping clusters or hierarchies of clusters) and - which probably is most important to many users - are represented by a simple, data-like representative: the cluster mean.
So if you just want to have a heuristic to reduce your data set to k representative objects, k-means is a really good heuristic.


Query and sort by field on entity referenced object

Question: I have a custom content type that has an entity reference field, that refers to an existing node from a different content type.
I'm performing the query like so
<code>$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue');

$nids = $query->execute();
</code>
Each of these issue nodes have a field_publication field that refers to a publication node. Each of these publication nodes have a field_permission_category that I'm grabbing like so.
<code>foreach ($nids as $nid) {
   $node = NODE::load($nid);
   $pub = $node->field_publication->entity;
   $pub_permission = $pub->field_permission_category->value;
}
</code>
But I want to be able to order the results of the initial query by the value of field_permission_category from the referenced field, but I'm not sure how to go about that, and I'm not even sure that's possible. Basically I want to be able to do
<code>$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue')
->sort('field_publication->entity->field_permission_category->value', DESC);
</code>
Can you sort a query by a field inside a referenced node?
Comment: Not sure if it does work (don't have time to test) but I think if there was a way it would be something like `->sort('field_publication.entity.field_permission_category')`
Answer: The answer by Clive is correct.
I  used this query for a project :
<code>$query->sort('field_projets.entity.field_date_mise_en_prod', 'DESC');
</code>
'field_projets' is the field name of the entity reference field on my node.
And 'field_date_mise_en_prod' is the name of a date field belonging to the referenced entity .
You can also use this syntax on conditions.
Exemple :
<code>$query->condition('field_tags.entity.name', 'cats');
</code>
You asking for a tag with the name 'cats'.


error when deleting view

Question: when I try to delete a view from the views module, I receive the following error:
error_1
Trying to save a new view shows this:
error_2
Any idea how to fix this?
I also cannot delete the view manually as my phpadmin tells me that there is an error and that I have to configure session.save_path... but I cannot find any file named session.save_path on my server.
Please let me know if you ever had this errors and if you know how to fix this. I invested 50 hrs to develop new functionality and I cannot risk the website goes down for days...
Thanks in advance!!
Comment: 1) The first of the two errors you link to could not be causing deletion to fail. Something else must be happening as well. Have you checked the logs? 2) What  if you try to create a new View with a different name? 3) Please don't link to images outside of the site. Preferably just copy the error messages into the question, or attach the images to the it.
Comment: I am not allowed to post images as my profile has not the correct status.. so for now I linked them through my website. where can I check the logs? trying to enable the database logging shows:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'usr_web181_2.watchdog' doesn't exist: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp)
Answer: It sounds like you've got some pretty serious problems here.
The fact that you can't use PHPMyAdmin because of the session.save_path setting (which is in php.ini by the way, it's not file name) would suggest that something on your server has changed. At a guess I'd say your web server no longer has write access to the session folder, but without seeing the full error message it's hard to say.
The fact that the you can't enable the db log module is also quite worrying. That module defines the watchdog table upon install so the fact that it's missing might suggest Drupal is having problems creating database tables.
The best advice I can give is to get a local version of the site up and running, with permissions for files/databases set up in a way you know is correct, and see if you still have problems.
If you do, then you know that the problem is somewhere else and you should start methodically disabling and uninstalling modules until you can narrow down the culprit.
If you don't, then you know the problem is with the live server configuration.
Comment: This morning I was able to log in to PHPMYAdmin and I ran a repair on all tables. Post to that, I deactivated unused modules and deleted them. Deleted the content auf  "semaphore" and "sessions" table, deleted cache and tried again to work with views. WORKING! Was able to delete and to create views.. perfect!!!
Comment: Glad to hear you got it sorted, that sounded like a nightmare for a minute there!

error when deleting view


In App Purchase Non-Consumable - Performance - App Completeness iOS 14.2

Question: Issue I am facing is this below:
"We found that your in-app purchase products exhibited one or more bugs when reviewed on iPhone running iOS 14.2 on Wi-Fi."
"When validating receipts on your server, your server needs to be able to handle a production-signed app getting its receipts from Apple's test environment. The recommended approach is for your production server to always validate receipts against the production App Store first. If validation fails with the error code "Sandbox receipt used in production," you should validate against the test environment instead."
I have implemented in-App Purchase (Non-Consumable), Its working perfectly fine in Buy and Restore etc. Apple Rejects with the above reason.
What I am doing:

Using SwiftyStoreKit
Click Buy Button
SwiftyStoreKit.retrieveProductsInfo
SwiftyStoreKit.purchaseProduct
On Success ( SwiftyStoreKit.finishTransaction )

Restore:

Click Restore
SwiftyStoreKit.restorePurchases

Please let me know if need more information or code etc and what I am doing wrong which rejected the app.
Apple Recently Replied me as well this below message:
"Regarding purchasing in-app purchases, we continue to be unable to buy the full version of the app. When we tap on the button to buy, the app continues to load indefinitely.
We are not able to provide feedback on app concepts or features, but we recommend evaluating your suggestions against the App Store Review Guidelines, as well as the iOS Developer Program License Agreement (PLA), and the iOS Human Interface Guidelines."
Comment: did you get solution to this
Comment: @AmitVerma no not yet. Don't know whats the issue. People are saying that try to upload again but if that rejected again then it will make app approval process lengthy
Answer: So I found the Solution for this. When ever you receive error something like above, here are the steps you need to check and do.

Check first your In-App Purchase Implementation. Are you doing it correctly, ending the transaction etc.
Check what is the latest version of iOS supported by your XCode. If its lower than the shown in the issue like in mine ( xcode ios version was 14.0 and issue with 14.2).

For that you need to just download the latest XCode which support that iOS Version and make a build and then submit for review. It will surely work.


What if in $ aw^2 +c +bw =0 $ $ a,b,c $ are not real ? $ w $ is the cube root of unity.

Question: I was just solving a problem in which i was stuck that if  $ a,b,c $ are real then Is it true that if $ aw^2 +c +bw =0 $ then $ a=b=c $ ? What in case if $ a,b,c $ are not real?
Comment: As a non-real cube of unity.
Comment: If $a,b,c$ are not necessarily real, you may not have $a=b=c$. For example, you could have $a=0, b=1, c=-w$.
Answer: You know that $w^2=-w-1$. Suppose that $a+bw+cw^2=0$. Replacing $w^2$ we find that $(a-c)+(b-c)w=0$.
If $b-c\neq0$, then we have that $w=-\frac{a-c}{b-c}$, and the right hand side is real: as $w$ is not real this is absurd. It follows that $b=c$ and that our equation is in fact that $a-c=0$. We thus conclude that $a=b=c$.
Comment: If you think there is some problem, you should explain what problem you think there is. Making us guess what you are thinking is not exactly a good idea, you see...
Comment: My answer assumes the coefficients are real. If they are allowed to be any complex numbers, then **obviously** the answer to the question in your title is no. Take $c=-w$, $b=1$ and $a=0$ in the equation of your title, for example.
Comment: I am sorry, but I don´t see any point in repeating what I already wrote three times.
Comment: Is the result i got using it also true then
Comment: Sure it is.${}{}$
Comment: Suppose as @user8734617 said it will hold even if $ a,b, c $ are not equal like $ a=w $ $ b=w^2 $ $ c=-2 $ then putting in $ w =  - (a-c)/(b-c) $ we get w = -1 which is not true
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/73224/discussion-between-jasmine-and-mariano-suarez-alvarez).
Comment: $ w =  - (a-c)/(b-c) $ can we write this if a,b,c are not real
Comment: If $a$, $b$ and $c$ are allowed to be non-real, then the question in the title of your question has an obvious negative answer. Just as I wrote two comments above.
Comment: Yes i believe the title has an obvious answer. I did not have a better title flashing so i asked something deviated from what i exactly wanted to know,but when we go on solving the equation for example as you got $ w =  - (a-c)/(b-c) $ we get contradictions.
Answer: Yes, it is true. Note that $\omega^2=-1-\omega$. Therefore$$a\omega^2+b+c\omega=0\iff-a+b+(-a+c)\omega=0.$$Since $1$ and $\omega$ are linearly independent, it follows from this that $-a+b=-a+c=0$. In other words, $a=b=c$.
Answer: For real $a,b,c$ it is true. Note $w^2=\overline{w}$ so $0=aw^2+bw+c=a\overline{w}+bw+c=(a+b)\Re(w)+(b-a)\Im(w)+c$, which then implies $a=b$, and then, because $\Re(w)=-\frac{1}{2}$: $-a+c=0$, i.e. $a=b=c$.
For complex $a,b,c$ it is not true. Take $a=w, b=w^2, c=-2$.
Comment: I am talking about contradiction thing. I am not obtaining w
Comment: $ w =  - (a-c)/(b-c) $ and put the values of $a =w$ $ b=w^2 $ $c= -2$ then we get w=-1 which is not true
Comment: @Jasmine $w$ is already known... The point is that $w$, $w^2$ and $-2$ are not all equal to each other, yet $aw^2+bw+c=0$ holds. Your thinking is also correct, but requires borrowing a little from the answer by Mariano Suárez-Álvarez...
Comment: @Jasmine Sorry, I updated my comment above.
Comment: Oh okk I see. I am very confused as to me both of you appear to contradict each other but both of you seem to be correct at your places.
Comment: @Jasmine Nope, Mariano's answer is good, no contradiction there at all! I just wanted to show on a concrete example that the statement does not hold for complex $a,b,c$. I think he has another example in his comments.
Comment: @Jasmine Note also Mariano did his work assuming $a+bw+cw^2=0$ rather than $aw^2+bw+c=0$, i.e. in his answer $a$ and $c$ are *swapped*. The way *you* wrote it, his formula turns into $w=-\frac{c-a}{b-a}$ and then you will see that there will be no contradiction.
Comment: I was completely out of mind in doing such a big mistake. I am really very sorry.
Answer: Complex roots of real polynomials are found in conjugate pairs.
If $\omega$ is a root of the polynomial $ax^2 + bx + c$ then $\bar \omega$ is also a root.
$ax^2 + bx + c = a(x-\omega)(x-\bar\omega) = a(x^2+x +1)$


How could you use comparison test to solve this series?

Question: Determine whether this series converges:
$\sum_{k=1}^{\infty} \frac{\sqrt{k}}{k^2+3}$
I am thinking of using the comparison test to prove that the series converges. I will compare this series to $\frac{1}{k\sqrt{k}}$. Is this correct? I'm not sure how it works. If the comparison test does not work, can you suggest other tests that can be applied here?
Answer: You're on the right track.  Specifically, note that for all $k \ge 1$, we have
$$\frac{\sqrt{k}}{k^2 + 3} < \frac{\sqrt{k}}{k^2}$$ becaues the LHS denominator is strictly larger than the RHS denominator.  Then since the RHS simplifies to $$\frac{\sqrt{k}}{k^2} = \frac{1}{k^{3/2}},$$ we see that $$\sum_{k=1}^\infty \frac{\sqrt{k}}{k^2 + 3} < \sum_{k=1}^\infty \frac{1}{k^{3/2}}.$$ Since the sum on the right is convergent, and the sum on the left is obviously positive (because all of its terms are positive), the sum on the left must converge.
Answer: The method for rational functions and some other functions, to find the right $p$-series for direct or limit comparison is the same:  First find a value of the index after which all terms are positive.  Then, from the numerator and denominator factor out the leading power of the index, leaving something whose terms have constant (mostly zero) limits.  Using your problem as an example...
$$  \frac{\sqrt{k}}{k^2+3}  $$
The leading (highest) power of $k$ in the numerator is easy: $k^{1/2}$.  The leading power in the denominator is also easy: $k^2$.  We factor those out of the numerator and denominator, respectively.
\begin{align*}
\frac{\sqrt{k}}{k^2+3} &= \frac{k^{1/2}}{k^2} \cdot \frac{1}{1+3/k^2}  \\
    &= \frac{1}{k^{3/2}} \cdot \frac{1}{1+3/k^2}  \text{.}
\end{align*}
We have essentially factored the general summand is "the power of $k$ that is most nearly parallel to the summand" times "a correction multiplier that rapidly approaches (in this case) $1$".
Okay...  We factored it.  So how do we use it?  We "build back up" to the general term you have.  We start by examining the nearly constant part.
$$  1 < 1 + 3/k^2 \leq 1+3/1^2 = 4  $$
That may seem fast.  Building up this inequality is good warmup for the build-up we have after, so let's work through this one.  We start with the low end of the index.
\begin{align*}
    k &\geq 1  \\
    k^2 &\geq 1^2 = 1 & &\text{squaring positives is monotonic}  \\
   \frac{1}{k^2} &\leq \frac{1}{1^2} = 1  & &\text{reciprocals reverse inequalities}  \\
    \frac{3}{k^2} &\leq \frac{3}{1^2} = 3  \\
    1 + \frac{3}{k^2} &\leq 1 + \frac{3}{1^2} = 4  \\
\end{align*}
To get "$1 < 1 + 3/k^2$" we just use that $3$ and $k^2$ are positive, so their ratio is positive so we have added something bigger than $0$ to $1$ yielding something bigger than $1$.
So, where are we?
$$  \frac{1}{k^{3/2}} \cdot 1 <  \frac{1}{k^{3/2}} \cdot \frac{1}{1+3/k^2} \leq \frac{1}{k^{3/2}} \cdot 4  \text{.}  $$
This strongly suggests a comparison test with the converging $p$-series $\sum k^{-3/2}$.  The direct comparison test will succeed if the general term of your series is less than the general term of the converging $p$-series.  (Positive and smaller than converging is converging.  Positive and bigger than diverging is diverging.)  So let's build up (again).
\begin{align*}
1 &< 1 + \frac{3}{k^2}  \\
k^{3/2} \cdot 1 &< k^{3/2} \cdot \left( 1 + \frac{3}{k^2} \right)  \\
\frac{1}{k^{3/2} \cdot 1} &> \frac{1}{k^{3/2} \cdot \left( 1 + \frac{3}{k^2} \right)}  \\
\frac{1}{k^{3/2}} &> \frac{1}{k^{3/2}} \cdot \frac{1}{1 + \frac{3}{k^2}}
\end{align*}
The left-hand side is the general term of the given series.  The right-hand side is the general term of the converging $p$-series.  By the direct comparison test, the given series converges.
Suppose the inequality had gone the other way.  (The easiest way to do this is to make the general term of the given series be  $\displaystyle \frac{\sqrt{k}}{k^2 - 3}$.  Then the direct comparison test will give us no information.  (Positive and bigger than a converging series could be anything.))  The limit comparison test, however, will tell us the same thing the factored form
$$  \frac{1}{k^{3/2}} \cdot \frac{1}{1 - 3/k^2}  $$
tells us:  The $p$-series $\sum k^{-3/2}$ most closely parallels this series up to a nearly constant multiplier between $-2$ and $1$.  (This is an example of the first step way back at the beginning of this post.  "First find a value of the index after which all terms are positive."  $k = 2$ is such an index.  So we should frame our series as the mixed signs part, $\displaystyle \sum_{k=1}^1 \frac{\sqrt{k}}{k^2 - 3}$ and the positive part, $\displaystyle \sum_{k=2}^\infty \frac{\sqrt{k}}{k^2 - 3}$.  The finite sum is just some number, so does no affect convergence.  The positive part then is subject to the above factoring and comparison tests.)


Show a 404 for not-found subdomains instead of showing root domain's content

Question: I'm using nginx. What I'm trying to achieve:

A root domain domain.com which gets contents from /var/www/domain.com
A subdomain sub.domain.com which gets contents from /var/www/sub.domain.com
Any other subdomain *.domain.com (where * != sub) should get contents from /var/www/404

If this isn't clear: it is similar to the StackEchange setup, where http://somesub.stackexchange.com/ gives a 404.
I succeed in the first using two server blocks with different server_names. However, how can I setup nginx to link to /var/www/404 when no server block matching the subdomain is found?
With a basic setup, all subdomains that are not found return the same contents as the root domain.
I'd like to make this generic, so that if I add another server block for sub2.domain.com, I don't have to change the block for the 404.
The code I'm using now:
server {
    listen 80;
    server_name domain.com;
    root /var/www/domain.com;
    charset utf-8;

    location / {
        index index.php index.html;
        autoindex on;
    }

    location ~ \.php$ {
        fastcgi_pass    127.0.0.1:9000;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include         fastcgi_params;
    }
}

server {
    listen 80;
    server_name sub.domain.com;
    root /var/www/sub.domain.com;
    charset utf-8;

    location / {
        index index.php index.html;
        autoindex on;
    }

    location ~ \.php$ {
        fastcgi_pass    127.0.0.1:9000;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include         fastcgi_params;
    }
}

Answer: Nginx, like Apache, will always use its first domain in the config list as its default. In your case, that means that for any domain that doesn't have its own config, it will choose the config for domain.com as that is the first one.
So the solution is simply to set up another domain that contains only a 404 page, and have that be the first domain listed. You can then add as many specific domains as you like; the first one will only be used when there's no other matching domain name in the config file.


Econometrics Random Effect model

Question: In R, I wrote the following lines of code - I need to "translate it" into a mathematical expression :
<code>random_effect <- plm(dvexptot ~ age + sex + educyr + inctot + hinotcov + workev + himcare,
                   data = df_clean, model = "random", effect = "individual",
                   index = c("id", "year"))
</code>
In the case of a pooled OLS regression, it's easy enough :
$$y_{it} = \beta_0 + \beta_1 age_{it} + \beta_2sex_{it} + \beta_3educyr_i + \beta_4inctot_{it} + \beta_5hinotcov_{it} + \beta_6workev_i + \beta_7himcare_{it} + \epsilon_{it}$$
On the other hand, I'm unsure for the random effect model
Answer: Just add a $\mu_i$ term for the RE.

Econometrics Random Effect model


Docker - Run Container from Inside Container

Question: I have two applications:

a Python console script that does a short(ish) task and exits
a Flask "frontend" for starting the console app by passing it command line arguments

Currently, the Flask project carries a copy of the console script and runs it using subprocess when necessary. This works great in a Docker container but they are too tightly coupled. There are situations where I'd like to run the console script from the command line.
I'd like to separate the two applications into separate containers. To make this work, the Flask application needs to be able to start the console script in a separate container (which could be on a different machine). Ideally, I'd like to not have to run the console script container inside the Flask container, so that only one process runs per container. Plus I'll need to be able to pass the console script command line arguments.

Q: How can I spawn a container with a short lived task from inside a container?
Answer: You can just give the container access to execute docker commands. It will either need direct access to the docker socket or it will need the various tcp environment variables and files (client certs, etc). Obviously it will need a docker client installed on the container as well.
A simple example of a container that can execute docker commands on the host:
docker run -v /var/run/docker.sock:/var/run/docker.sock your_image

It's important to note that this is not the same as running a docker daemon in a container. For that you need a solution like jpetazzo/dind.
Comment: Although sometimes may be needed, such a solution has freate security risks. See more here https://stackoverflow.com/questions/40844197/what-is-the-docker-security-risk-of-var-run-docker-sock
Comment: Thanks for the reply. I will give this a shot. I'm guessing this won't work if the console script is supposed to run on a different host, since the socket is being passed in is from the Flask host. How would I go about passing in the socket from a different machine?
Comment: The trickiest part of that is figuring out how to identify that host, and of course, making sure that host is reachable from the Flask container via tcp. Then the Flask container needs the host client certs. It actually sounds like a nightmare – is there a good reason not to just make sure both run on the same host?


Image Insert and Theming

Question: When you have have an image field on a content type, and use the Insert button to place it into the body, do you get a chance to theme it in Drupal 7?  theme_image doesn't seem to get called, and I am not seeing anything the the API refernce.  I know this is JS functionality on the edit page, but there could be ways to still theme it.  Thanks.
Edit for clarification:
When you use Insert to get images into the body, just the image gets inserted and the theme system gets bypassed.  If you use the image as a field, then all modules get a chance to theme it.  This results in inconsistent image usage on a site.
For example, if I use an image as a field, the RDF module will tack on some metadata and my custom theme_image will do its thing.  When I use Insert with the same image, just the plain image gets put in.
On previous projects, I have added some javascript to the theme to fix these discrepancies, but the code needs to be adjusted each time something changes with how images get themed.  Ideally, I am searching for a method to allow images-as-fields and image-inserted-into-body to be themed the same way, without resorting to Javascript or manually editing the images in the body.  If this isn't built-in functionality, I may try to patch the Insert module to allow it.
Comment: I haven't been able to find any modules that allow you to change wrapping HTML and img tag properties (meta data) within an Insert module type functionality. If you're looking to create custom functionality yourself, I would probably recommend patching or forking Image Resize Filter instead of Insert, since Image Resize Filter already provides options to manipulate items being inserted with the Insert module.
Comment: That's what I figured.  I did a long search for a D6 solution a while ago, and was hopeful that things had changed for D7.
Answer: I will assume you are referring to using the Insert module.
Once you have inserted an item into a node field (most likely the body), it then becomes a simple string of text within that field and is processed as such. There is no longer anything linking it to the image field that you used to upload it, and no way to hook onto it and perform any programatic changes. The only "theming" that can be done to the image at this point is CSS changes.
You could potentially add optional styles for the images via your WYSIWYG's configuration or you could use the Image Resize Filter module to allow the node editor to change the size of the image and/or create a link to the full-size image.
If you could give some details about what exactly you are wanting to do to that images that have been added via the Insert module, there might be another solution someone can suggest.

Image Insert and Theming


How to render the content in which the user is mentioned in?

Question: I render the Views page on the user profile page to show the content this user created.
Now the scenario changed and I have to render the content in which this user has been mentioned using Entity Reference fields. For just one field there is no problem, since I did it using Contextual Filter ... but when I'm trying to do so using multiple different fields (for different content types), then I do not get any results.
Is it possible to achieve this using UI or is it possible to put a custom query somewhere to get results and benefit from the Views fields?
Thank you all in advance!
Answer: If you think about writing this as a pure SQL query, what you are trying to do is have multiple WHERE conditions that are separated by OR operators.
Using OR operators with Conextual Filters is not possible out-of-the-box with Views. All Contextual Filters are added as AND filters.
There appears to be a module that adds this option, although I have not tested it. It doesn't have an official release, but appears to be in use by over 2000 sites, so might be worth a try: https://www.drupal.org/project/views_contextual_filters_or
Ultimately, however, this could be solved with a different data architecture. Is there a reason you have multiple different fields for referencing the user? Could these fields be combined into one base field, with instances on various content types? If so, then you can do it with a single Contextual Filter.
Answer: It can be done using views only, no need for a contextual filter.
Create a user view instead of a content view.
Add the relationship content referencing user using the field entity reference field.
Add the content fields that you want, using the relationship for each of them.
Add the filter user = currently logged in user, using the relationship.
The result is all content of all content types, that reference the currently logged in user.


Product page with 2 times css

Question: Im trying to create a product page, but my boss wants different css for every next photo and text. I need 2 different css styles, that will aply on where the image is. Like the first block will have the image at the left and the second block will have the image on the right.
This is basicly what im trying to do :
I think I could do this with css and some custom classes? So that every added block with text and image will align itself properly without having to edit the css for every block everytime you create a new block. If someone could point me in the right direction on how to achieve this, that would be great !:)
Answer: If you are achieving this html by using views then set the rows even and odd patterns and do the CSS according to the even and odd class.

Product page with 2 times css


How to use CGAffineTransformMakeRotation?

Question:
I want to draw text use Quartz 2D. The "menu" direction is wrong. I want "Menu" still readable and have 45 degree with X-axis. Below is my code:
<code>CGContextSelectFont(context, "Arial", 12, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextFill);

CGContextSetRGBFillColor(context, 0, 0, 0, 1); // 6
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1);

CGContextSetTextMatrix(context, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));
CGContextSetTextMatrix(context, CGAffineTransformMakeRotation(45));
CGContextShowTextAtPoint(context,10, 10, "Menu", 4);
</code>
Answer: CGAffineTransformMakeRotation expects angle in radians, not in degrees.
<code>#define DEGREES_TO_RADIANS(x) (M_PI * (x) / 180.0)
...

CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(45));
</code>
Comment: You should put extra parenthesis around `x` in the macro to make it safe to use with expressions like `30+15`. With you macro that would lead to `(M_PI * 30+15 / 180.0)` which is the same as `((M_PI*30) + (15/180.0))`. A safer macro would be `#define DEGREES_TO_RADIANS(x) (M_PI * (x) / 180.0)`
Answer: <code>[view setTransform:CGAffineTransformMakeRotation(M_PI / 2)];
</code>
Comment: or just `M_PI_2`, which is `M_PI / 2`


NVDA Skips first focusable element on initial page load when tab pressed

Question: Recently while attempting to make my site accessible I stumbled upon a bizarre problem.  During the process of setting up a 'skip navigation' link, I noticed that when the page is initially loaded (by 'initially loaded', I mean in a clean browser session, not on refresh—as NVDA keeps a track of the last focused element so results would be dependent on that).
When the page loaded and the tab key pressed, the element that received focus was the 2nd element (which as you will see from the below simplified example, is the site logo/name (also an anchor link)).
The problem doesn't show when NVDA is not running... everything works as expected, Firefox works perfectly fine with or without NVDA running but the problem is present in Chrome, Edge and Opera desktop.  I've not tested it on any other browsers thus far.
Please note, because of the nature of the problem, I didn't include a runnable code snippet or fiddle (as there would be other elements on the screen and, as I said this problem only shows with a new browser session/clean page load.  Here is some simplified code to show the problem...
CSS
body, html {
  margin: 0;
}

.skip-nav {
  position: absolute;
  margin: 10px 0 0 10px;
  white-space: nowrap;
  display: inline-block;
  padding: 0;
}

.skip-nav a {
  position: absolute;
  left: -1000px;
  border: 2px solid blue;
  border-radius: 2px;
  background-color: black;
  padding: 5px;
}

/* Move link into viewport when focused */
.skip-nav a:focus {
  left: initial;
}

nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 30px;
  background-color: darkblue;
  padding: 10px;
  color: white;
}

nav ul {
  list-style: none;
}

nav li {
  display: inline;
  margin: 0 5px 0 5px;
}

a {
  text-decoration: none;
  color: white;
}

a:hover {
  color: rgb(165, 165, 165);
}

HTML

  Skip navigation

  Name

Home

Services

About

Contact

  Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi dolores voluptates temporibus culpa in quia et magni laborum architecto fugit!

Things I have tried
The first thing I did was to disable all my browser extensions/test in Chrome incognito mode. Then I tried in the other browsers mentioned above.  I also tried other focusable elements (such as a button and even a div with the 'tabindex=0' attribute set.  I also put my initial link on its own (not within a parent div).  All gave the same results.
Workaround
Instead of placing the link in a div, I put it in an ul/li... and it works perfectly...

        I should focus on first tab press
        I should focus on second

         When you press tab after this page has loaded (at least for me), the initial tab press will focus the second
         link for some reason.

         This seems to happen however I present the link (on its own, wrapped in a div, section, or even a ul/li with the
         list-style set to 'none')  :-(.

Comment: Sorry took me a while to get back to this, the `` trick I mentioned does work!
Comment: Thanks for the update Graham, I actually tried it and yes, it does work (still not fully understanding *why* it works though)... however the screen-reader now announces 'blank' instead of 'bullet'!!   I did find a workaround for this through which involves a small amount of JS.   Marking this as accepted as it answers the main question that was asked.  Thanks for the help with this., appreciate it.
Comment: Thanks for this, I'll look into the 'span' work-around and check back here in a day or so. Appreciate it.


Definir nome para uma Foreign Key criada a partir de uma Migration no Laravel

Question: Estou construindo uma aplicação utilizando o Laravel 5.1 e no meu Diagrama ER ele é bem profundo e detalhado (até com a nomenclatura de índexes). Preciso saber como posso fazer para criar uma Foreign Key utilizando os métodos de migration do laravel em que eu possa definir o nome da mesma, talvez algo do tipo:
<code>Schema::create('historico', function (Blueprint $table) {
    $table->increments('id');
    $table->dateTime('data_reg')
          ->default(DB::raw('CURRENT_TIMESTAMP'));
    $table->integer('usuario_id');
    $table->foreign('usuario_id')
          ->foreignName('historico$usuario_id') // <-- procuro isso aqui
          ->references('id')
          ->on('usuario')
          ->onDelete('CASCADE')
          ->onUpdate('CASCADE');
    $table->string('acao', 500);
    $table->longText('conteudo')->nullable();
});
</code>
Comment: Se a resposta resolveu o problema, considere por gentileza marcá-la. Assim saberemos que ela foi útil para você e terá uma melhor visualização por parte do outros usuário.
Answer: Passe um segundo parâmetro na função foreign().
Exemplo:
<code>$table->foreign('usuario_id', 'nome_da_foreign_key') // o que você procura
          ->references('id')
          ->on('usuario')
          ->onDelete('CASCADE')
          ->onUpdate('CASCADE');
</code>
Você pode ver o prototipo da função foreign key no arquivo Blueprint.php do laravel:
<code>/**
     * Specify a foreign key for the table.
     *
     * @param  string|array  $columns
     * @param  string  $name
     * @return \Illuminate\Support\Fluent
     */
    public function foreign($columns, $name = null)
    {
        return $this->indexCommand('foreign', $columns, $name);
    }
</code>


Mathieu Crickboom "The violin" method

Question: My teacher insist on teaching Mathieu Crickboom's The violin books. The violin has 5 volumes. it usually take 5 years for 5 volumes.

I don't know is it good method?
what's the most famous method for teaching violin?(or what's some experts suggest.)
Answer: .To your question "is it good method?" I would say there are different "schools", different ideals of how to work repertoire, bowing and holding. The European and Russian schools being the biggest.
Mathieu Crickboom was a great violinist who played with for example Pablo Casals.
His books are good. More important is the guidance you have of your teacher thru them.
I would say other famous violin methods/teaching books are Dont, Schradieck, Kreutzer, Sevcik and Mazas, ammong others, Some are more "hardcore" technique, others are more melodie &/or harmony focused, and of course (even not being a "method") Bach's Sonatas & Partittas is a very important book to develop in playing, intonation and doubble stops.
Again, Mathieu's book is good. If you want hardcore go to Schradiek , if you like more melody/harmony studies with technique inside take Dont.
Comment: This is a very interesting discussion, specially if together with violin pedagogy. Although it is often a conversation subject I am not aware or literature or academic textes comparing different methods.
Comment: @ArashMousavi, found this link that might fit your question also. http://speedyviolinlessons.com/members/wp-content/uploads/2010/05/Violin-Mastery-Ebook.pdf
Comment: nice answer, is there any document that describe each method in more detail?
Comment: Great answer. It would be even more useful if you could include their strengths and weaknesses with your list of methods.
Answer: I think the method, be it what it is, is just content to practice.
The real guidance is the teacher.
However, a great method is one that surrounds all the core techniques that are stacked on upon the other, meaning if you play lesson A good you're ready to go to lesson B, but more important is, especially for beginners, is that level 100 in the book covers only the very basic stuff.
IMHO, a method that spends many lessons on the boring core whole notes stuff, will make you a better violin, since when you play fast music you don't really pay attention to the negligible things in intonation, bowing, arm and finger movement, and more.
I've been exploring many methods and one of the methods I've found to be very throughout that when achieved leaves you with a very good technique disregarding the genre or style you play, is from a Hungarian violinist, conductor and teacher Frigyes Sándor (1905-1979). The method is relatively rare but I found it to be very efficient. It concentrates on every technique spending many lessons on each aspect, after completion you're technique basis is really solid.

Mathieu Crickboom "The violin" method


Vector bundle of dimension $\leqslant n$ on $n$-connected space is trivial

Question: I wonder whether any vector bundle of dimension $\leqslant n$ on an $n$-connected CW-complex is trivial? It seems that,

the complex can be given cellular structure with exactly one 0-dimensional cell and no other cells of dimension $\leqslant n$,
there is a inner product on the vector bundle by the paracompactness of CW-complexes,
the corresponding $S^{n-1}$-fiber bundle, by some obstruction theory argument (I am not sure which one, but it should use the fact that all maps $S^{\leqslant (n-1)} \to S^n$ are homotopic), has a section,
and its orthogonal complement has smaller dimension, so allowing the proof by induction.

For $n=1$ it is true: any covering (with two sheets) over simply-connected space is trivial. But I have not found the general statement anywhere, so it there an error?
Comment: To add to the list of examples to see that is not true, consider the tangent bundle on $S^5$. It admits a nowhere-zero section, and so splits into the sum of a trivial real line bundle and a rank 4 real bundle. If the claim were true, this rank 4 bundle would be trivial, and hence $S^5$ would be parallelizable, which is not the case.
Comment: You can have an $n$-skeleton equal to a point, not just the $(n-1)$-skeleton.
Comment: @OlivierBégassat: thank you, I've corrected.
Comment: If your CW complex are compact the question becomes "is every map $X \to BO(n)$ nullhomotopic when $X$ is $n$-connected?", I don't know if that helps (at least it's easier to reformulate that in terms of obstruction theory if you want).
Answer: No, this is not the case. As Najib points out in the comments, this is the same as asking "if $X$ is $n$-connected, is every map $X \to BO(n)$ null-homotopic?"
Instead, let's show this isn't true for oriented bundles; if every bundle is (unoriented) trivial, then there are 2 oriented bundles up to isomorphism.
Take $X = S^4$ and $n = 3$. $SO(3)$ has a double cover isomorphic to the group of unit quaternions $S^3$, which fits into a fibration $\Bbb Z/2\Bbb Z\to BSO(3) \to BS^3$, and $BS^3 = \Bbb{HP}^\infty$ (this coming from a more general fibration $G/H \to BH \to BG$). Passing to the long exact sequence of homotopy groups we see $\pi_k(BSO(3)) = \pi_k(\Bbb{HP}^\infty)$. By cellular approximation, $\pi_4(\Bbb{HP}^\infty) = \pi_4(S^4) \cong \Bbb Z$, which gives far more oriented 3-bundles over $S^4$ than possible if they were all (unoriented) trivial.
Answer: Your proposed argument fails at the third step. It is just not true that if $X$ is $n$-connected then every $S^{n-1}$-bundle over it is trivial.
The desired statement is not even true rationally: the rational homotopy groups of $BO(n)$ are not hard to calculate and in particular for $n \ge 3$,
$$\pi_{4n-4}(BO(2n)) \otimes \mathbb{Q} \cong \mathbb{Q}$$
so it follows that there are countably many nontrivial $2n$-dimensional real vector bundles over $S^{4n-4}$, which moreover can be distinguished by their Pontryagin classes $p_{n-1}$, and this gives an infinite family of counterexamples to the desired statement.
Answer: This is more of a comment on the other answers.
We can interpret the case $n = 0$ in terms of classifying spaces as well. The point is that $BO(1) = \mathbb{RP^{\infty}}$, and any map $f$ from a simply connected space $X$ to $BO(1)$ will lift to the universal cover of $BO(1)$, which is $S^{\infty}$. In particular, $f$ will factor through a contractible space, and thus is null homotopic.
Of course, one can also prove this more directly, also using the lifting lemma on the simply connected space itself, and without referring to classifying spaces. But phrasing it this way makes it natural that one would want to a "lifting" lemma for universal principle bundles (in particular for $G = O(n)$). However, there doesn't seem to be one, as the answers to this question show. (Or if there is one, it is more subtle than just checking induced maps on homotopy groups.) (Note that the map corresponding to a vector bundle lifts to the universal bundle, which is contractible, iff the map is homotopic, iff the vector bundle is trivial.)


Every linear orthogonal transformation can be represented as a block matrix

Question: How would you show that every linear orthogonal transformation can be represented as a block matrix, with the blocks either being 2x2 rotation matrices or $\pm1$? I have managed to show it for the 2 and 3 dimensional case but am having trouble generalising to n dimensions
Comment: How did you show it in the 3 dimensional case?
Answer: You can use induction over $n$, the space dimension (that is, prove that is true for $n=1$, or maybe $n=2$, which you have already done; and also prove that if the result is true for dimension $k<n$ it is also true for dimension $k=n$.)
A useful result is that if the orthogonal linear transformation $T$ is $S$-invariant (where $S$ is some vector subspace), then $T$ is also $S^\bot$-invariant.
Think also how the matrix of $T$ will look in a base which contains both a base of $S$ and of $S^\bot$. To be more precise: if $\mathcal{B}=\{v_1,\ldots,v_r,v_{r+1},\ldots,v_n\}$ is an orthogonal base of $V$ (not just any base), and if $\{v_1,\ldots,v_r\}$ is a base of a subspace $S$ (of course $\dim S=r$), then $S^\bot=\langle v_{r+1},\ldots,v_n\rangle$ (and those generators form a base of $S^\bot$, of course).
Now, if $T\colon V \to V$ is an $S$-invariant orthogonal endomorphism of $V$ (and consequently is also $S^\bot$-invariant) and if $\mathcal{B}$ is as above, what can you say about the structure of the matrix $[T]_\mathcal{B}$?
Then, as mentioned by @hardmath, you can show that there is always a proper subspace $S$ such that $T$ is $S$-invariant (think about the eigenvalues of $T$, for instance), and then use the fact that any proper subspace will have dimension strictly smaller than $n$, so you can use the inductive hypothesis.
Maybe you can do it following that scheme.
Comment: If you want to improve this, you would show how an invariant proper subspace $S$ must exist.


Restoring data from a failed and possibly partly overwritten mdadm raid1

Question: I have a failing hard disk (let's call it sda) which contains, among other things, a 1.5 TB partition (let's call it sda3). There is another disk (sdb), which has a 1.5 TB partition (sdb1) as well. Both used to be part of an mdadm level 1 RAID using metadata version 1.2. Inside this RAID partition (let's call id md5), there is a LUKS encryption container (let's call it md5_uncrypted). This container should contain an ext4 partition.
At some place in time around August 10, 2012, I somehow restarted the RAID array with sdb1 missing and didn't even notice that. When I wanted to replace the RAID yesterday (three months later), I started copying data from sdb1 until I realized that it was out of date. So I took a look at the old sda3. By mistake, I ran mdadm --create instead of mdadm --assemble to restart md5 with only sda3 available. Accordingly, I ignored all warnings and let mdadm --create continue. cryptsetup didn't like the content of the new RAID. I didn't actually think mdadm --create would corrupt data if the same metadata version is used? Well, apparently it did.
I compared the first 20 MB of sda3 and sdb1 and noticed that they are equal starting at about 8 MB. So I copied the first 8 MB of sdb1 to sda3 (I have a backup of the old first 20 MB of sda3) and tried to assemble md5 (with only a single drive, sda3). Unfortunately, this gave me an error:
failed to add /dev/sdb1: Invalid argument

I also tried using the LUKS header from sdb1 on a freshly mdadm --created sda3, which cryptsetup happily did (of course), but it contained garbage.
My question is: Is there any chance to restore at least some of the data from sda3? Since I have the state from three months ago, everything helps, even just a list of files, or a list of files with modification dates.
Edit:
# mdadm --examine /dev/sdb1
         Magic : a92b4efc
       Version : 1.2
   Feature Map : 0x0
    Array UUID : 76a25475:70aa881c:dd30cc93:bbae03b7
          Name : ubuntu:0
 Creation Time : Fri Mar 16 20:52:16 2012
    Raid Level : raid1
  Raid Devices : 2

Avail Dev Size : 2930272256 (1397.26 GiB 1500.30 GB)
    Array Size : 1465129848 (1397.26 GiB 1500.29 GB)
 Used Dev Size : 2930259696 (1397.26 GiB 1500.29 GB)
   Data Offset : 2048 sectors
  Super Offset : 8 sectors
         State : clean
   Device UUID : b9012482:afa502cf:7794f4fb:2a0da196

   Update Time : Wed Nov 21 20:51:51 2012
      Checksum : 4e54a07 - correct
        Events : 15003

  Device Role : Active device 1
  Array State : .A ('A' == active, '.' == missing)

# mdadm --examine /dev/sda3
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 54ea031e:42367512:b6a8675b:91f2cb6f
           Name : willow:5  (local to host willow)
  Creation Time : Wed Nov 21 18:03:35 2012
     Raid Level : raid1
   Raid Devices : 2

 Avail Dev Size : 2929999872 (1397.13 GiB 1500.16 GB)
     Array Size : 1464999744 (1397.13 GiB 1500.16 GB)
  Used Dev Size : 2929999488 (1397.13 GiB 1500.16 GB)
    Data Offset : 262144 sectors
   Super Offset : 8 sectors
          State : active
    Device UUID : 93c70c36:3cc540a5:13817695:bd4f327c

    Update Time : Wed Nov 21 18:03:35 2012
       Checksum : 321ddb3e - correct
         Events : 0

   Device Role : Active device 1
   Array State : .A ('A' == active, '.' == missing)

Answer: First if you have a spare HDD I would strongly advise to mirror sda3 and just work with the mirror.
mdadm --create with the same options shouldn't corrupt data unless defaults of unspecified options are changed between the version which initially created the array and the current version.
Did you compare the superblocks on sdb1 and sda3 with mdadm --examine?
Unless you've added/changed/removed keys the luks header should be identical. Have you tried to restore luksHeaderBackup from the sdb1 array to the created array on sda3?
Different offsets of the luks header {'L','U','K','S',0xba,0xbe} on sdb1 and sda3 would explain garbage in luks volume.
Comment: Thanks for your suggestions. I think, version 3.2.3-2 created the array, and right now I'm on 3.2.5-3, so there's probably no change in default values involved. As for comparing the superblocks – the original `sda3` superblock is lost, so which should I compare against? I will have a look at the luks header positions; I didn't change the keys in the last three months on that system.
Comment: 1MB from the start of the partition I presume? And directly at the start of the raid array? 1936220465 sounds wrong for the payload offset, that would be beyond the end of HDD
Comment: Unfortunately, both LUKS headers start at exactly 1MB.
Comment: And have exactly the same content. I wonder if I can't just take everything from the LUKS header to the end and try to luksOpen it? I would probably need to correct LUKS' payload offset (which currently has 1936220465 if I'm not mistaken).
Comment: compare the old superblock from sdb1 against a newly created on sda3 and the one you made during the initial assemble/create mishap.
Comment: 1 MB from the start of the physical partition. When building the raid on `sdb1`, the LUKS header is at 0, but the `sda3` RAID has only garbage and no LUKS header. I guess I should investigate a bit more what kind of garbage that is and whether it is somewhere on this partition.
Comment: There is a luks header 1MB from the start of the physical sda3 partition but not at the start of the raid array of sda3? The raid layout has to be different then. Is the start of the sda3 raid array before or after the LUKS header on the physical sda3 partition?
Comment: I posted the two `mdadm --examine` headers. There's definitely a different, wrong data offset in the new `sda3` header. So, I figured I should ignore the mdadm stuff and just take everything from `sda3` after the first 1 MB (so from the start of the LUKS header on). I tested that with the first 20 MB, and cryptsetup happily uncrypted it, and fsck.ext4 thinks the uncrypted stuff is an ext4. So, I think we're done here. Thank you very much for guiding me through this process!


How to store regex match in a variable to use with Search/Replace in Notepad++

Question: I need to capture a word using a pattern and store somewhere to use in replace operation:
For instance I have this text
ab iiids
as sasas
md aisjaij
as asijasija

I am able to capture everething before the first space using the following pattern:
.*?(?=[" "])

Let´s say I could use '$' to represent the match in the search and replace so I would like to have the following in the replace field
INSERT INTO table (value) VALUES ("$")

Could not find a solution.
Is this even possible?
Comment: You could use capturing groups. For example the following pattern `(a)bc`, this will match `abc`. The replacement would look like `$1foo`. So if there was `abc` as input, the output would be `afoo`
Answer: Yes, $& or $0 represents the entire match in the replacement string:
Find what: .*?(?=[ ])
Replace with: INSERT INTO table \(value\) VALUES \("$0"\)

Note that you don't need the quotes inside the character class. Otherwise your match will stop at a quote as well. Also note, that there is another catch, that you have to escape parentheses in the replacement string (thanks to acdcjunior for noticing that). That's because Notepad++ uses boost, which supports a parenthesis-delimited conditional construct.
Using your input, this will result in
INSERT INTO table (value) VALUES ("ab") iiids
INSERT INTO table (value) VALUES ("as") sasas
INSERT INTO table (value) VALUES ("md") aisjaij
INSERT INTO table (value) VALUES ("as") asijasija

For more advanced use cases, you can wrap parts of the regex in parentheses, and reference the substrings they matched with $1, $2, and so on.
By the way, a more explicit pattern would be:
^[^ ]*(?=[ ])

This makes sure that you don't get additional matches where you don't want them.
Finally, here is a reference of all the things you can do in the replacement string.


Laravel Eloquent 5.1 update related model efficiently

Question: I am looking for a clean solution for querying and modifying my Eloquent model's dynamic properties, stored in another table.
My main model is User. A User may have multiple UserVariables. When loading the model through a UserRepository, I may or may not eager-load the variables.
What I want to achieve is that the UserVariables can be modified in-memory, and be automatically saved when, and only when the User is saved.
Here is my solution (stripped out the non-relevant parts), which works, but is nor elegant, nor scalable:
/**
 * @property boolean $isCommentingEnabled
 */
class User extends \Illuminate\Database\Eloquent\Model
{
    public function variables()
    {
        return $this->hasMany('UserVariable', 'var_userid', 'user_id');
    }

    public function getIsCommentingEnabledAttribute()
    {
        foreach ($this->variables as $variable) {
            if ($variable->name == UserVariable::IS_COMMENTING_ENABLED) {
                return (boolean) $variable->value;
            }
        }
        return false;
    }

    public function setIsCommentingEnabledAttribute($enabled)
    {
        foreach ($this->variables as $variable) {
            if ($variable->name == UserVariable::IS_COMMENTING_ENABLED) {
                $variable->value = $enabled ? 1 : 0;
                return;
            }
        }
        $this->variables()->add(new UserVariable([
                'name'  => UserVariable::IS_COMMENTING_ENABLED,
                'value' => $enabled ? 1 : 0,
        ]));
    }
}

/**
 * @property-read int $id Unique ID of the record.
 * @property string $name Must be one of the constants in this class.
 * @property int $userId
 * @property string $value
 */
class UserVariable extends EloquentModel {}

class UserRepository
{
    public function findById($id)
    {
        return User::with('variables')->find($id);
    }

    public function saveUser(User $user)
    {
        return $user->push();
    }
}

This solution clearly doesn't scale. If the user had 5+ variables, the code would be abundant, even if I extracted the loops.
I suspect there must be a short and clean solution in Laravel to just pop out a User's UserVariable by name, or get a new one if it does not exist, modify its value and put it back to the model. When a User::push() is called, it's auto-saved. Done.
I'm looking for something like
$user->variables()->where('name', UserVariable::IS_COMMENTING_ENABLED)->first()->value
        = $enabled ? 1 : 0;

But the above does not work properly, because it uses the DB, not the model. Any help is appreciated.
Note: I'm working on a large legacy code base, so changing the DB structure is out of the question for now.
Answer: Unfortunately, there's no built-in way to do this. Fortunately, it's not too bad to just implement.
We have our model with its ->variables relation.
class User extends \Illuminate\Database\Eloquent\Model {
    public function variables() {
        return $this->hasMany('UserVariable', 'var_userid', 'user_id');
    }

We then need to build a method which tells us whether or not we've already loaded said relation, and one to load them if we haven't.
    protected function hasLoadedVariables() {
        $relations = $this->getRelations();
        return array_key_exists('variables', $relations);
    }

    protected function loadVariablesIfNotLoaded() {
        if(!$this->hasLoadedVariables()) {
            $this->load('variables');
        }
    }

These methods allow us to build generic getters and setters for UserVariables.
The getter makes sure that the variables relation is loaded, then returns the first value with a matching key.
    protected function getVariable($key) {
        $this->loadVariablesIfNotLoaded();
        foreach($this->variables as $variable) {
            if($variable->key === $key) {
                return $variable->value;
            }
        }
        return null;
    }

The setter is a little more complicated because we want to update an existing UserVariable model if one exists and create one if it doesn't, and in either case save the change in the ->variables relation but not the DB. ($this->variables->push($variable) saves to the relation but not to the database).
    protected function setVariable($key, $value) {
        $this->loadVariablesIfNotLoaded();
        foreach($this->variables as $k => $variable) {
            if($variable->key === $key) {
                $variable->value = $value;
                return;
            }
        }
        // We didn't find an existing UserVariable so we create one.
        $variable = new UserVariable;
        $variable->user_id = $this->id;
        $variable->key = $key;
        $variable->value = $value;
        $this->variables->push($variable);
    }

Laravel's ->push() method does not save records which do not exist to the database by default, but we can override it to do so.
    public function push(array $options = []) {
        if($this->hasLoadedVariables()) {
            foreach($this->variables as $variable) {
                if(!$variable->exists) {
                    $this->variables()->save($variable);
                } else if($variable->isDirty()) {
                    $variable->save();
                }
            }
        }
        parent::push();
    }

Finally, with all that in place, we can add specific getters and setters for single attributes.
    protected function setIsCommentingEnabledAttribute($enabled) {
        $this->setVariable(UserVariable::IS_COMMENTING_ENABLED, $enabled);
    }

    protected function getIsCommentingEnabledAttribute($enabled) {
        $this->getVariable(UserVariable::IS_COMMENTING_ENABLED);
    }
}

To use this, just write code the way you normally would.
$user = User::find(123);
$user->is_commenting_enabled; // Calls the getter, no DB calls
$user->is_commenting_enabled = 1; // Calls the setter, no DB calls
$user->push(); // Saves the user and any variables which have been added or changed.


Is the "System RAM" displayed by /proc/iomem is like unallocated memory?

Question: I could figure out other memory map info like few are device bus specific memory
I want to know like
What is the System RAM means here..
0000000-0000ffff : reserved
00010000-0009c3ff : System RAM
0009c400-0009ffff : reserved
000a0000-000bffff : PCI Bus 0000:00
  000a0000-000bffff : Video RAM area
000c0000-000c7fff : Video ROM
000d0000-000d0fff : Adapter ROM
000d2000-000d3fff : reserved
000d4000-000d7fff : PCI Bus 0000:00
000d8000-000dbfff : PCI Bus 0000:00
000dc000-000dffff : PCI Bus 0000:00
000e0000-000fffff : reserved
  000f0000-000fffff : System ROM
00100000-bb27bfff : System RAM
  01000000-015b0afb : Kernel code
  015b0afc-01878c3f : Kernel data
  01939000-01a11fff : Kernel bss
bb27c000-bb281fff : reserved
bb282000-bb3e9fff : System RAM
bb3ea000-bb40efff : reserved
bb40f000-bb46efff : System RAM
bb46f000-bb46ffff : reserved
bb470000-bb4f0fff : ACPI Non-volatile Storage
bb4f1000-bb70efff : reserved
bb70f000-bb716fff : System RAM
bb717000-bb71efff : reserved
bb71f000-bb77dfff : System RAM
bb77e000-bb79efff : ACPI Non-volatile Storage
bb79f000-bb7e1fff : System RAM
bb7e2000-bb7fefff : ACPI Tables
bb7ff000-bb7fffff : System RAM
bb800000-bfffffff : reserved
c0000000-dfffffff : PCI Bus 0000:00
  c0000000-c04fffff : PCI Bus 0000:04
  c0500000-c06fffff : PCI Bus 0000:03
  c0700000-c08fffff : PCI Bus 0000:02
  c0900000-c0afffff : PCI Bus 0000:02
  c0b00000-c0b00fff : Intel Flush Page
  d0000000-dfffffff : 0000:00:02.0
e0000000-efffffff : PCI MMCONFIG 0000 [bus 00-ff]
  e0000000-efffffff : reserved
    e0000000-efffffff : pnp 00:09
f0000000-febfffff : PCI Bus 0000:00
  f0000000-f03fffff : 0000:00:02.0
  f0400000-f04fffff : PCI Bus 0000:03
    f0400000-f0403fff : 0000:03:00.0
  f0700000-f0703fff : 0000:00:1b.0
    f0700000-f0703fff : ICH HD audio
  f0704000-f0704fff : reserved
    f0704000-f0704fff : 0000:00:1f.6
      f0704000-f0704fff : ips thermal sensor
  f0705000-f07057ff : 0000:00:1f.2
    f0705000-f07057ff : ahci
  f0705800-f070580f : 0000:00:16.0
    f0705800-f070580f : mei
  f0706000-f07063ff : 0000:00:1a.0
    f0706000-f07063ff : ehci_hcd
  f0706400-f07067ff : 0000:00:1d.0
    f0706400-f07067ff : ehci_hcd
  f0706800-f07068ff : 0000:00:1f.3
  f0800000-f08fffff : PCI Bus 0000:04
    f0800000-f080ffff : 0000:04:00.0
      f0800000-f080ffff : r8169
    f0810000-f0810fff : 0000:04:00.0
      f0810000-f0810fff : r8169
    f0820000-f083ffff : 0000:04:00.0
  feaff000-feafffff : reserved
    feaff000-feafffff : pnp 00:09
fec00000-fec0ffff : reserved
  fec00000-fec003ff : IOAPIC 0
fed00000-fed003ff : HPET 0
  fed00000-fed003ff : reserved
fed10000-fed13fff : pnp 00:09
fed18000-fed18fff : pnp 00:09
fed19000-fed19fff : pnp 00:09
fed1c000-fed8ffff : reserved
  fed1c000-fed1ffff : pnp 00:09
  fed20000-fed3ffff : pnp 00:09
  fed40000-fed44fff : pnp 00:09
  fed45000-fed8ffff : pnp 00:09
fee00000-fee00fff : Local APIC
  fee00000-fee00fff : reserved
ff000000-ffffffff : reserved
  ff000000-ffffffff : pnp 00:09
100000000-17bffffff : System RAM
180000000-1bbffffff : System RAM

Is that unallocated userspace memory..?
Please make it clear.
Please don't confuse this post with the one here:
Is System RAM the only section where heap/stack resides?
Comment: @satish: Memory map are "not contiguous". So you will be having device specific memory maps interleaved by unallocated memory i.e System RAM.
Comment: My question is why there are multiple "System RAM" ?
Answer: 0000000-0000ffff : reserved      // Reserved = not used, not available for anything.
00010000-0009c3ff : System RAM   // Regular memory - can be used to store code or data/
0009c400-0009ffff : reserved
000a0000-000bffff : PCI Bus 0000:00   // PCI device memory case
  000a0000-000bffff : Video RAM area   // (graphics/video memory in this)
000c0000-000c7fff : Video ROM          // VGA BIOS memory
000d0000-000d0fff : Adapter ROM        // General area for "boot ROM", e.g. Network boot
000d2000-000d3fff : reserved
000d4000-000d7fff : PCI Bus 0000:00   // Some other PCI device
000d8000-000dbfff : PCI Bus 0000:00   // as above
000dc000-000dffff : PCI Bus 0000:00
000e0000-000fffff : reserved
  000f0000-000fffff : System ROM      // System BIOS
00100000-bb27bfff : System RAM        // Regular RAM
  01000000-015b0afb : Kernel code     // Kernel "code" uses this bit.
  015b0afc-01878c3f : Kernel data     // Kernel "data"
  01939000-01a11fff : Kernel bss      // Kernel "initialized to zero" data.
bb27c000-bb281fff : reserved
bb282000-bb3e9fff : System RAM
bb3ea000-bb40efff : reserved
bb40f000-bb46efff : System RAM
bb46f000-bb46ffff : reserved
bb470000-bb4f0fff : ACPI Non-volatile Storage    // Advanced Control and Power Interface memory (doesn't got away when power is off!)
bb4f1000-bb70efff : reserved
bb70f000-bb716fff : System RAM
bb717000-bb71efff : reserved
bb71f000-bb77dfff : System RAM
bb77e000-bb79efff : ACPI Non-volatile Storage
bb79f000-bb7e1fff : System RAM
bb7e2000-bb7fefff : ACPI Tables
bb7ff000-bb7fffff : System RAM
bb800000-bfffffff : reserved
c0000000-dfffffff : PCI Bus 0000:00
  c0000000-c04fffff : PCI Bus 0000:04     // PCI bus bridge device

Comment: Peterson: Clear.. Thanks..! can you brief this a little please.
bb470000-bb4f0fff : ACPI Non-volatile Storage    // Advanced Control and Power Interface memory (doesn't got away when power is off!)
Comment: It would normally be implemented as a NVRam (serial eeprom) - it's "non-volatile", so things can be stored there without the power being on. I don't know exactly how/what it is used for, to be honest.
Comment: Peterson : Okay I figured out, Maybe eeprom is mapped there. when system is shutdown it stores the content of that region to eeprom
Comment: Serial EEPROM is not likely to be mapped into linear memory address space.  Serial EEPROM is usually connected to the system using TWI or I2C or SPI, and the device address space is typically kept local to the serial interface.  (Although Atmel did do a software mapping of DataFlash in U-Boot.)  The ACPI Non-volatile Storage is more likely battery-backed SRAM or parallel flash memory.
Comment: @sawdust, might be battery-backed SRAM, I doubt paralled flash memory
Answer: iomem are addresses that map to physical memories and device registers..
The addresses referring to system RAM are termed as physical addresses(to store kernel or user space code and data), and those referring to device maps as bus addresses.
This is largely dependent on the architecture.
Comment: I could not get like what you are saying. Here, few regions are tagged as "System RAM" I want to know whether this system ram means unallocated memory(user space).


how can i get the value of a variable from a different form variable? vb.net

Question: im trying to make a game for a class on vb.net and i want the player to be able to change the car. im doing that by adding a picturebox and a button in the first form.
when you click the button, it takes you to another form with several radiobuttons (im experimenting so i only used 2) and there you can pick the color.
when you pick a color, a value is stored in a variable and i want to be able to get that value in the first form. but the image never changes when i go back.
i think the problem is when it comes to storing the variable and getting it in the other form, so i would appreciate some help with that. however, if you find some other mistake in the code, please help me out.
edit:i came to the conclusion that the problem is not with the variable. i think it might have something to do with the if structure.
here is form 1
Public Class Form1
    Public color2 As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        color2 = 0
        Form2.Show()
        Hide()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        color2 = Form2.color

        If color2 = 1 Then
            PictureBox1.Image = Image.FromFile("C:\Users\ritac\OneDrive\Ambiente de Trabalho\Visual Basic\teste.cor\teste.cor\Resources\153413201_357943841905712_3966209847925971836_n.png")
        ElseIf color2 = 0 Then
            PictureBox1.Image = Image.FromFile("C:\Users\ritac\OneDrive\Ambiente de Trabalho\Visual Basic\teste.cor\teste.cor\Resources\153493631_1389827618051421_5894198564571460500_n.png")
        End If

    End Sub
End Class

and here is form 2
Public Class Form2
    Public color As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If RadioButton1.Checked = True Then
            color = 1
        ElseIf RadioButton2.Checked = True Then
            color = 0
        End If

        Form1.Show()
        Hide()
    End Sub
End Class

Comment: You have a button that shows Form2 but not one to retrieve it's color value.  You only ever retrieve in on Form1's load.  As a simple test, add another button to Form1 that does nothing but this: `MsgBox(Form2.color.ToString)`.  Temporarily disable your Form2 hiding.  Run it, change the RB selection on Form2, and after each change, click the new button on Form1 to see the value of Form2.color.
Comment: @techonaut i was able to check if the value of the variable was going to form1 and it was. now i dont know what the problem is. not even my teacher can figure this out.
Comment: Please update your code to show where you know you are getting the value back OK, and the point where it's failing.
Answer: Here is an example to show how NOT to use the default instance of Form2.  It also shows passing the instance of Form1 to the instance of Form2.  Give it a try.  The Stops are there for debugging.  They can be removed.
Form1
Public Class Form1

    Private Form2Instance As Form2

    Public FooVar As Integer = Integer.MaxValue

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ChkForm2()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ChkForm2()
        FooVar = Form2Instance.BarVar
        If FooVar = Integer.MaxValue Then
            Stop
        ElseIf FooVar = Integer.MinValue Then
            Stop
        ElseIf FooVar = 0 Then
            Stop
        Else
            Stop
        End If
        Me.Hide()
        Form2Instance.Show()
    End Sub

    Private Sub ChkForm2()
        If Form2Instance Is Nothing OrElse Form2Instance.IsDisposed Then
            Form2Instance = New Form2(Me)
        End If
    End Sub
End Class

Form2
Public Class Form2

    Private Form1Instance As Form1

    Public Sub New(Frm1 As Form1)
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        Form1Instance = Frm1
    End Sub

    Public BarVar As Integer = Integer.MinValue

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If RadioButton1.Checked Then
            BarVar = Integer.MaxValue
        ElseIf RadioButton2.Checked Then
            BarVar = Integer.MinValue
        Else
            BarVar = 0
        End If
        ShowForm1()
    End Sub

    Private Sub ShowForm1()
        Me.Hide()
        Form1Instance.Show()
    End Sub
End Class


Cálculo de porcentagem em C

Question:
" Codifique, compile e execute um programa em C que receba o
  salário-base de um funcionário, calcule e mostre o salário a receber,
  sabendo-se que esse funcionário tem gratificação de 5% sobre o
  salário-base, e paga imposto de 7% sobre o salário-base. "

#include <stdio.h>

int main()
{
    float salario,s1,s2,final;

    printf("Digite o salario: ");
    scanf("%f",&salario);

    s1=(salario*0.07)/100;
    s2=(salario*0.05)/100;
    final=s2-s1;

    printf("O salario com desconto: %f",final);

    return 0;
}

Comment: Por favor, além de postar o código deixe claro na pergunta qual o problema que você encontrou e o que você já tentou fazer.
Comment: Vlw, o bigown já me ajudou !!!
Answer: O primeiro erro é que está aplicando o desconto antes de dar o bônus, que é o contrário do que o enunciado determina.
Segundo que está calculando porcentagem errado mesmo. Está achando o percentual a ser aplicado, dividindo por 100, não sei porque, e não está aplicando ao total.
Como tanto o bônus, como o desconto deve ser dado em cima do salário base, fica fácil fazer a conta. A fórmula precisa pegar o valor total que é o seu 100%, então vamos normalizá-lo para 1 (daí vem a divisão por 100 que estava usando, você já faz ela antes de colocar no código). Depois normalizamos para 1 os percentuais, ou seja 5%, vira 0,05 (dividido por 100 novamente) e 7% vira 0,07. Então somamos o total (1) com o bônus (0,05) e subtraímos o desconto (0,07). Olha que fórmula simples.
Se quiser visualizar com a divisão:
salario = salario * (100 / 100 + 5 / 100 - 7 / 100)

Obviamente podemos simplificar isto. Já simplifiquei no código abaixo. No teste feito no ideone eu já fiz toda a conta.
Por fim, está usando variáveis demais. Não é um erro, mas é desnecessário.
Em um código real várias coisas poderiam ser feitas de forma diferente. Não vou falar que o tipo float não é adequado para valor monetário.
#include <stdio.h>

int main() {
    float salario;
    printf("Digite o salario: ");
    scanf("%f", &salario);
    salario *= 1 + 0.05 - 0.07;
    printf("\nO salario com desconto: %f", salario);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Luan, lembra que eu te perguntei (na versão anterior desta pergunta) se a sua dúvida era de mátemática ou de programação? Você havia respondido que era de programação, mas agora se confirma que é mesmo de matemática. Não estou comentando por mal, apenas pra vc perceber isso e focar seu estudo naquilo que é de fato a sua maior dificuldade. :) Assim, sugiro aproveitar a boa resposta que teve e fazer exercícios alternativos (com outros problemas similares mesmo).
Comment: @LuizVieira de fato não tinha me atentado a este detalhe, fui na intuição quando estava fazendo, já que o imposto não pode ser sobre o salário base, mas quem sou eu pra dizer que o exercício é que tá errado... :D Melhorado.
Comment: Por mais pessoas como você eu voto sim (:
Comment: Eu dei uma simplificada ainda maior no ideone. Preferi não fazer isto inicialmente para você entender o processo, mas poderia ser mais simples.
Comment: Vw a todos que responderam, vou procurar mais pra fazer não quero ficar parado num ponto haha.
Comment: Na próxima dúvida não se limite a colar código, detalhe a sua dificuldade/problema, pois pode ser a mesma que outro utilizador do SO. @Maniero o salvador \o/ hehehe

Cálculo de porcentagem em C


Is there a way to disable the  option for menu links?

Question: For our unified Drupal platform, we require all of our sites main menu items to be a page and any sub-pages to show a path following the parent menu item. So if "About Us" (with a path of /about-us) is a top level menu item, it must be a page. And the page "History" under that will have a path of /about-us/history. "About Us" cannot be a <nolink> with History as a child. How can I prevent users from using the <nolink> option for menu links? The core link module includes in the description to the user of how to include the <nolink> option. That shows that if it supports internal and external links. Well, I don't want to exclude one of those for menu links in general. I'm thinking I'm going to have to do a form alter, plus some type of validation, but I'm not sure what.
It was added from this issue but they did not do a toggle the way the D7 link contrib module did. And it's a toggle I need - to turn it off in this case.
Answer: I'd say that I would solve this requirement by doing three things:

CSS: easy one, just hide the tooltip about
JavaScript: add a client-side validation that checks the value of the link field and if the '' regexp is found, prevent from saving and show a message.
hook_form_alter and check for instance via route parameters if it has menu_link_content and then add your server-side validation.

Also, point 1 could be done as well in the form_alter by replacing the description there instead of via CSS.
Comment: I found the appropriate form to alter, but the form element is `link[0][uri]` and I'm not quite sure how to alter that. I tried: `$form['link'][0]['uri']['#description'] = t('my replacement text');` but that didn't work. I would also need to alter the validation.