Método OnMouseUp() não funciona no unity4

Question: Olá!
Sou novo em Unity e não consigo fazer o método OnMouseUp(); funcionar
<code>using UnityEngine;
using System.Collections;
 public class touch : MonoBehaviour {

    void OnMouseUp() {

        Debug.Log("Drag ended!");
    }}
</code>
Eu já atribuí o script ao objeto. Clico nele e nada acontece. Alguém sabe me explicar porque não funciona?
Comment: O teu objecto tem um Collider ou um GUIElement?
Comment: O colega @lazyFox muito provavelmente acertou o motivo. Veja na [documentação do método](http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseUp.html), onde diz claramente: "*This event is sent to all scripts attached to the Collider or GUIElement.*"
Comment: Aliás, @lazyFox, você já poderia fornecer uma resposta com base na sua colocação. :)
Comment: Olá amigos! obrigado pelas dicas achei um tutorial aqui https://www.youtube.com/watch?v=52U-eCAeGSo
Comment: Olá Emerson. Você conseguiu resolver o seu problema com esse tutorial? Se sim, por favor, crie uma resposta você mesmo explicando (não basta só apontar o tutorial!) qual era o problema e como você o resolveu. Isso pode ajudar outras pessoas no futuro, e justifica manter a sua questão aqui no site. :)
Answer: Conforme a documentação da Unity, para que o evento OnMouseUp funcione, o mesmo deve estar em um objeto que contenha um Collider ou GUIElement.
Para maiores informações, segue a documentação: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseUp.html


Application running as a service is not able to create the same number of processes as when it runs from cmd

Question: I have a Windows application which creates up to 35 processes and it's working OK when it's running from cmd.
But when it is executed as a service on the same machine it is able to create only 20 processes and all other are killed because of some kind of resource exhaustion problem.
The problem is persistent on one Windows 2003 server but not reproducible on other servers.
Can it be because the system has run out of desktop heap? http://support.microsoft.com/kb/184802
How can I check it?
Answer: Yes, it's possible that's what happening. You can monitor the Desktop Heap with the (wait for it....) Desktop Heap Monitor! You can get it here, or it's the third hit on Google for "desktop heap". Other hits on that search phrase give a lot of detail on diagnosing and fixing the issue, so do some reading, load that tool, and you're off to the races! Give it a few shots and then post back here letting us know if that helps you.
Answer: Is it an application you created? If so you could probably have it log information about available memory and resources to a file to help narrow down what is happening. Is anything showing up in the logs for Windows? What account is the service running under? If you try running the service as your user that you're testing under does the same thing happen? Different environment variables, or a different security context?
What is the process doing? It could be something with an odd security setting. There may be a tool with sysinternals that can help you debug the issue, like using procmon. That may show where the file or registry setting is getting a denied or fail error, depending on what the process is doing. Even if procmon couldn't help there may be other tools in the suite that will. Google for sysinternals (free from Microsoft) and see what their stuff can tell you.


NTP doesn't seem to be enabled and synchronised in Debian Jessie

Question: When I follow steps below in Ubuntu, NTP is enabled and synchronised. However, the case is opposite in Debian Jessie. Anybody knows the reason why Debian says "no"? Also should I worry at all since the "Local time" is correct?
Steps taken
$ timedatectl set-timezone Europe/London

$ sudo apt-get install -y ntp

$ cat /etc/ntp.conf
driftfile /var/lib/ntp/ntp.drift
server 0.uk.pool.ntp.org iburst
server 1.uk.pool.ntp.org iburst
server 2.uk.pool.ntp.org iburst
server 3.uk.pool.ntp.org iburst
restrict 127.0.0.1
restrict ::1

$ service ntp stop
$ ntpd -gq
$ service ntp start

$ systemctl enable ntp
$ systemctl restart ntp

Debian Status
$ timedatectl
      Local time: Sun 2018-05-27 08:57:32 BST
  Universal time: Sun 2018-05-27 07:57:32 UTC
        RTC time: Sun 2018-05-27 07:57:30
       Time zone: Europe/London (BST, +0100)
     NTP enabled: no
NTP synchronized: no
 RTC in local TZ: no
      DST active: yes
 Last DST change: DST began at
                  Sun 2018-03-25 00:59:59 GMT
                  Sun 2018-03-25 02:00:00 BST
 Next DST change: DST ends (the clock jumps one hour backwards) at
                  Sun 2018-10-28 01:59:59 BST
                  Sun 2018-10-28 01:00:00 GMT

$ ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
+h88-150-240-202 22.214.171.124    3 u   36   64    1   10.349   -1.919   0.882
*ntp3.wirehive.n 188.8.131.52     2 u   33   64    3   13.717   -0.094   1.398
+ns1.do.steersne 18.104.22.168     2 u   32   64    3    9.994   -1.230   0.947

Ubuntu Status
$ timedatectl
      Local time: Sun 2018-03-14 10:51:48 GMT
  Universal time: Sun 2018-03-14 10:51:48 UTC
        RTC time: Sun 2018-03-14 10:51:46
       Time zone: Europe/London (GMT, +0000)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

Comment: Did you try `timedatectl set-ntp true`?
Comment: I've done so much research but never seen that command anywhere or I somehow missed it. That did the trick! If you answer the question I can accept it. Thanks.
Answer: To enable time synchronization with timedatectl use the command as follows.
timedatectl set-ntp true

This will enable the systemd service systemd-timesyncd.service. From man timedatectl.
set-ntp [BOOL]
     Takes a boolean argument. Controls whether network time synchronization is active and enabled (if
     available). This enables and starts, or disables and stops the systemd-timesyncd.service unit. It does not
     affect the state of any other, unrelated network time synchronization services that might be installed on
     the system. This command is hence mostly equivalent to: systemctl enable --now systemd-timesyncd.service
     and systemctl disable --now systemd-timesyncd.service, but is protected by a different access policy.

     Note that even if time synchronization is turned off with this command, another unrelated system service
     might still synchronize the clock with the network. Also note that, strictly speaking,
     systemd-timesyncd.service does more than just network time synchronization, as it ensures a monotonic
     clock on systems without RTC even if no network is available. See systemd-timesyncd.service(8) for details
     about this.

So it is possible that e.g. ntp or chrony are running already but timedatectl might not be aware of that.
Further you might have to configure your NTP servers in /etc/systemd/timesyncd.conf unless you get your NTP servers via DHCP or they might also be configured in a corresponding systemd-networkd.service configuration. For more information refer to man systemd-timesyncd.service.


In a normed vector space,open connected set is path-connected.(Proof using equivalence relation)

Question: Suppose $(V,\Vert.\Vert)$ is a normed linear space(NLS) and $E$ is an open connected set in $V$,show that $E$ is pathwise connected.
Proof:
Definition:A subset $E$ of a normed linear space $V$ is said to be polygonally connected if for each $x,y\in E$,$\exists x=x_0,x_1,...,x_{n-1},x_n=y$ in $E$ such that $\{tx_{k-1}+(1-t)x_k : t\in [0,1]\}\subset E$
 .
In this problem,it suffices to show that $E$ is polygonally connected.Define an equivalence relation on $E$ as follows:
$x\sim y$ iff $x$ and $y$ have a polygonal connection in $E$.
Verify that $\sim$ is an equivalence relation on $E$.
So,$\sim$ generates a quotient set $E/\sim$ ,the set of all equivalence classes of $E$ by $\sim$.
Now we shall show that $E/\sim$ is a singleton and contains $E$ only.
Let,$x\in E$,then $[x]\in E/\sim$
We shall show below that $[x]$ is closed in $E$.
For that we take a convergent sequence $(x_n)$ in $[x]$ which converges to $x_0\in E$.We will show that $x_0\in [x]$.
Since $x_0\in E$ and $E$ is open,so $\exists r>0$ such that $B(x_0,r)\subset E$.
Note that $B(x_0,r)$ is open in $E$.
Now $(x_n)\to x_0$,hence $x_n\in B(x_0,r)$ eventually($\forall n\geq N$ ,say).
Now $V$ is a normed linear space,so $B(x_0,r)$ is convex ,so for an $n\geq N$,$x_n$ and $x_0$ are connected polygonally and hence $x_n\sim x_0$ but $x_n\in [x]$.So,$x_0\in [x]$.
Thus $[x]$ is closed in $E$.
Now we show that $[x]$ is open in $E$.
We shall take a sequence $(a_n)\subset E$ converging to a point $a$ of $[x]$ and show that $a_n\in[x]$ eventually.
since $a\in [x]\subset E$ and $E$ is open,so $B(a,r)\subset E$ for some $r>0$.
Clearly any point of $B(a,r)$ is polygonally connected to $a$ as balls are convex in NLS $V$.
and also $a\in [x]$,so $B(a,r)\subset [x]$.Now $(a_n)\to a$ and hence eventually $(a_n)$ is in $B(a,r)$ and hence $a_n \in [x]$ eventually.
So,$[x]$ is open in $E$.
So,$[x]$ is a non-empty closed-open set in $E$ and $E$ is connected.So,$[x]=E$ and we are done.
So,any two points in $E$ have a polygonal connection between them.So,$E$ is polygonally connected and is obviously path connected.
Is there anything wrong in this proof?Can anyone suggest any alternative way?
Answer: Your proof is correct. Here is a shorter proof.
Clearly each path component $P$ of an open subset $E \subset V$ is open in $V$ because if $x \in P$ and $B(x,r) \subset E$, then $B(x,r) \subset P$. Thus the path components of $E$ form a partition of $E$ into pairwise disjoint open subsets.
If $E$ is connected and has more than one path compenent, we get a non-trivial partition into pairwise disjoint open subsets which is a contradiction.


Meu form tá dando muito problema com a parte do cadastro

Question: O meu site tem os formulários de login, o formulário de cadastro e o "Recuperar minha senha"  um ao lado do outro, eu quero conectar o formulário de cadastro com o meu banco de dados, o de login eu já consegui, mas o de cadastro eu ainda não consegui, pretendo fazer um form de cadastro usando jQuery e Ajax, alguém pode me ajudar a conectar?
O nome do meu banco de dados é klp e o nome de minha tabela é table

Sign Up

  <form id="cadastra_user" method="POST" action="">

<input type="text" name="name" value="" placeholder="Complet name">

<input type="text" name="user" value="" placeholder="Username">

<input type="text" name="email" value="" placeholder="E-mail">

<input type="password" name="senha" value="" placeholder="Password">

    <button type="submit" value="Enviar" class="btn btn-primary" />Sign Up</button>
    </form>

Essa era a página de conexao para o cadastro que foi amostrado no video, mas parece que não funcionou

Tem algo faltando no vídeo? Alguém me ajuda ae por favor porque estou sem saber o que fazer para isso dar certo
https://www.youtube.com/watch?v=R9AY97_yvpo

1
2
3
4
Tipo, agr até que está aparecendo que foi cadastrado (imagem 1), porém nada aparece no meu bd (imagem 2) e o negócio é que eu tenho as conexões certas no bd, tanto de cadastro quanto de login (imagens 3 e 4)... desde já, agradeço á todos que estão me ajudando e tentando me ajudar
Comment: Não entendi nada, edite sua pergunta, está muito ampla.
Comment: Poderia melhorar o texto de sua dúvida? Seu título está totalmente não específico e vejo muita sujeira em seu texto. E o seu código não está devidamente marcado como código pelo markdown (dica, seleciona o trecho de código e pressione `ctrl+k`)
Comment: Pela segunda foto pude observar que não estás declarando as variaveis, pode ser que o formulario que voce criou está com os inputs de mesmo nome que o do de cadastro, ex: no primeiro form(login) tem input com o name="usuario" e no form de cadastro tem um input com o mesmo nome, ele está pegando o valor do primeiro formulario
Comment: Mas tipo, se não forem usados inputs de mesmo nome tanto no cadastro quanto no login, não terá como registrar as informações nos lugares certos
Comment: Obrigado pela ajuda pessoal
Comment: eu quero conectar o formulário de cadastro com o meu banco de dados, o de login eu já consegui, pretendo fazer um cadastro utilizando o JQuery e Ajax para que ao clicar no botão "Inscrever-se", a página não prcise recarregar.
Como o Anderson Henrique disse, o problema para a mensagem de cadastro estava no script do java, porém, mesmo aparecendo a mensagem de cadastro do cliente, as informações não são inseridas na minha tabela (table) do meu banco de dados (klp), se quiserem ver os prints dos códigos, eu coloquei ali embaixo para se alguém tiver qualquer dúvida sobre os códigos... obrigado
Answer: Experimente fazer assim, está faltando um igual no new FormData e na url, como está no mesmo local somente coloque o nome do documento, comentei de uma olhada

Sign Up

      <form id="cadastra_user" method="POST" action="">

<input type="text" name="name" value="" placeholder="Complet name">

<input type="text" name="user" value="" placeholder="Username">

<input type="text" name="email" value="" placeholder="E-mail">

<input type="password" name="senha" value="" placeholder="Password">

        <button type="submit" value="Enviar" class="btn btn-primary" />Sign Up</button>
        </form>


i am getting this message: your project requires a newer version of the Kotlin Gradle plugin

Question: Hello when i want to run my app in debug mode using F5 key i am getting this message:

[!] Your project requires a newer version of the Kotlin Gradle plugin.                       │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then │
│ update /Users/adm/Documents/Work/manzanos/android/build.gradle:                              │
│ ext.kotlin_version = ''

but i do what the exact message says adding but after run the app i get the same message:
here my build.gradle (android/build.gradle)
<code>buildscript {
   ext.kotlin_version = '1.6.10'
   ext {
    compileSdkVersion = 30 // o superior
    targetSdkVersion = 30 // o superior
    appCompatVersion = "1.0.2" // o superior
    playServicesLocationVersion = "17.0.0" // o superior
 }

repositories {
    google()
    jcenter()
}

 dependencies {
     classpath 'com.android.tools.build:gradle:3.5.4'
     classpath 'com.google.gms:google-services:4.3.3'
    }
 }

allprojects {
    repositories {
      google()
      jcenter()
   }
}

 rootProject.buildDir = '../build'
 subprojects {
   project.buildDir = "${rootProject.buildDir}/${project.name}"
}
 subprojects {
    project.evaluationDependsOn(':app')
}

 task clean(type: Delete) {
     delete rootProject.buildDir
}
</code>
and here my build.gradle(inside app)
<code>  def localProperties = new Properties()
  def localPropertiesFile = rootProject.file('local.properties')
  if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
     localProperties.load(reader)
   }
}

   def flutterRoot = localProperties.getProperty('flutter.sdk')

 if (flutterRoot == null) {
  throw new GradleException("Flutter SDK not found. Define location with flutter.sdk
 in
   the local.properties file.")
 }

 def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
  if (flutterVersionCode == null) {
      flutterVersionCode = '1'
  }

   def flutterVersionName = localProperties.getProperty('flutter.versionName')
  if (flutterVersionName == null) {
     flutterVersionName = '1.0'
  }

  def keystoreProperties = new Properties()
  def keystorePropertiesFile = rootProject.file('key.properties')
  if (keystorePropertiesFile.exists()) {
     keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
  }

   apply plugin: 'com.android.application'
   apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
   apply plugin: 'com.google.gms.google-services'

  android {
   //compileSdkVersion rootProject.ext.compileSdkVersion
    compileSdkVersion 30

    lintOptions {
       disable 'InvalidPackage'
    }

     defaultConfig {
       applicationId "xxxxxxx"
     //        applicationId "xxxxxx"
       minSdkVersion 21
       targetSdkVersion 30
       versionCode flutterVersionCode.toInteger()
         versionName flutterVersionName
       testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
       targetSdkVersion rootProject.ext.targetSdkVersion
      //  manifestPlaceholders = [appAuthRedirectScheme: 'pe.manzanaverde.manzanos']
     }

     signingConfigs {
        release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile file(keystoreProperties['storeFile'])
          storePassword keystoreProperties['storePassword']
       }
     }

    buildTypes {
       release {
          signingConfig signingConfigs.release
          useProguard true
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-
     rules.pro'
         }
      }
   }

   flutter {
      source '../..'
   }

    dependencies {
       implementation 'com.google.firebase:firebase-analytics:17.5.0'
       testImplementation 'junit:junit:4.12'
       androidTestImplementation 'androidx.test:runner:1.1.1'
       androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    }
</code>
here flutter doctor.

Here my pubspec.yaml

by the way i am using java and not kotlin so for that reason i dont understand why the message.
thank you so much your answer.
Answer: I answer my own question:
What i have done is the following steps:

i opened my project in Android Studio and wait till it finish load.
then go to File->Project Structure->Project
then in Android Gradle Plugin Version change to 3.5.4 and Gradle Version to 6.7
then Apply
close android studio, close vscode
re open vscode and fixed.
Comment: There is no gradle plug in visible to me can you please show some images?


Matrix pencils of quadratic forms

Question: Consider a matrix pencil of quadratic form $F-λB$ with $B$ positive definite.
For which $λ$ the pencil $F-λB$ less or equal to $0$ (negative definite)?
Comment: Writing F-λB makes the minus sign look like a hyphen instead of a minus sign. I changed it to $F-λB$. ${}\qquad{}$
Comment: AK, can you answer it if $B=I?$
Comment: i think the solution for this problem will be with the arguments in the book by F Gantmacher: MATRIX THEORY I, 1959, pp 317-326, Extremal properties of the characteristic values of a regular pencil of forms.
Answer: As you are talking about quadratic forms, I assume that $F$ is Hermitian. By Sylvester's law of inertia, $F-\lambda B$ is negative definite if and only if $B^{-1/2}FB^{-1/2}-\lambda I$ is negative definite. In turn, it is negative definite if and only if $\lambda > \rho(B^{-1/2}FB^{-1/2})=\rho(FB^{-1})$. Replace $>$ by $\ge$ when negative semidefiniteness is concerned.

Matrix pencils of quadratic forms


Start Activity from Non-Activity

Question: I have an Activity class.
public class A extends Activity
{
}

Then I have a class that is not an Activity but I want it to start the Activity A.
public class B
{
    public B()
    {
       Intent I = new Intent(null, A.class);
       i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
}

The code is take from this question which should work: Calling startActivity() from outside of an Activity?
However, when I run it I never change from my first activity to activity A. What am I doing wrong? Should I be listening to the FLAG_ACTIVITY_NEW_TASK inside A?
Comment: you must have a context to start an Activity. If you have a context then you can start activity from almost every point
Comment: Are you calling `startActivity()`?
Comment: @MikeJohn you can use startActivity in your class b but you need a valid context to do so. context.startActivity(intent);
Comment: startActivity can't be called inside of `B` because `B` is not an Activity. @IllegalArgument can you explain context?
Comment: @IllegalArgument How do I get this valid context? Is it a reference to class A?
Answer: Something like this should work:
public class B {
Context context;

public B(Context context) {
    this.context = context;

}

public void startNewActivity(String str) {
    try {
        Intent i = new Intent(context, Class.forName(str));
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
}

Use case of class B:
    B b = new B(A.this);
    b.startNewActivity("MainActivity");//the "MainActivity" is the className of the java class

Note I find this way wierd and a overkill.
Comment: I might be able to use it if this line `A.class` can be something more generic that would work for other activities. Maybe using `context.class` (that would probably fail.)

Start Activity from Non-Activity


WPF - MenuIten as Icon without TEXT

Question: We have been given a design (UI) for a WPF project. It contains a Menu which is represented by an Icon (No Text)
Is it possible to have a Menu button as an Icon withot text? And if so how can it be achieved?
Answer: yes you can, some examples:
having only a button without no text in it:
<Button Background="your color"></Button>

having a button with an image(icon) in it:
<Button>
    <image Source="your image path" Width="100" Height="100"/>
</Button>

this is what i can answer, you can provide more informations about what you want to do exactly so i can help :)
Answer: Provide the actual path to the source attribute of the image element.
<MenuItem>
    <MenuItem.Icon>
        <Image Source=""/>
    </MenuItem.Icon>
</MenuItem>

WPF - MenuIten as Icon without TEXT


Copy Resource icon on dll load

Question: I have a C# assembly with a resource file that contains an icon. How can I copy the resource on every load to the caller directory. When i compile the assembly it copies fine...but I need to copy on every load of the assembly so the calling executable can use it.(The resource folder gets deleted when the executable unloads)
Answer: You could embed the resource file and the write it out every time the assembly is loaded.
Set the resource file to have a "Build Action" equal to "Embedded Resource" in the file properties of the visual studio solution explorer.
then you can unpack it with something like this:
<code>        private static string _srvExePath;
        private static void UnpackFiles()
        {
            if (!Directory.Exists(_srvExePath))
            {
                Directory.CreateDirectory(_srvExePath);
            }

            Stream s1 = Assembly.GetExecutingAssembly().GetManifestResourceStream( assmblyname +"."+ resourcefile);
            byte[] b1 = new byte[s1.Length];
            s1.Read(b1, 0, (int)s1.Length);

            File.WriteAllBytes(_srvExePath + file, b1);
            //Console.WriteLine("unpacking: " + _srvExePath + file);
        }
</code>
Comment: Getting null at : Stream s1 = Assembly.GetExecutingAssembly().GetManifestResourceStream( assmblyname +"."+ resourcefile);
Comment: Added: string[] resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
Comment: You need to format the name of the file to be the "assemblyname.filename", no path on the assembly name. Did you set the resource file property to be "embedded resource"?  Looks like it is not finding the embedded file. look here for [more info](http://msdn.microsoft.com/en-us/library/vstudio/xc4235zt(v=vs.100).aspx)
Comment: All set...didn't have my full namespace...Thanks

Copy Resource icon on dll load


How do I hide title of a node?

Question: I have tried doing this in hook_node_view or  hook_node_view_alter with no luck:
I have tried things like:
     unset( $node->title); or
      $node->title ='';
note: my node was created using panel nodes
Answer: The Exclude Node Title module has that functionality if you'd prefer a non-code solution.

This module handles a very simple functionality, decide whatever to exclude a node title from full node page or node teasers.
Comment: I also thought about mentioning it but didn't because I though he is asking about node display page only..
Answer: Hope this will help you.
In Drupal 7 , if you dont want any modules then you can use template preprocess functions for you requirement.

template_preprocess_page

function THEMENAME_preprocess_page(&$vars) {
    if ($vars['is_front']) {//for home page
      $vars['title'] = '';
    }
    elseif (!empty($vars['node']) && in_array($vars['node']->type, array('NODETYPE1', 'NODETYPE2'))) {//for specific node type(NODETYPE1 OR NODETYPE2)
      $vars['title'] = '';
    }
}

You can also use template_preprocess_node

function YOURTHEME_preprocess_node(&$node) {
      // check for node type
        if(in_array($node['type'], array('NODETYPE1', 'NODETYPE2'))) {//for specific node type(NODETYPE1 OR NODETYPE2)
         $node['title'] = NULL;
      }
}

Answer: If you use modules display suite or/and page manager (part of ctools), you could have more control of all the fields, including the title.
Comment: Then you may not have looked so close :-) http://picpaste.com/Markering_081-J9Wep7Yw.png
Comment: I have never seen title to be controlled by Manage Display tab..
Answer: $title is not inside the $node variable but independent. You will find it inside page.tpl.php rather than node.tpl.php, where usually we guess at first.
So if you are trying to hide it then you should better do some action on this one or just hide it from your specific page.tpl.php.

How do I hide title of a node?


VB.net Excel - change cell value to specific formatting

Question: New here: I'm writing a VB.net addIn for Excel in VS2015 that I need a bit of help with. I've got the part working where I delete rows containing a value of both Mull and X or Z, but...
When column 1, row(x) contains a value of both "Mull", some number between 0 and 10 and "Y" And Not "_Y", I want to change it to have the formatting of Mull & iterative # & _Y. Here's the code I'm trying to do this in:
<code>    Dim i As Integer = 1
    Do While i <= totalRows

        ' Dim newArray() As Char = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} *Better way below

        'Find all Cells that contain "Mull" for Mullion and get the individual characters in order to break it apart and
        'format it correctly.

        r = Nothing
        If array.GetValue(i, 1).ToString.Contains("Mull") Then
            Dim strOld = array.GetValue(i, 1).ToString.Contains("Mull")

            Dim str As String = CStr(array.GetValue(i, 1))
            If str.Contains("Z") Then
                'Dim xlWorkSheets As Excel.Sheets = Nothing
                r = CType(sheet.Rows(i), Excel.Range)
                r.Cells.EntireRow.Delete()

            ElseIf array.GetValue(i, 1).ToString.Contains("X") = True Then
                MsgBox("Contains an X" & " index " & i)
                r = CType(sheet.Rows(i), Excel.Range)
                Dim countX As Integer
                countX = sheet.Rows.Count
                r.Cells.EntireRow.Delete()
            End If

            'Do Until sheet.Cells(i, 1).ToString.Contains("_Y")
            MsgBox("Mull and Y found")
            For Each str In array.GetValue(i, 1).ToString()
                If array.GetValue(i, 1).ToString.Contains("Mull") And Not array.GetValue(i, 1).ToString.Contains("_Y") Then
                    Dim num As Integer = 0
                    r = CType(sheet.Cells(i, 1), Excel.Range)
                    Dim strNew As String
                    strNew = Microsoft.VisualBasic.Left(str, Len(str) - 2)
                    Dim test1 As String = str
                    Dim result = Truncate(test1, 16)
                    Dim result2 As String
                    result2 = Truncate(test1, 10)
                    Dim finalText As Object = result2 & "_" & num & "Y"
                    r.Value = finalText
                    MsgBox(num)
                    num = num + 1
                Else
                    Return
                End If
                'Loop
            Next
        Else
        End If

        i = i + 1
    Loop
</code>
BTW, my Truncate function looks like this:
<code>Public Function Truncate(value As String, length As Integer) As String
    If length > value.Length Then
        Return value
    Else
        Return value.Substring(0, length)
    End If
End Function
</code>
**Note I'm importing ...Interop.Excel
I could really use some help on this one.
Thanks!
Answer: Never mind, I got it by using another string type variable and writing the lines out to Excel like this for ones that contain "Z" for instance:
Dim finalText As String = result & i & "_Z"
                            r.Value = finalText


Jelastic log rotation

Question: I use jelastic cloud. And I need have to clear logs manualy.
How can I make log rotation for nodes (especially apache and nginx).
Answer: Log rotation should be configured and enabled by default on every type of Jelastic node.
If you are seeing issues with this or you want to adjust the log rotation details in some way, I recommend to contact your hosting provider's support team to check it.
Comment: Hosting provider said that I need to add crontab task for logrotate. But there are not cron folder in nginx node.
Comment: @verybadbug I don't think your user (running the cron) will have appropriate permissions for that.
Comment: Checked this further, and by default the cron already exists (in cron.daily). There's also already logrotate.d/nginx config (for example) defined to rotate the log files.

It's surprising that your hosting provider does not know about this!
Comment: Ok.. I'll contact with my provider and ask about this. Thanks.
Comment: Yes.. Provider fully configure log rotation on environment. And later I ask for make changes in rotation (time of execution), that the provider also made. It remains to verify that old logs is removing.
Answer: You can to clear logs manually from your dashboard.

Unfortunately,in Jelastic logrotate configuration and editing is not available for users.
Comment: Yes, I do so. But I need to do this every day, because there are ~2Gb logs per day.

Jelastic log rotation


Is every simple function on a compact measure space the pointwise limit of continuous functions?

Question:
Question: Let $(X,\mu)$ be a measure space and suppose that $X$ is compact. Is every simple measurable function $s:X\to\mathbb{R}$ (i.e. $s(X)$ is a finite set) the pointwise limit of continuous functions $f_n:X\to\mathbb{R}$?

Edit: Actually the answer is no! Thanks to David Mitra for the counterexample. But the question bellow still holds. End Edit.
I am asking this question in order to understand a proof in Rudin's Real and Complex Analysis (p. 102). He defines a function $g:[-\pi,\pi]\to\mathbb{R}$ by
$$g(t)=\begin{cases}1 &; D_n(t)\geq 0 \\ -1 &;D_n(t)<0,\end{cases}$$
where
$$D_n(t)=\sum_{k=-n}^ne^{ikt}.$$
He then says (without any explanation) that there are continuous functions $f_k:[-\pi,\pi]\to\mathbb{R}$ such that $-1\leq f_j\leq 1$ and $f_j(t)\to g(t)$ for every $t$, as $j\to\infty$.
After some work, I found a way to convince myself that this is true, but I don't find it obvious at all. Since Rudin doesn't give any explanation, this must be very obvious and there should be something that I missed.
To prove it, I first used Uryshon's Lemma to obtain continuous functions $f_j$ such that
$$D_n^{-1}([0,\infty))\prec f_j\prec D_n^{-1}((-1/j,\infty)).$$
The limit of these functions is $\chi_{D_n^{-1}([0,\infty))}$ and by making a translation and a scaling, we are done.

Question: How would YOU prove it?
Comment: No. With Lebesgue measure on $[0,1]$, the characteristic function of $\Bbb Q\cap[0,1]$ is not the pointwise limit of continuous functions. (A pointwise limit of continuous functions on $[a,b]$ is a *Baire class one function*; one can show such a function is continuous at each point of a dense subset of $[a,b]$.)
Comment: @DavidMitra just a suggestion, why not post this as an answer?
Comment: Ok thank you @DavidMitra !
Comment: @OP: Your construction is fine, I don't think there is a much simpler way. Just one comment why the construction is possible in this case: The set where $D_n (t) < 0$ is open. Hence, we don't just have **some measurable** set/function, but a very particular one.
Answer: The answer to your first question is no.
A real-valued function $f$ on $[a,b]$ is called a Baire class one function if it is the pointwise limit of a sequence of continuous functions from $[a,b]$.  It is known that a Baire class one function has many points of continuity; in fact, the set of continuity points of a Baire class one function on $[a,b]$ is dense in $[a,b]$ (an even stronger statement can be made). See this MO post for references.
So, easy counterexamples can be made. For instance, on $[0,1]$, the characteristic function of $\Bbb Q\cap[0,1]$ is not Baire class one.  It is a Lebesgue measurable simple function, of course).


Diatonic chords of a pentatonic vs blues scale?

Question: In the blues scale, when I form the diatonic chords of this scale is the blue note (D# in the case of C major blues) also taken into account when forming the chords?
so in C major blues scale: C D D# E G A the chords would be:
1. C D# G
2. D E A
3. D# G C
4. E A D
5. G C D#
6. A D E
Or do I just form diatonic chords of the underlying pentatonic scale? Also, not too sure how I'd form the diatonic chords of the pentatonic scale.
C major pentatonic: C D E G A, the chords would be:
1. C E A
2. D G C
3. E A C
4. G C E
5. A D G
Does this look right?
Comment: That D# is more likely known as Eb in key C. Have you actually played these 'diatonc chords'? Do they sound authentic or good to you?
Comment: Since Blues seems to take the 'rule' book, and tear it up, there is no point trying to apply the 'rules' as written in it - many years before Blues was 'invented' - or was it 'discovered'?
Comment: @user45266 - Blues *melodies* are supposed to reconcile with *harmonies*??!
Comment: This is a problem that I remember personally struggling with: reconciling the blues' melodies with its harmonies. I've come full circle, it seems :)
Comment: @Tim not too much. they don't sound bad. but they're unconventional. that's what made me ask this in the first place, I wasn't sure if I was on the right track. I'm glad it's just good old I IV V. I like how simple blues is. as far as D# vs Eb, I wanted to edit it to Eb but then I realized the answers are using it.
Comment: The way I look at the 'altered' notes for minor blues is 3, 5 and 7 are all flattened Thus standard major (diatonic) notes in key C E, G and B. Blues notes - Eb, Gb and Bb.
Comment: Related: https://music.stackexchange.com/questions/84473. The harmony/melody is basically diatonic with added blue notes.
Comment: @Tim Well, that's what a less-experienced user45266 once attempted, anyway...
Answer: You could make chords out of blue notes, but why would you?
In general the blues scale(s) is only applied in certain circumstances: unsurprisingly, in blues music. The best answer to this kind of question, in my opinion, is to observe blues music to determine blues' chords.
You certainly could write blues music with chords like the ones you listed above, because no one's stopping, you, but when I think of "blues chords", I think of three chords, and only three: The I7, the IV7, and the V7.
I think that blues chords aren't really directly related to the blues scales or the pentatonic scales in general; they just seem to be the I, IV, and V with their dominant 7ths on them (and sometimes, to spice things up, the ♯9). The real beauty of the blues scale is its melodic capabilities, not its chord construction. The blues chords are a framework around which the blues scale is used melodically; while most of the notes in the blues chords have at least some justification in some blues scale, the real reason those chords exist is because they carry a "blues feel", whether that be due to societal influence of not.
Take the major blues scale C-D-D♯-E-G-A. The chords that traditionally go with this scale are C7 (C E G B♭), F7 (F A C E♭), and G7 (G B D F). The note F appears multiple times, and yet is never mentioned in the major blues scale that's being played. The note B♭ is part of the tonic chord, and never appears in the blues scale. Another way of thinking about it is that one can apply the blues scale of the chord being played to the melody as well; when playing F7, (F-G-G♯-A-C-D) all work pretty well in the melody, providing more justification. But in my opinion, the justification isn't important, because the chords weren't actually from the blues scale at all.
The blues scale is a loose association of notes that when used melodically tend to be perceived as "bluesy". The blues chords tend to use similar groups of notes, but there's no useful direct relationship between the blues scale and blues chords.

It's the same thing with the pentatonic scales. At least in popular music (because it's different in more ethnic-sounding music), the pentatonic scales aren't the only allowable notes. Plenty of pop songs use just the pentatonic scale in the melody, but the chords are far from restricted to that scale. Usually, it's I-IV-V and sometimes vi, quite similar to the blues in terms of framework around which the melody is implemented. The whole point of the pentatonic scale is to remove the notes with the most tension (well, that's at least an important effect of using the scale), but without any tension, all of western harmony falls apart. See the duality?
That said, the pentatonic scales make some cool chords. And of course, not all blues songs only use three chords, and not all pop songs only use "the" four chords. However, the scale of the melody and the scale of the chord do not have to be the same, and often they arent in those two styles/harmonic environments.
TL;DR: Blues scales don't affect the blues chords. Same for Pentatonic as used in western music.
Comment: @foreyez, you could use the minor blues scale over i, iv, v but also over i, iv, V7alt. However, one should caution against overusing these blues scales. For example, in my opinion, using the C major blues scale over the entire 12-bar blues form usually sounds pretty stale.
Comment: You beat me to it! +1. And actually, bringing the *minor* blues scale into the equation (why not - it's still blues?!) in key C, there's only three 'missing' notes - B, Db/C# and Ab/G#. Funnily enough, the B will get used over a V chord (G), the Ab will get used over a IV chord (F), and I'm sure someone will justify that poor old C#..!
Comment: @Tim Off top of head: You could get a C# if you play B7 as a flat-five sub for F7 and add the C# to make it B9. I haven't listened to it yet, but it's a little intriguing: Cm B9 G7? It's a little like the line cliché from *Air that I breathe* but backwards.
Comment: That C#/Db is one of the blue notes from Gm blues, isn't it...? So, in actual fact, it would appear that in a standard 12 bar blues, using I7, IV7 and V7, every note available to Man (and some other notes 'in the cracks'!) can and will be available. Just a matter of judicious placing.
Comment: @luserdroog Oh, that sounds actually prettt spicy! The example I thought of was in a more blues (although I love me some blue jazz) context: C♯-D played over the G7 in a C blues sounds pretty idiomatic (it's the crunch with the D, the 5th of G7).
Comment: Would minor blues scale use i iv v too? (lowercase to emphasize minor chords)
Comment: 'Would minor Blues scale use i iv v too?' It's a well established facct that minor Blues notes work over major/seventh chords, but not vice versa. You wouldn't use major Blues notes over a minor blues backing. It seems that you sometimes don't try these things out before asking the questions. If you did, maybe that would answer those questions.
Answer: The so-called blues scale isn't really a thing. Jazz, blues, and rock and roll music doesn't really build melodies out of such a scale. The blues scale is sort of a crutch that teachers use to help students get started with playing the blues, and different teachers don't even agree on what notes are in the scale. The form you give, C D D# E G A in C, isn't even one that I've ever seen before. If someone held a gun to my head and demanded that I name the notes in a C blues scale, I'd probably say something like C Eb F F# G Bb. But you can throw the D or the A in, or not use the F#, or play E instead of or in addition to Eb.
You seem to be taking a certain version of the blues scale and building chords by starting on a certain note and playing every other note in the scale. This does work in the sense that if you start from a diatonic scale and do this, you get the usual triads and seventh chords, but it's not really where harmony comes from or how chords are constructed. At the physical/physiological level, the major triad clearly comes from the overtone series, but in general chords are just combinations of notes that occur in music. Originally they occurred because people were writing music with 3 or 4 voices, and combinations of notes came about because of the way the different melodic lines interacted.
There are lots of ways of making various scale patterns fit with various chords in a bluesy context. It would be boring and static if the only way of doing it was to make the chord and melody out of the same set of 5 or 6 notes. Some examples:
You can play a chord consisting of C E G Bb Eb (usually voiced with Eb on the top). Or a piano player can play a C7 chord (C E G Bb) while the melody line can be Eb.
Any note whatsoever can be played as a chromatic passing tone. For instance, over a C7 chord you could play Bb B A, and depending on how you executed it and fit it into the musical context, it could sound fine.
In a 12-bar blues in C, if you're improvising melodically, then it tends to sound boring and static if you never recognize the changes in harmony with changes in the notes you're using in the melody. If you play Eb over the F7 chord and then play E over the C7 chord, it gives the listener the feeling that you're helping to tell the harmonic story. If you play E over the F7 chord, it's probably going to sound just plain wrong.
Scale fragments can be transposed. For instance, you could start a 12-bar blues in C by playing a lick on the notes G A Bb over the C7 chord. Then when the chord changes to F7, you can transpose the same lick to C D Eb, and similarly, if you like, for the rest of the chord changes.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/94719/discussion-on-answer-by-ben-crowell-diatonic-chords-of-a-pentatonic-vs-blues-sca).


Prove that following sequence is bounded

Question: I have to prove that $x_n=\frac{1-n}{\sqrt{2+n^2}}$ sequence is bounded. I've solved some easier ones, but these seems to be kinda different. I have to find actual bounds of the sequence.
Comment: Hint: $(x_n)$ is bounded if and only if $(x_n^2)$ is bounded.
Comment: It is convergent, hence bounded.
Comment: Welcome to Mathematics Stack Exchange.  Note that $x_1=0$ and $x_n<0$ for $n>1$
Answer: Lower bound:
$$ \frac{1-n}{\sqrt{2+n^2}} = \frac{1}{\sqrt{2+n^2}} - \frac{n}{\sqrt{2+n^2}} \geq \frac{1}{\sqrt{2+n^2}} - \frac{n}{\sqrt{n^2}} = \frac{1}{\sqrt{2+n^2}} - 1 > -1$$
Upper bound:
Since $\sqrt{2+n^2} > 0$ we get
$$\frac{1-n}{\sqrt{2+n^2}} \leq \frac{1}{\sqrt{2+n^2}} < \frac{1}{\sqrt{2}}$$
Answer: Upper bound : $U=1/√2;$
$n=0$: $x_0= 1/√2$;
$x_1=0$; and $x_n <0$ for $n \ge 2$;
Let $n \ge 2$:
$\dfrac{2-n}{\sqrt{2+n^2}} >\dfrac{-n}{\sqrt{2+n^2}}>$
$\dfrac{-n}{\sqrt{n^2}}=\dfrac{-n}{n}=-1$;
Lower bound: $L=-1$.
Comment: but $n$ is natural only.
Comment: jolskey. $n=0,1,2,.....$ natural numbers.  $x_n$ can be positive, xero, and negative depending on $n$.Ok?


How to connect to the nomad/consul UI with tls enabled?

Question: I'm now researching the Hashistack and trying to deploy pet microservice-based project on it. I deployed Nomad and Consul clusters with Ansible roles on bare metal nodes:

https://github.com/ansible-community/ansible-consul.git (v2.5.4)
https://github.com/ansible-community/ansible-nomad.git (v1.9.6)

Servers of Nomad and Consul are placed on the same nodes.
I do not use Vault. I created separate private CA, generated TLS certificates and private keys for these services and configured Nomad and Consul servers and clients to use them.
My goal is to setup production ready Hashistack cluster. So that I want to setup full TLS for both services.
I successfully connected to both UIs via HTTP, but when I try HTTPS, I get the SSL_ERROR_BAD_CERT_ALERT error.
I'll appreciate if you suggest the best practices to operate the Hashistack in production, and what steps are required for it.
Thank you!
Comment: In case someone runs into the issue where you've configured Consul with auto_encrypt and the Nomad clients also receive "bad certificate" (or something similar) when trying to communicate with the Consul clients on localhost, then check here: https://discuss.hashicorp.com/t/nomad-consul-integration-with-tls-and-verify-ssl-true-not-working/58263/2
Answer: You need first, generate a client certificate for your web brower.
Then convert it to PKCS12 format.
openssl pkcs12 -export -inkey ./nomad-cli.key -in ./nomad-cli.pem -out ./nomad-cli.p12

Let's say your are using Chrome,
Go to chrome://settings/certificates?search=certificate and import the converted certificate nomad-cli.p12.
Comment: This was the answer for me. Instead of Chrome I used Firefox and Imported this .p21 cert via Settings > Privacy & Security > Certificate > View Certificates > Your Certificates`.
Answer: I've found answer for same case.
When nomad cluster deployed with mTLS need deploy cli keys to each server nodes or at least on the node to which you are configuring the connection.
cli keys generated by instruction https://learn.hashicorp.com/tutorials/nomad/security-enable-tls#nomad-ca-key-pem
and nginx configured by instruction https://learn.hashicorp.com/tutorials/nomad/reverse-proxy-ui?in=nomad/manage-clusters
however this manual does not contain a description of configuring mTLS.
You need add following parameters in location /.
 location / {
    ....
    proxy_pass      https://127.0.0.1:4646;
    proxy_ssl_certificate     /etc/nomad.d/cli.pem;
    proxy_ssl_certificate_key /etc/nomad.d/cli-key.pem;
    proxy_ssl_verify              off;
    ....
}

In this case nginx can connect encrypted connection with nomad http port with TLS.
Also don't forget enable http basic auth at least.
Answer: I'm a bit late to respond, but came across the same error. Figured I'd leave my solution in case future readers find it helpful...
For me, the issue came down to the verify_https_client flag in my Nomad tls config block. Since Nomad is configured for mutual TLS, all clients (including web browsers) need to provide a client certificate signed by the same CA used by Nomad in order to connect. You'll need to generate/sign that certificate, and look up how to configure your browser to automatically provide it when needed.
For production use, that's the safest route. For a dev environment, you can just set that verify_https_client config to false in your Nomad config.
Here's a link to the Nomad docs for this flag: https://www.nomadproject.io/docs/configuration/tls#verify_https_client
Comment: Hi, how you open from web browser if verify_https_client = true ?
Comment: @kholisrag: See airo's answer here: https://stackoverflow.com/a/71192623/9602527
Comment: yeah, already solve it long time ago using nginx proxy_ssl too
Answer: I found that this answer was the correct approach for me but I wanted to add additional context concerning how I generated the cert that gets exported via the openssl command.
I issued the cert with my intermediate CA via:
vault write \
    -format=json \
    pki_int/issue/nomad \
    common_name=client.global.nomad \
    alt_names="${NOMAD_SERVER_IP},localhost" \
    > nomad-cli.json

jq -r .data.ca_chain[] nomad-cli.json > ca.pem
jq -r .data.certificate nomad-cli.json > cert.pem
jq -r .data.private_key nomad-cli.json > key.pem

openssl \
    pkcs12 -export \
    -inkey key.pem \
    -in cert.pem \
    -out browser-cert.p12 \
    -password pass:

Instead of Chrome I used Firefox and Imported the browser-cert.p12 cert file via Settings > Privacy & Security > Certificate > View Certificates > Your Certificates.


Como retornar array validado para um formulário?

Question: Tenho um sistema de inscrição step-by-step que seria passo a passo, ou seja primeiro o usuário informa alguns dados depois outros e outros... Quero ir validando esses dados com PHP (pois tenho que fazer consulta no banco de dados para ver se o usuário já existe). Tenho o seguinte código:
<form  method="post" action="forms/register.php">

Registrar

login

            <?php
            if (isset($_REQUEST['error'])) {
                $erro = $_REQUEST['error'];
                if ($erro == "userexist") {
                    echo "Usuário ou email já cadastrado!";
                    echo "
Veja-os novamente..

";
                } else if ($erro == "passdistint") {
                    echo "Senhas são distintas!";
                    echo "
Os campos de senha devem ter a mesma senha..

";
                } else if ($erro == "every") {
                    echo "Erro desconhecido!";
                    echo "
Tente novamente mais tarde...

";
                } else if ($erro == "sucess") {
                    echo "";
                }
            }
            ?>

                웃
                <input type="text" class="form-control" maxlength="15" id="user" name="user" required="" placeholder="Usuário">

                @
                <input type="email" class="form-control" name="email" required="" placeholder="Email">

                #*
                <input type="password" class="form-control" maxlength="15" id="senha" required="" name="pass1" placeholder="Senha">
                #*
                <input type="password" class="form-control confirm" maxlength="15" id="senha2" required=""  name="pass2" placeholder="Confirmar Senha">

            <input type="hidden" name="step" value="1">

            <input type="submit" class="btn btn-success md-btn" value="Próximo"/>

Registrar

perfil

        <?php
            if (isset($_REQUEST['error'])) {
                $erro = $_REQUEST['error'];
                if ($erro == "userexist") {
                    echo "Usuário ou email já cadastrado!";
                    echo "
Veja-os novamente..

";
                } else if ($erro == "passdistint") {
                    echo "Senhas são distintas!";
                    echo "
Os campos de senha devem ter a mesma senha..

";
                } else if ($erro == "every") {
                    echo "Erro desconhecido!";
                    echo "
Tente novamente mais tarde...

";
                } else if ($erro == "sucess2") {
                    echo "";
                }
            }
            ?>

                웃
                <input type="file" class="form-control btn btn-default md-btn fileimg" accept="image/*"  name="img" required="" >

                Nome
                <input type="text" class="form-control" maxlength="200" required="" name="nome" placeholder="Nome Completo">

                Nascimento
                <input type="date" class="form-control" required="" name="data">
                Profissão
                <input type="text" class="form-control" maxlength="100" required=""  name="profissao" placeholder="Trabalho em..">

            <input type="hidden" name="step" value="2">

            <input type="submit" class="btn btn-success md-btn" value="Próximo"/>

</form>

A primeira parte (onde o usuário informa login, email e senha) é confirmada assim:
$mnpdo = new MinPDO();
$step = $_REQUEST['step'];
if($step == 1) {
    if(isset($_REQUEST['user']) and isset($_REQUEST['email'])) {
        $user = $_REQUEST['user'];
        $email = $_REQUEST['email'];
        try {
            $result = $mnpdo->consult("users", "*", "email = '$email' or username = '$user'");
            if($result[0]["username"] == $user or $result[0]["email"] == $email) {
                header("location:../singup.php?error=userexist");
                exit();
            }
        } catch (MinPDOException $ex) {
            if($ex->getMessage() != "No results!") {
                header("location:../singup.php?error=".$ex->getMessage());
                exit();
            }

        }

        if(isset($_REQUEST['pass1'])) {
            $pass1 = $_REQUEST['pass1'];

            if(isset($_REQUEST['pass2'])) {
                $pass2 = $_REQUEST['pass2'];
                if($pass1 != $pass2) {
                    header("location:../singup.php?error=passdistint");
                    exit();
                } else {
                    header("location:../singup.php?error=sucess");
                    exit();
                }
            } else {
                header("location:../singup.php?error=pass2");
                exit();
            }
        } else {
            header("location:../singup.php?error=pass");
            exit();
        }
    } else {
        header("location:../singup.php?error=user");
        exit();
    }
}

Quando ele valida retorno sucess e assim eu faço a ação para ir para a próxima etapa..
Como faço para quando ele voltar com o sucess ou até mesmo com falha ele não perder os dados que foram validados?
Estava pensando em a medida que for validando ir armazenando os valores em um array $validado['meuinput'] e ao retornar com o head pegar os valores do array, mas como passo o array para a página? (sem ser por url - get)
Comment: Acho que você pode usar variáveis de sessão.
Answer: Você pode armazenr o array em uma variável de sessão... As váriáveis de sessão podem ser acessadas de qualquer página, o que resolveria o problema de transito de informações... Ex:
    $_SESSION["nomeDaVariavel"] = $seuArray;

A cada item novo que você adicionar ao array, será necessário atualizar a variável de sessão, utilizando o mesmo comando acima.
Quando ocorrer alguma falha no processo de autenticação, você destrói a variável de sessão. Ex:
    if($result[0]["username"] == $user or $result[0]["email"] == $email) {
            header("location:../singup.php?error=userexist");
            unset($_SESSION['nomeDaVariavel']);
            exit();
        }

Comment: Atualizei a resposta, @gustavox. Realmente, estava fraca mesmo... Obrigado pelo feedback... =)
Comment: Olá Andre, acho que você poderia melhorar esta resposta, incluindo alguma explicação, e um exemplo de como fazer isso.
Comment: Ficou legal André. +1
Answer: Você pode utilizar $_SESSION, assim que entrar na validação do passo grava na sessão:
session_start();
$_SESSION["meuinput"] = "valor";
$_SESSION["meuinput2"] = "2";
session_write_close();
Dai depois de redirecionar na tela do formulário é só inputar os dados:

<?php

session_start();

?>

<input type="text" value="<?=isset($_SESSION['meuinput'])?$_SESSION['meuinput']:'';?>">
Comment: Ahhh, faz sentido o que vc falou então, pois para usar o `=` depende da configuração do PHP, no meu aqui tá funcionando porque minha configuração permite. Valeu
Comment: Faltou o `echo` no value.
Comment: Na verdade não faltou não, pois o `<?=` é o mesmo que `<?php echo`
Comment: Eu tentei assim, acusou erro no `=` '-'


Sensitive data on the client side

Question: Including a sensitive data on the client side.
How can I include the user id or other sensitive data in the client side, and retrieve it after that without allows to the customer to change it in the #clientside?
For example:

name

Comment: If you have something you don't want the end user to know, then it shouldn't be sent to the client period. Even if you did accomplish this, what would be the point of sending it to the client if the client can't even use it because it's encrypted? This seems like an [XY problem](https://xyproblem.info/).
Comment: Not sure to understand the question
Comment: Because ,When User want to make something on the app like friend request or something then I can got him with his Id
Answer: Your best choice is to use some encryption like JWT and store the user data in the payload. Don't share the private key on the client side so the token can't be tampered with.
Or after login of the user creates a cookie and saves it in the database alongside the user id. Store the cookie token in the cookies of the user. The user logs in with the cookie and you know which user it is by the cookie. If they change the cookie token then it won't match the ones in the database.
Comment: so the best way is to use api with JWT Thank you
Comment: Yes I use JWT too on my .NET Core API. It works like a charm.

Sensitive data on the client side


Given $A=\{(x,y)\in\mathbb{R}^2 \mid (x+m)^2-(y-m)^2=1\}$. Find $f(A)$ and $f^{-1}(A)$

Question: The question: Given a bijection $f:\mathbb{R}^2\to\mathbb{R}^2,\, (x,y)\mapsto (2x+y-m, x-2y-m)$. Determine $f(A)$ and $f^{-1}(A)$ where $A=\{(x_1,x_2)\in\mathbb{R}^2 \mid (x_1+m)^2-(x_2-m)^2=1\}$.
My attempt: So the condition of $A$ can be interpreted as:
$$
\begin{cases}
x=\sqrt{1+(y-m)^2}-m&\qquad&\text{if } x>-m\\
x=-m-\sqrt{1+(y-m)^2}&\qquad&\text{if } x\le -m\\
\end{cases}
$$
But then substitute into the bijection would make things ugly. Beside I feel that there is some logical flaw with such argument. Any suggestion on how to deal with this?
Comment: HINT.-$A$ is an hyperbola of parametrics $x=\sec (t)-m$ and $y=\tan (t)+m$ so you have to calculate
$$f\left(\sec (t)-m,\tan (t)+m\right)$$
Answer: Your function and its inverse act as
$$f(x,y) = (2x+y-m, x-2y-m)$$
$$f^{-1}(x,y) = \frac15(2x+y+3m, x-2y-m)$$
Set $(u,v) = f(x,y)$, then $(x,y) = f^{-1}(u,v) = \frac15(2u+v+3m, u-2v-m)$. Therefore:
\begin{align}
(u,v) \in f(A) &\iff (x,y) \in A\\
&\iff 1 = (x+m)^2 - (y-m)^2\\
&\iff 1 = \left(\frac{2u+v+3m}{5}+m\right)^2 - \left(\frac{u-2v-m}{5}-m\right)^2\\
&\iff 1 = \frac{1}{25} (28 m^2 + 44 m u + 3 u^2 - 8 m v + 8 u v - 3 v^2)\\
&\iff 25 = (2 m + 3 u - v) (14 m + u + 3 v)
\end{align}
Therefore $$f(A) = \{(u,v) \in \mathbb{R}^2 : (3 u - v+2m) (u + 3 v+14m) = 25\}$$

Set $(x,y) = f^{-1}(u,v)$, then $(u,v) = f(x,y) = (2x+y-m, x-2y-m)$. Therefore
\begin{align}
(x,y) \in f^{-1}(A) &\iff (u,v) \in A\\
&\iff 1 = (u+m)^2 - (v-m)^2\\
&\iff 1 = \left(2x+y-m+m\right)^2 - \left(x-2y-m-m\right)^2\\
&\iff 1 = -4 m^2 + 4 m x + 3 x^2 - 8 m y + 8 x y - 3 y^2\\
&\iff 1 = -(2 m - 3 x + y) (2 m + x + 3 y)
\end{align}
Therefore $$f^{-1}(A) = \{(x,y) \in \mathbb{R}^2 : (3 x - y-2m) (x + 3 y+ 2 m ) = 1\}$$


Finding unique partitions for a number

Question: I am using below code for finding partitions for a given number (N). How can I ensure only unique partitions? For instance partitions (1, 1, 1, 7), (1, 1, 7, 1), (1, 7, 1, 1) and (7, 1, 1, 1) would be considered the same and only one of these should be output.
Thanks
Regards
<code> Dim N = 10

        For i As Integer = 0 To N
            For j As Integer = 0 To N
                For k As Integer = 0 To N
                    For l As Integer = 0 To N
                        If i + j + k + l = N Then
                            Dim St As String = String.Format("({0:d}, {1:d}, {2:d}, {3:d})", i, j, k, l)
                            Console.WriteLine(St)
                        End If
                    Next
                Next
            Next
        Next

        Console.Read()
</code>
EDIT: Below seems to be working from someone's suggestion;
<code>Module Module1

    Sub Main()

        Console.WriteLine("Please enter an integer.")
        Dim sReadLine As String = Console.ReadLine()
        Dim iValue As Integer

        If IsNumeric(sReadLine) Then
            iValue = CInt(sReadLine)
        Else
            Console.WriteLine("'" & sReadLine & "' is not a numeric value. Press any key to exit.")
            'Application.Exit()
            Console.Read()
            Exit Sub
            End
        End If

        Console.Clear()
        Console.WriteLine("Number is {0}", iValue)
        Console.WriteLine("")

        Partitions1(iValue)

        Exit Sub

    End Sub

    Dim partitions As New List(Of Part)

    Private Sub Partitions1(N As Integer)
        For i As Integer = 0 To N
            For j As Integer = 0 To N
                For k As Integer = 0 To N
                    For l As Integer = 0 To N
                        If i + j + k + l = N Then
                            Dim thisPartition As New Part()
                            thisPartition.Parts = New Integer() {i, j, k, l}
                            If Not partitions.Contains(thisPartition) Then
                                partitions.Add(thisPartition)
                            End If
                        End If
                    Next
                Next
            Next
        Next

        For Each x In partitions
            Dim St = "("
            For Each y In x.Parts
                St = St & y & ", "
            Next
            St = Left(St, Len(St) - 2)
            St = St & ")"
            Console.WriteLine(St)
        Next

        Console.WriteLine("")
        Console.WriteLine("{0} unique partititons found.", partitions.Count)
        Console.Read()

    End Sub

    Public Class Part 'Sorted array of integer with comparer
        Implements IEquatable(Of Part)
        Public Property Parts As Integer()
            Get
                Return m_Parts
            End Get
            Set(value As Integer())
                m_Parts = value
                Array.Sort(m_Parts)
            End Set
        End Property

        Private m_Parts As Integer()

        Public Overloads Function Equals(other As Part) As Boolean _
           Implements IEquatable(Of Part).Equals
            If other Is Nothing Then
                Return False
            End If
            If other.Parts.GetLength(0) <> m_Parts.GetLength(0) Then Return False
            Dim result As Boolean = True
            Array.Sort(other.Parts)
            For I As Integer = 0 To other.Parts.GetLength(0) - 1
                If other.Parts(I) <> m_Parts(I) Then
                    result = False
                    Exit For
                End If
            Next
            Return result
        End Function
        ' Should also override == and != operators.
    End Class

End Module
</code>
Answer: Collect the found solutions in a list, then writen an algo which eliminates the duplicates from the list and then print the list.

Finding unique partitions for a number


(Open Source) Cloud-Filesystem to run a Database on Top?

Question: what are current "technologies and implementations" to get a filesystem with unlimited capacity by using single servers with their harddisk to form a "grid/cloud filesystem"?
I need to have unlimited space (by adding further servers) but it must be a filesysem that is capable of running a database on top.
I know of Apache Hadoop but that seems not be be Ideal for running a DB on top of it (or am I wrong??)
And iSCSI seems to be "remote/networked" but I do not know how and if this is clusterable?
thank you very much!!
jens
Answer: Two words: STUPID IDEA. This is like asking "what is the best way to win in formula one with a 40 ton truck". The design principles between distributed file systems and database storage systems are orthogonal - they go for totally different targets. Actually most proper databases will try living in a handfull of files - so they end up in one (not controlled) node anyway (per file).
For a database you want defined IO performance, seriously optimized latency - you do a lot of very time critial IO. Actually larger database storage systems are designed around IOPS - IO operations per second - optimizing delays out. Storage SIZE Is normally not critical - in the pre SSD days you bought discs not for space primarily, but for IO performance. I once had a chance to work with a database distribute over 190 discs in a SAN - because it needed the hugh IO performance. The discs were not particularly full.
For a distributed file system you want ease of management, transparenty of location, focus on storage size instead of defined IO performance. You actually can not guarantee IO performance on a good enough level as you get a very unreliable (as in: can change) infrastructure below. You rely on caches to handle performance in many parts, which is redundant with what the database does itself and will simply not work in a proper optimized database scenario.
One is a 40 ton truck for moving lots of things, the other is a highly tuned formula one car. You will not ever get them into the same boat because they are designed based on different assumptions.
Answer: Unless you have great bandwidth between the nodes, I don't think this is going to fly.
You could set up a distributed block device with drbd, for instance, and run a RAID setup over several boxes, mount the fs on a single node and run your database server. But the performance is going to suck unless you have LAN-level communications performance.
What are you storing in your database which does not fit a single server? Is it really cheaper for you to buy multiple boxes vs. one big server?
Have you looked into sharding?
Are you storing files in your database? If you are, could you split those off?
Answer: This depends on the type of database you're talking about.
If you're looking for a SQL-based database like MySQL or PostgreSQL, you're barking up the wrong tree (with a couple of interesting exceptions, see below).
If you're trying to run something like a glorified key-value store like Cassandra or HBase, read on. When the partitioning algorithm is order-preserving, you can do things similar to what you can do in SQL, except you have to do joins manually and you get the advantage of being able to map-reduce for aggregates and more complex analysis tasks (depending on the DB platform), potentially with the help of projects like Pig and Hive.
For Cassandra, you don't need a specific file system. Again, if you need to run queries and have things similar to indexes, you'll want to use an order-preserving partitioning algorithm.
For HBase, you need to use HDFS as the base FS. HyperTable used to work under either HDFS or KFS; right now, I don't see any mentions of KFS but I also saw something about being able to work in a standalone fashion like Cassandra. I'm not too sure about partitioning and sorting on HyperTable, but I know that HBase by default stores records in order and supports indexes.
Now the interesting exceptions.
There is a project called Hadoop DB which integrates PostgreSQL with Hadoop and may, depending on what you're trying to do, serve your needs.
There's also the crazy idea of writing a storage engine for MySQL that interfaces with one of the systems above. The joins and aggregates and such would be done for you on the MySQL side while the data storage, indexing and retrieval would be your job. You'd also need to coordinate for transactions if you choose to support them. This means you could have multiple load-balanced MySQL servers talking to a huge HBase cluster. The only thing you'd be missing is the ability to push out map-reduce tasks to make aggregates and analysis over large parts of your data set more efficient. But you could do that periodically outside MySQL, and store the analysis results in another table that you can query with MySQL, again, depending on your needs.
Answer: A relatively simple way to do this is create a virtual machine install at a provider like Linode.  They provide pre-installed versions of most Linux distributions.
Manage your storage under LVM.  If you need more storage, the provider can add it for you - just have LVM add the additional volume to the volume group.
Which filesystem you use is a separate question.


4/4 corresponds to 12/8 but 4/4 =/= 12/8

Question: How is it possible that a 4/4 signature corresponds to a 12/8 signature ? 4/4 is equal to 1 and 12/8 is more than 1 .
If i try to divide a 1/4 in 3 notes i get 1/12, not 1/8 as the 12/8 should be.
Comment: This could well be a duplicate question.
Comment: Possible duplicate of [What feel is 12/8 meter and why?](https://music.stackexchange.com/questions/52369/what-feel-is-12-8-meter-and-why)
Comment: I don't know about that being a duplicate of this question, that asks about "feel" of 12/8. Possibly a duplicate of something else?
Answer: The time signature does not function as a fraction in mathematics. The top number serves to tell how many beats per measure, while the bottom number tells what rhythm gets counted as one beat. In 4/4, for instance, the top 4 states that there are four beats per measure, whereas the bottom 4 states that one quarter note equals one beat.
Therefore, with 4/4, you'll feel a definite "one two three four, one two three four" throughout the song.
In 12/8, you'll have 12 eighth notes per measure. However, rather than feeling "1 2 3 4 5 6 7 8 9 10 11 12," you'll normally feel the eighth notes in groups of three -- "1 2 3 4 5 6 7 8 9 10 11 12".  Or, to simplify, "one and a two and a three and a four and a".
This is called subdivision of the beat, this grouping of eighth notes into groups of either two or three. In 4/8, for instance, you'll feel eighth notes in groups of two (1 2 3 4), whereas in 6/8, 9/8, or 12/8, you'll feel the eighth notes grouped into groups of three.
Hope this helps!
Answer: They are related in the sense that they are both quadruple time, meaning in both instances there are four beats to a bar. 4/4 time is just Simple Quadruple time where a beat is equal to a crotchet and 12/8 is Compound Quadruple time where there are four beats of dotted crotchets.
In essence, simple time means beats without dots and compound time means beats with dots. They are both four-time the one just having regular crotchet beats and the other dotted crotchet beats.
Comment: Does this mean that one bar in 12/8 time is half as long again as one bar in 4/4?
Comment: @Tim 12/8 is 1.5 times as long.
Comment: That could be true. How long is a crotchet?  Quite often something meant to be played in swing feel will be notated in 4/4, for simplicity, and a little picture at the top shows a crotchet = 3  triplet quavers. At this point, 4/4 equals 12/8 in length.
Comment: 6 crotchets vs 4 crotchets = 1.5 times as long.
Comment: 4 crotchet = 12 quaver triplets. But all of this, without bpm, is meaningless. One minim @ crotchet =120bpm is the same length as one crotchet @crotchet = 60 bpm. Not many pieces will be written part in 4/4, rest in 12/8. Semantics.
Answer: 4/4 is four quarter notes to the bar.  12/8 is four dotted quarters to the bar.  Useful for music where the sub-divisions of each beat are mostly into three.  Saves you writing a load of triplets (those groups of three 8th notes with a 3 bracket over the top, indicating that the three are to fit into the space normally taken by two of them).
Simple time.  One-and-Two-and-Three-and-Four-and.  4/4.   Or One-and-Two-and One-and-Two-and.  2/4.  (Etc. That's not an exclusive list of Simple time signatures.)
Compound time.  One-and-a-Two-and-a-Three-and-a-Four-and-a/  12/8.   Or One-and-a-Two-and-a One-and-a-Two-and-a.  6/8.  Etc.
Answer: Whilst the time signature looks like a mathematical fraction, in a way it is, but there again, it isn't !
The top number, just like a fraction, tells how many there are, the bottom tells what they are. So, in 4/4, there are 4 of them (top), and the bottom tells they are crotchets, aka quarter beat note value, in each bar or measure. So far so good. Just like a fraction.
When we get to a time signature like 6/8, there are 6 quavers (eighth notes) in each bar. The confusing part here is that they are arranged in two lots of three. So the count is either 1--2-- or put in another way, 123456. Still with this 'fraction' - 3/4 time has the same number of 'bits' in each bar, but they get emphasised differently. 123, as there are 3 crotchets to count.
Now on to 12/8. It's pretty well double 6/8 (surprise!), but counted 1--2--3--4-- in each bar. But - those quavers can be seen in a timing manner that 3 get played in the time of two in 4/4 time sig. So, in 4/4, using normal eighth notes, there will be 8, counted 1&2&3&4& in each bar, but the equivalent timing at the same tempo for 12/8 will be 1&a2&a3&a4&a. So both can be equal in timing (bpm) but their time sigs won't be equal mathematically. It ain't easy!


Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda?

Question: I get an error when try to start npm:
Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda

with a reference to an exported function (position 47:19
in the original .ts file), resolving symbol
CoreModule in D:/Projects/UI3/src/app/core/core.module.ts
Core is:
providers: [
    {provide: HttpService,
      useFactory: (backend: XHRBackend, options: RequestOptions) => { // Here 47 line number
        return new HttpService(backend, options);
      },
      deps: [XHRBackend, RequestOptions]},
    AuthenticationService,
    DialogsService,
    AuthenticationGuard,
    I18nService
  ]

So, it had worked before.
Answer: You need to extract your arrow function like:
export function httpServiceFactory(backend: XHRBackend, options: RequestOptions) {
    return new HttpService(backend, options);
}

...

@NgModule({
  ...
  providers: [
    {
        provide: HttpService,
        useFactory: httpServiceFactory,
        deps: [XHRBackend, RequestOptions]
    },
    AuthenticationService,
    DialogsService,
    AuthenticationGuard,
    I18nService
  ]

See also

https://github.com/angular/angular/issues/11262
Comment: Thanks! You are a hero!


floating point value not working if the value is not manually assigned

Question: I need to check if the percentage change is > 0, ==0, < 0, and NULL.
So I got get_count() that returns result of SELECT statement...:
get_count () {
    sqlplus -s un/pass <<!
    set heading off
    set feedback off
    set pages 0
    select trunc(PRNCT_CHANGE, 3)
    FROM SEMANTIC.COUNT_STATISTICS;
   exit;
!
}

count=$(get_count $1) #possible values: -0.789, -10.999, 11.897, 20, 1, 0...

if [ -z "$count" ]; then
    echo "The count percentage change returns null value"
elif [[ "$count" -gt 0 ]]; then
    echo "The count percentage change ($count) is greater than zero"
elif [[ "$count" == 0 ]]; then
    echo "The count percentage change stays unchanged (is zero)"
elif [[ "$count" =~ ^[\-0-9] ]]; then
    echo "The count percentage change is $count"
else
   echo "$count  ... Something else is wrong here"
fi

If I manually assign value for $count ie:
count=-0.987

This is working great.
otherwise if I let get_count() method return the value, it is always jumping to else statement...
Should I convert the value that gets passed to $count variable somehow..?
Comment: Your `get_count` doesn't actually use the argument passed to it.
Comment: Yea...I get the value. Because it gets echoed out:  "-71.888  ... Something else is wrong here"
Comment: is that what you meant? @chepner
Comment: I'm just pointing out that your function will return the same value no matter what the value of `$1` is. That may be relevant after your immediate problem is fixed.
Comment: yes, i commented out the complexity of the query@chepner
Answer: bash doesn't understand floating point values. You'll need to use an external program like bc to do the comparison:
if [ -z "$count" ]; then
    echo "The count percentage change returns null value"
elif [[ $(echo "$count > 0" | bc ) -eq 1 ]]; then
    echo "The count percentage change ($count) is greater than zero"
elif [[ $(echo "$count < 0" | bc ) -eq 1 ]]; then
    echo "The count percentage change ($count) is less than zero"
elif [[ "$count" == 0 ]]; then
    echo "The count percentage change stays unchanged (is zero)"
else
   echo "$count  ... Something else is wrong here"
fi


Dificuldade em formular query

Question: Em um sistema existem parcelas cadastradas . Os usuários podem classificar as parcelas por famíliaDeParcela sendo que cada usuário tem suas próprias famíliaDeParcela.
As parcelas são comuns a todos.
Tenho 4 tabelas:
Usuario que tem cod_usuario PK
Parcela que tem cod_parcela PK
FamiliaDeParcelas que tem cod_usuario FK e cod_familia PK
Parcela_FamiliaParcela que tem cod_familiaFK , cod_parcela FK , e uma PK composta por cod_familia e cod_parcela
Exemplo de uso :
Temos 5 parcelas cadastradas
    Horas extras além da 6a,
    Horas extras além da 8a,
    danos morais,
    danos materiais,
    periculosidade.

O usuário 1 cadastra as famílias HORAS EXTRAS, DANOS e OUTROS que pertencerão só a ele e então pode classificar
    Horas extras além da 6a --> HORAS EXTRAS
    Horas extras além da 8a --> HORAS EXTRAS
    danos morais ---> DANOS
    danos materiais ---> DANOS
    periculosidade ----> OUTROS

E o usuário 2 cadastra as famílias SALARIAL e INDENIZATÓRIA que pertencerão só a ele e então pode classificar
    Horas extras além da 6a --> SALARIAL
    Horas extras além da 8a --> SALARIAL
    danos morais ---> INDENIZATÓRIA
    danos materiais ---> INDENIZATÓRIA
    periculosidade ----> NULL ( DEIXAR SEM CLASSIFICAR )

Quando um usuário estiver usando preciso listar todas as parcelas com sua FamiliaDeParcela e caso não tenha sido classificada , retornar só os dados da parcela, mas só desse usuario !
Se faço
     select *
     from Parcela p
     left outer join Parcela_FamiliaDeParcelas pf ON pf.cod_parcela = p.cod_parcela
     left outer join FamiliaDeParcelas f on f.cod_familia = pf.cod_familia and f.cod_usuario = @codusuario

Com essa query pra cada classificação que o usuário faz ela retorna 1 ocorrencia extra pra cada classificação da mesma parcela que outro usuário fez ( porém com null nos dados da familia )
Se adiciono no final um where f.cod_usuario = @codusuario ele retorna só as parcelas do usuário , mas não as parcelas não classificadas
O que devo fazer ?
Answer: A pergunta está bem confusa (rs), mas pelo que entendi, acho que há erro de cardinalidade. Veja na imagem abaixo o modelo relacional das tabelas:

Se estiver correto, você gravará o campo cod_familia na tabela Parcela como uma FK (Chave Estrangeira), assim não haverá a necessidade da tabela Parcela_FamiliaParcela. E também gravará o campo cod_usuario na tabela Parcela como uma FK.
E sua consulta poderá ficar assim:
select *
from parcela p
left join FamiliaDeParcelas fp on (fp.cod_familia = p.cod_familia)
inner join Usuario u on (pf.cod_usuario = u.cod_usuario)
where pf.cod_usuario = @cod_usuario

Espero ter colaborado!
Comment: O diagrama que você fez está correto Eduardo, porém uma parcela não pertence a um usuário e por isso não posso colocar em parcela uma FK_USUARIO . Também não posso colocar FK_Familia na parcela uma vez que ela não pertence a um usuário e cada usuário pode fazer sua própria classificação . Se fizesse isso eu teria que recadastrar todas as parcelas para todos os usuários . ex parcela1 , usuario1 ,familia1  / parcela1 , usuario2,familia2
Comment: Vou tentar clarificar aqui , vamos considerar que Parcela = Produto , FamiliaDeParcela = Categoria em um sistema que todos os usuarios podem vender  Arroz , chocolate e refrigerante . um usuário pode criar uma categoria alimentos e classificar Arroz, chocolate e Refrigerante como alimentos .  um segundo usuário cria 3 categorias comida,doce e bebida , e classifica arroz como comida , chocolate como doce e refrigerante como bebida .
Comment: Eduardo, consegui solucionar usando right join !  Muito obrigado pela ajuda cara , fiquei extremamente contente por ter recebido sua resposta com o trabalho de fazer o diagrama e tudo . Logo vou deletar essa pergunta porque acho que ela não ajuda muita gente e realmente ta confusa . Mas não antes de agradecer . Brigadasso !!
Comment: Kkkkk. Pelo seu primeiro comentário o que eu ir realmente não ia funcionar. Mas que bom que conseguiu. Estamos aqui pra isso, para tentar ajudar. Fica na paz.
Comment: Foi a primeira vez que tive que usar right join na vida !  Tive que começar a query  from FamiliaDeParcela pra então fazer o join na tabela de união usando FamiliaDeParcela.id e não Parcela.id  e como tinha que listar todas as parcelas right join Parcela no final , feito isso funcionou certinho ! \o//
Answer: O problema era o seguinte:
Como comecei a query from Parcela p  e fazia um left outer join Parcela_FamiliaParcela usando p.cod_parcela a query retornava todos os registros que tinham p.cod_parcela incluíndo os dos outros usuários .
Percebi isso e então comecei a query from FamiliaDeParcela fp e fiz o um left join usando fp.cod_familia e @codusuario  seguido de um right join pra listar todas as parcelas e assim funcionou direitinho !
A query final ficou:
    SELECT *  FROM FamiliaDeParcelas
    LEFT OUTER JOIN PARCELA_FAMILIAPARCELAS f ON f.cod_familia = FamiliaDeParcelas.cod_familia
    AND FamiliaDeParcelas.cod_usuario = @codusuario
    RIGHT OUTER JOIN Parcela ON f.cod_parcela = Parcela.cod_parcela

Answer: Veja se assim resolve o seu problema:
select * from `Parcela_FamiliaParcela` `pfp`
left join `FamiliaDeParcelas` `fdp` on (`fdp`.`cod_familia`=`pfp`.`cod_familia`)
left join `Usuario` `u` on(`u`.`cod_usuario`=`fdp`.`cod_usuario`)
left join `Parcela` `p` on (`p`.`cod_parcela`=`pfp`.`cod_parcela`)
where `u`.`cod_usuario`=@cod_user

Comment: Ivan , acredito que assim só vai retornar as parcelas que foram classificadas , além disso não teria a necessidade de unir a tabela usuário uma vez que os dados do usuário só viriam quando u.cod_usuario e  fdp.cod_usuario fossem iguais , logo where fdp.cod_usuario = @cod_user daria no mesmo
Comment: A query que eu fiz é pra trazer tudo na relação baseado no usuário (você pode tirar a condição `where`. E tudo que não precisar). O que você acredita, só vai valer se você executar a query primeiro, depois tire suas conclusões. Pois acredito que você está enganado.
Comment: A união "left join" não é limitadora.
Comment: https://uploaddeimagens.com.br/imagens/uniao-png--2 Segue sua query executada , aconteceu exatamente o que falei... tenho 109 parcelas cadastradas , so listou as 2 classificadas pra esse usuário
Comment: pela imagem qualquer um pode ver que não é a minha query... desculpe.
Comment: não, minha query, tem : * não está pegando 2 campos. Além disso, a imagem não está completa. Então ela não prova os fatos, além disso, não se trata de humildade, a questão é ser claro e transparente. Eu não vejo isso na forma que vc se expressa. Não quis te ofender, só que a falta de humildade partiu de você, quando você pré julgou a minha query, pois aqui estamos empenhados em ajudar o outro.
Comment: se minha opinião não atende a seu propósito, não tem porque questioná-la, simplesmente a descarte. Assim como eu faço quando não considero útil. Eu não perco meu tempo. Assim caminha a Humilnidade.
Comment: Ivan , segue sua query executada ao lado da query que usei pra resolver o problema . Lembrando que a quantidade de campos selecionados não interfere no retorno . https://uploaddeimagens.com.br/imagens/imag-png

Dificuldade em formular query


Maps and Wedge Products

Question: I'm currently trying to prove Cramers rule with the wedge product definition of a determinant. The proof hinges on the fact that if M is some map, then we can write:
$$ M\left(\vec a \wedge \vec b\right) = M\left( \vec a \right) \wedge M\left( \vec b \right) $$
However, I'm at a loss here, because I really don't understand why this should be true. IF M is a linear map, I thought linearity implies that $M(a+b) = M(a)+M(b)$, can anybody explain why the above identity is true?
Thanks in advanced
Comment: Can you explain your notations? What is $\vec a$ (where does it live in?) and what is $\wedge$? What is $M(\vec a \wedge \vec b)$?
Comment: As I understand it, $\vec a$ is a vector in n dimensional space, and M is a map - which is like a matrix, that takes $\vec a $ and returns a new vector - like $A \vec x  = \vec b$ does in linear algebra. $\wedge$ is the standard wedge product operator.
Comment: Have you tried going into components and using some identity for an anti symmetric tensor?
Comment: So to clarify, applying the map M to the bivector returned by $\vec a \wedge \vec b$, produces the same bivector we would get if we apply the map to the vector a, then to the vector b; before finding the corresponding bivector with the wedge product
Comment: So let's say $M$ is a linear map from some vector space to itself. But $\vec a\wedge \vec b$ will live in a different vector space. So how do you interpret $M(\vec a \wedge \vec b)$?
Comment: I haven't tried that, no. I'm not entirely sure what you mean, could you please elaborate :).
Comment: Thats exactly where my confusion comes from John. I don't see how this can be true, because I don't see how M can apply to both a bivector (LHS) and to a standard vector (RHS).
Comment: https://www.youtube.com/watch?v=moPJKRRMxjk - IF you go to approximately 6:30, he's using the identity I've written above.
Answer: This is perhaps a slight abuse of notation in that, as John pointed out, $M$ acting on a bivector $a \wedge b$ seems incompatible with the notion that $M$ acts on ordinary vectors.
A possible resolution to the notation issue would be to write, for vectors $v_1, v_2, \ldots, v_k$,
$$M_{(k)} (v_1 \wedge v_2 \wedge \ldots \wedge v_k) \equiv M(v_1) \wedge M(v_2) \wedge \ldots \wedge M(v_k)$$
And hence, given a linear operator $M$, we also define several other linear maps $M_{(2)}, M_{(3)}$, and so on.  Nevertheless, it's pretty common to just say $M(a \wedge b) \equiv M(a) \wedge M(b)$ since there's little chance of getting confused about what map you're applying.
Since each of the $M_{(k)}$ is technically distinct from the others, I think you should be able to accept that this is merely a convenient definition?  That we choose this definition might be motivated from the tensor product, but I must stress it is merely a convenient choice until one asks why and how this definition gives us $M_{(n)}(\epsilon) = (\det M) \epsilon$ for any $n$-vector $\epsilon$.
Comment: Thanks for that, this clears things up a lot. But just to clarify, if M is a matrix, and we apply it to a: would the same matrix be applied to $ a \wedge b$? I know this is probably just repeating what you said - but I just want to be completely clear.
Comment: If you choose a basis, and write the linear map $M$ in terms of components in that basis, then the matrix representation of $M_{(2)}$ is going to be different from that of $M$.  Among other reasons, $M$ acts on common vectors, which have $n$ components, but $M_{(2)}$ acts on bivectors, which have $n(n-1)/2$ components.

Maps and Wedge Products


Views to Display Nearby nodes according to user current location(latitued/longitute)GPS

Question: I have Content type named Restaurant, When creating restaurant nodes I am imputing the Latitude/Longitude  using the GEOFIELD  module.
I have managed to Display all the restaurants in One Map using Views, Leaflet and leaflet Markercluster modules, you can see the attached screenshot.
My task now is to create a page named Nearby, where all restaurants near to user's current location(Latitude/Longitude) will be displayed, let say restaurant within 2km from the current users location.
To get the current user location, A prompt will appear on his/her browser asking them to share their location this is more specific for anonymous users.
I believe there must be a way to accomplish this task using Views or custom module.
Please Guide me step by step on how to make it happen.
any help will be highly appreciated.
Answer: Having messed with many Drupal mapping modules, I've found IP Geolocation Views & Maps to be the best overall helper (along with Leaflet, which I love). Give it a shot! It has lots of options, supports lots of maps, has geolocation stuff built in, marker clustering and some other stuff.
Comment: Thank you @scotself,  i will give a try as you suggested and Give u feedback.


Finding intervals on an instrument vs. naming them

Question: I would like to piggyback on this question: If someone can sing a melody, why can they not also recognize the intervals within that melody?
The OP is asking why it is easy to sing a song we know, meaning we memorized the intervals, why is it difficult to name intervals when we hear them.
My twist on this is:
If I play with apps that train me to recognize intervals, it takes some warmup period before I'm able to do it decently, then accuracy goes up. But somehow, each time I try to play again, I am back to the same, without the warming up I'm not so good. But overall, if this was a competition, I wouldn't be so good, despite having started to play instruments some 40 years ago :)
However, when I hear an interval, I'm usually able not only to replicate it on a guitar with good accuracy, but I'll hit the first note quite close to the original as well.
(To some extent I can do it on the piano too, but not as well as on the guitar.)
Has anyone an idea why there is such a difference?
Comment: A sort of analogy might be  - if someone can say a word, why can't they spell it?
Comment: You can't identify something you were never taught.
Comment: How long have you been using the apps? If you've been using them for half an hour a day for 6 months, for example, I'd be concerned about your slow learning rate.
Comment: haha, no, I've been using them .. when stuck waiting in the car for my gf to be ready :) maybe 1 time a month or so in the last couple years
Answer: Part of this may be a form of instrument-specific absolute pitch. Although most of my students don't have absolute pitch, many do have terrific pitch memory on their instrument: thus pianists can recognize pitches that are played on a piano, but not those played by a cello. It sounds like you have better pitch memory when it comes to the guitar than on the piano. (Absolute pitch is, after all, just really good pitch memory.)
As for errors creeping in before a warmup period, consistent practice often involves occasional steps backwards where we briefly forget something or are briefly less successful than we once were. It happens when learning foreign languages, and it certainly happens in our musical lives. I wouldn't stress too much on where the beginnings of your sessions are, as long as the ends of your sessions show improvements.
Answer: The simple fact is that these are all different skills.
Also keep in mind the fact that our brain is very good at learning to perform different tasks with the least possible effort, but also without learning anything more than absolutely necessary.
For example, if you learned to write with your right hand, and it might seem logical to conclude that doing the same action with your left hand should be just as easy, but it turns out it is not...
In a similar way, repeating what you hear with your voice is one thing (which by the way parrots and other birds can do pretty well, too), but understanding intellectually what interval that is according to a certain system (temperate tuning) is quite another thing. And having learned what intervals they are, being able to play them smoothly on a physical instrument, is yet another different thing.
So, they are just different skills that require different physical and conceptual types of practice to be mastered. Of course some components are overlapping, but many other components are not, and for that dedicated practice is required.
Answer: Intervals between two strings on a guitar have a particular shape - P4 on adjacent strings is the same fret, wherever it is played (obviously not between strings 2 and 3!). On piano there's a whole host of different looking intervals; that same P4 can be white/white, black/black, white/black or black/white. So it won't be as easy to pick out, unless you know your intervals intimately.
Difficulty naming them? Most folk can sing an interval without even realising that's what it is, never mind what it's named. And then there's always - 'is that an aug.4 or a dim.5..?


Clip a UIView with a circle path Swift iOS

Question: I'm trying to clip my camera preview (UIView) inside a circle path but the mask I seems to not clip my view.

        let preview = cameraController!.previewLayer
        preview.translatesAutoresizingMaskIntoConstraints = false
        _view.translatesAutoresizingMaskIntoConstraints = false

        let path = UIBezierPath(arcCenter: CGPoint(x: _view.frame.size.width/2, y: _view.frame.size.height/2),
                                radius: _view.frame.size.width/2.5,
                                startAngle: CGFloat(0).toRadians(),
                                endAngle: CGFloat(360).toRadians(),
                                clockwise: false)

        path.reversing()
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.lineWidth = 5
        preview.layer.mask = shapeLayer
        preview.layer.addSublayer(shapeLayer)
        preview.clipsToBounds = true

        _view.addSubview(preview)

What I am missing here ?
Answer: Most of the set up was fine, just changed a few things to get it working:
func maskPreview()
{
    // No change from your code
    let path = UIBezierPath(arcCenter: CGPoint(x: view.frame.size.width/2,
                                               y: view.frame.size.height/2),
                            radius: view.frame.size.width/2.5,
                            startAngle: CGFloat(0).toRadians(),
                            endAngle: CGFloat(360).toRadians(),
                            clockwise: false)

    // Removed this, not sure it was needed
    // Add it back if needed
    //path.reversing()

    // No change
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath

    // This should not be transparent since we need
    // the camera preview to be seen through here
    shapeLayer.fillColor = UIColor.white.cgColor

    // No change
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.lineWidth = 5

    // No change
    previewView.layer.mask = shapeLayer

    // You do not need to add the shape layer as a sublayer
    // after defining it as your mask
    // previewView.layer.addSublayer(shapeLayer)

    // No change
    previewView.clipsToBounds = true
}

End result

Update to discuss about the mask layers color
The documentation for mask defines this behavior that the alpha channel determines what content, if any will be allowed to show.

mask
An optional view whose alpha channel is used to mask a view's
content.
Discussion
The view's alpha channel determines how much of the view's
content and background shows through. Fully or partially opaque pixels
allow the underlying content to show through but fully transparent
pixels block that content.

The fill color is not the circle color as you rightly pointed out. You could change this and it would not matter as long as it is not clear color. It determines whether the mask renders the underlying view or not.
To actually add some color to this, I believe you cannot do it directly through the mask layer and you would need an intermediary layer.
Comment: @nicover - The border works the same as the fill color, that is, anything of the mask that is not transparent will be used to display pixels of the view below it. A quick test you can do is to make your `shapeLayer.fillColor = UIColor.clear.cgColor` clear again and I believe you will see the camera preview in the border only. If you want to add colors or border colors, I believe you will need to add another shape layer in addition to your mask - give it a go, if it is still proving too tricky, maybe open another question.
Comment: Thanks for this Shawn can't understand why the fill color is white ? The fill color is not the circle color then
Comment: @nicover - I updated the answer with some notes from the documentation.
Comment: great thanks again. please one more thing if I want to update the radius value here let say on click/drag I must to re execute all of this code ? or can I update only a part ? for the radius
Comment: I think you can do something with `CABasicAnimation` - some insights here https://stackoverflow.com/questions/36459532/uiview-layer-mask-animate and it could be a good new question if you are unable to figure it out.
Comment: Thanks.  regarding this question do you know why the stroke color is gone ?


upgraded php to 5.3.19 and memcached stopped working

Question: I have a server with centos 6.3 and cPanel
After the upgrade from php 5.3.16 to php 5.3.19 my site stopped working.
When I try to execute an index.php manually, I'm receiving the following error.

php: symbol lookup error: /usr/local/lib/php/extensions/no-debug-non-zts-20090626/memcached.so: undefined symbol: memcached_last_error_errno

Reinstalled memcached and memcache via pecl and manually but that did not help.
What is causing this problem and how do I fix it ?
Answer: Memcached 2.x extension in PHP requires a newer version of libmemcached.
So you need to make sure you remove the old one from the system:
yum remove libmemcached

Be sure it removed libmemcached.so.2* from your system.
Download & compile newer libmemcached from https://launchpad.net/libmemcached/+download (for me libmemcached-1.0.13 compiles fine on Centos 6.3)
Recompile memcached extension by issuing:
pecl install -f memcached

Now it should be fine.
For me it was.
Answer: Check for the "extension=memcached.so" extension entry in new php.ini file. Make sure it is there.
Now run "updatedb && locate memcached.so" to find this module and copy it to /usr/local/lib/php/extensions/no-debug-non-zts-20090626/ location.
Comment: His issue isn't about PHP not being able to find the extension; there are symbols that are not resolving in the SO file, presumably because he's got an old memcache library than what is required from the PHP extension.