How to use a 2D array as a result from a function in bash script

Question: I have the following function:
function regex_match_2d_list {
  local regex=$1
  local text=$2
  local groups=()
  while [[ $text =~ $regex ]]; do
    local group=()
    for (( i=0; i<${#BASH_REMATCH[@]}; i++ )); do
      group+=("${BASH_REMATCH[$i]}")
    done
    groups+=("${group[@]}")
    text=${text#*"${BASH_REMATCH[0]}"}
  done
  echo "${groups[@]}"
}

what I am trying to do is to have a function that is going to receive a regex and a text and it will output a 2d list where each element of that list is composed of all the groups from regex:
pattern="^([a-z]+)\s([a-z]+)"
text="hello world
foo bar"

res=$(regex_match_2d_list "$pattern" "$text")
echo "${res[0,1]}"

if I did understand it correctly, by doing res[0,2] I should receive "world" because is the second group of the first element.

but instead if am not getting anything. Could anyone explain to me what I am doing wrong here?
Answer: Note: you can debug those problem yourself by adding 'declare -p BASH_REMATCH text` immediately after the match. Short version below:
The line: text=${text#*"${BASH_REMATCH[0]}"} is expected to remove the match. However, the match does NOT include the trailing separators after the second token (new line between "hello world" and "foo bar"). You want to change the match to remove any trailing new line.
One possible solution - add the new line to the end of the pattern. To handle the last line which is not terminated with new line - I made it optional (with '?'). Possible to append new line to the text as alternative.
pattern="^([a-z]+)\s([a-z]+)"$'\n?'

Second issue is the transfer of BASH_REMATCH to groups (via intermediate group variable). Current code also copy element 0 of RE_BATCH, which will result in duplicating entries in groups. Consider using groups+=(${BASH_REMATCH[@]} instead.
Last problem is the assignment to 'res'. Current code will 'flatten' the array into single string. You probably want to get res as an array. One possible (but not always safe) to use array assignment res=($(regex_match ...)).
Final code:
function regex_2 {
  local regex=$1
  local text=$2
  local groups=()
  while [[ $text =~ $regex ]]; do
    groups+=("${BASH_REMATCH[@]:1}")
    text=${text#*"${BASH_REMATCH[0]}"}
  done
  echo "${groups[@]}"
}

pattern="^([a-z]+)\s([a-z]+)"$'\n?'
text="hello world
foo bar"

res=($(regex_2 "$pattern" "$text"))
declare -p res

Comment: that's almost ok, but if I am running you code I will have each element twice.
declare -a res=([0]="hello" [1]="world" [2]="hello" [3]="world" [4]="foo" [5]="bar" [6]="foo" [7]="bar")
Any idea why?
Comment: Oops, I did not notice. I've updated: `groups+=("${BASH_REMATCH[@]:1}")` so it will not copy the first element which include the complete matched text
Comment: even if your function runs ok for this example I think something is wrong, or is it not suppose to work with any regex?

For example by using this regex: `$'\[OK\][[:space:]]+([[:alnum:]_]+)\.([[:alnum:]_]+)([^[]*)'`

and the fallowing text:
`org_output="[OK] AAA.BBBBBB
aaabbbcccdddfffed
asdadadadadadsada
[OK] CCC.KKKKKKK
some text here
[OK] OKO.II"`
Comment: the output from your function will be: `declare -a res=([0]="[OK]" [1]="AAA.BBBBBB" [2]="aaabbbcccdddfffed" [3]="asdadadadadadsada" [4]="AAA" [5]="BBBBBB" [6]="aaabbbcccdddfffed" [7]="asdadadadadadsada" [8]="[OK]" [9]="CCC.KKKKKKK" [10]="some" [11]="text" [12]="here" [13]="CCC" [14]="KKKKKKK" [15]="some" [16]="text" [17]="here" [18]="[OK]" [19]="OKO.II" [20]="OKO" [21]="II" [22]="AAA" [23]="BBBBBB" [24]="aaabbbcccdddfffed" [25]="asdadadadadadsada" [26]="CCC" [27]="KKKKKKK" [28]="some" [29]="text" [30]="here" [31]="OKO" [32]="II")
`
Comment: but if I will do it via while: `while [[ $org_output =~ $regex_pattern_run ]]; do
  declare -p BASH_REMATCH
  org_output=${org_output#*"${BASH_REMATCH[0]}"}
done` it is going to be `declare -a BASH_REMATCH=([0]=$'[OK] AAA.BBBBBB\naaabbbcccdddfffed\nasdadadadadadsada\n' [1]="AAA" [2]="BBBBBB" [3]=$'\naaabbbcccdddfffed\nasdadadadadadsada\n')
declare -a BASH_REMATCH=([0]=$'[OK] CCC.KKKKKKK\nsome text here\n' [1]="CCC" [2]="KKKKKKK" [3]=$'\nsome text here\n')
declare -a BASH_REMATCH=([0]="[OK] OKO.II" [1]="OKO" [2]="II" [3]="")
`
Comment: isn't it suppose to get the same answer? Or I did get it wrong?
Comment: @Mircea: I execute the example with '[OK] AAA.BBBB ...', I'm getting:
declare -a res=([0]="AAA" [1]="BBBBBB" [2]="aaabbbcccdddfffed" [3]="asdadadadadadsada" [4]="CCC" [5]="KKKKKKK" [6]="some" [7]="text" [8]="here" [9]="OKO" [10]="II")
Which I believe is the expected output. I'm using Ubunto on WIN10 (bash 5.0). I'm not sure how do you get the output your described (with [OK]). Do you have any leftover 'echo' in your function ?
Comment: Well I am sure then that I am getting it right but based on that regex that I gave it to you I would expect this outpus: `declare -a BASH_REMATCH=([0]=$'[OK] AAA.BBBBBB\naaabbbcccdddfffed\nasdadadadadadsada\n' [1]="AAA" [2]="BBBBBB" [3]=$'\naaabbbcccdddfffed\nasdadadadadadsada\n')
declare -a BASH_REMATCH=([0]=$'[OK] CCC.KKKKKKK\nsome text here\n' [1]="CCC" [2]="KKKKKKK" [3]=$'\nsome text here\n')
declare -a BASH_REMATCH=([0]="[OK] OKO.II" [1]="OKO" [2]="II" [3]="")
`
Comment: If you copy my regex and my text example and then go try them over here https://regex101.com/ it would display the same result. I am not sure why that function is not working in the same way, or I did not really understand the solution.
Comment: or to put it simply... why there is a difference between your function and this code:  `while [[ $org_output =~ $regex_pattern_run ]]; do
  declare -p BASH_REMATCH
  org_output=${org_output#*"${BASH_REMATCH[0]}"}
done` isn't it supposed to do the exact same thing?
Comment: more then that, I've just tested, I've I will run the exact same code that is inside that function: `var_test=()
while [[ $org_output =~ $regex_pattern_run ]]; do
  var_test+=("${BASH_REMATCH[@]:1}")
  org_output=${org_output#*"${BASH_REMATCH[0]}"}
done

declare -p var_test` I will get the expected output: `declare -a var_test=([0]="AAA" [1]="BBBBBB" [2]=$'\naaabbbcccdddfffed\nasdadadadadadsada\n' [3]="CCC" [4]="KKKKKKK" [5]=$'\nsome text here\n' [6]="OKO" [7]="II" [8]="")
`
but somehow this is not working within the function...
Comment: I did ask a new question, if you would be kind to help me also whit this one, I've explained everything over there :).
https://stackoverflow.com/questions/74946104/why-dose-not-echo-return-the-same-thing-as-without
Comment: @Mircea I've posted an answer to the other question that cover the case where the text contain non alphanumeric characters.


Como criar um arquivo txt?

Question: No Java eu uso o PrintWriter e funciona perfeitamente, mas no Android estou apanhando muito, não funciona de jeito nenhum.
Alguém pode me ajudar nessa? É uma coisa simples, mas estou travado. Eu precisava criar um .txt simples com uma string. Agradeço desde já!
Comment: ...em um diretório que você possa visitar depois com um gerenciador de arquivos para poder ver o arquivo, correto?
Comment: sim, apenas criar um txt na área de trabalho ou nos meus documentos por exemplo.
Answer: Primeiro você deve inserir no AndroidManifest.xml a permissão para gravar no sdcard, antes da tag application :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Depois de criar os atributos, você vai criar o diretório:
private File diretorio;
private String nomeDiretorio;
private String diretorioApp;

Após isso, você deve definir o diretório:
diretorioApp = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            + "/"+nomeDiretorio+"/";

diretorio = new File(diretorioApp);
diretorio.mkdirs();

Depois de você criar o diretório onde o arquivo vai ser salvo, pode criar o arquivo txt:
//Quando o File() tem um parâmetro ele cria um diretório.
//Quando tem dois ele cria um arquivo no diretório onde é informado.
File fileExt = new File(diretorioApp, nomeArquivo);

//Cria o arquivo
fileExt.getParentFile().mkdirs();

//Abre o arquivo
FileOutputStream fosExt = null;
fosExt = new FileOutputStream(fileExt);

//Escreve no arquivo
fosExt.write(etTexto.getText().toString().getBytes());

//Obrigatoriamente você precisa fechar
fosExt.close();

Qualquer dúvida, da um toque ;D

Como criar um arquivo txt?


Xamarin.Android using MvvmCross crashes on Activity launch

Question: I am currently developing a Xamarin app and all of a sudden my Android app started crashing on LoginActivity. I have researched a lot on "

Java.Lang.ClassNotFoundException: Didn't find class
  "android.support.v7.appcompat.R$styleable" on path

"
Tried things like updating Android SDK, deleting bin and obj folder.  Looking at stacktrace it seems to be an issue with MvvmCross.  Currently I am using 3.5.1 of MvvmCross.
Another fact is that I am the only one in team who is facing this issue.
<code>[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] Java.Lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/appcompat/R$styleable; ---> Java.Lang.ClassNotFoundException: Didn't find class "android.support.v7.appcompat.R$styleable" on path: DexPathList[[zip file "/data/app/org.cancer.fundraising-1/base.apk"],nativeLibraryDirectories=[/data/app/org.cancer.fundraising-1/lib/x86, /vendor/lib, /system/lib]]
[MonoDroid]   --- End of managed exception stack trace ---
[MonoDroid] java.lang.ClassNotFoundException: Didn't find class "android.support.v7.appcompat.R$styleable" on path: DexPathList[[zip file "/data/app/org.cancer.fundraising-1/base.apk"],nativeLibraryDirectories=[/data/app/org.cancer.fundraising-1/lib/x86, /vendor/lib, /system/lib]]
[MonoDroid]     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
[MonoDroid]     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
[MonoDroid]     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
[MonoDroid]     at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:118)
[MonoDroid]     at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
[MonoDroid]     at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59)
[MonoDroid]     at md5da1044ae077a2d5a79e87e5c6bedf113.LoginActivity.n_onCreate(Native Method)
[MonoDroid]     at md5da1044ae077a2d5a79e87e5c6bedf113.LoginActivity.onCreate(LoginActivity.java:31)
[MonoDroid]     at android.app.Activity.performCreate(Activity.java:5990)
[MonoDroid]     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
[MonoDroid]     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
[MonoDroid]     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
[MonoDroid]     at android.app.ActivityThread.access$800(ActivityThread.java:151)
[MonoDroid]     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
[MonoDroid]     at android.os.Handler.dispatchMessage(Handler.java:102)
[MonoDroid]     at android.os.Looper.loop(Looper.java:135)
[MonoDroid]     at android.app.ActivityThread.main(ActivityThread.java:5254)
[MonoDroid]     at java.lang.reflect.Method.invoke(Native Method)
[MonoDroid]     at java.lang.reflect.Method.invoke(Method.java:372)
[MonoDroid]     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
[MonoDroid]     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
[MonoDroid]     Suppressed: java.lang.ClassNotFoundException: android.support.v7.appcompat.R$styleable
[MonoDroid]         at java.lang.Class.classForName(Native Method)
[MonoDroid]         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
[MonoDroid]         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
[MonoDroid]         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
[MonoDroid]         ... 19 more
[MonoDroid]     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
[MonoDroid]   --- End of inner exception stack trace ---
[MonoDroid]   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0xa047bf80 + 0x0002b> in <filename unknown>:0
[MonoDroid]   at Android.Runtime.JNIEnv.CallNonvirtualVoidMethod (IntPtr jobject, IntPtr jclass, IntPtr jmethod, Android.Runtime.JValue* parms) <0xa2007008 + 0x000b3> in <filename unknown>:0
[MonoDroid]   at Android.App.Activity.OnCreate (Android.OS.Bundle savedInstanceState) <0xa1018918 + 0x0014f> in <filename unknown>:0
[MonoDroid]   at ACS.FundRaising.Android.MvxActionBarEventSourceActivity.OnCreate (Android.OS.Bundle bundle) <0xa047b4e0 + 0x00037> in <filename unknown>:0
[MonoDroid]   at ACS.FundRaising.Android.LoginActivity.OnCreate (Android.OS.Bundle bundle) <0xa047b278 + 0x0001b> in <filename unknown>:0
[MonoDroid]   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_savedInstanceState) <0xa116f9b0 + 0x00057> in <filename unknown>:0
[MonoDroid]   at (wrapper dynamic-method) System.Object:dd5e6f9d-f207-497c-b5c3-0a2c9dac76e7 (intptr,intptr,intptr)
[MonoDroid]   --- End of managed exception stack trace ---
[MonoDroid] java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/appcompat/R$styleable;
[MonoDroid]     at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:118)
[MonoDroid]     at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
[MonoDroid]     at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59)
[MonoDroid]     at md5da1044ae077a2d5a79e87e5c6bedf113.LoginActivity.n_onCreate(Native Method)
[MonoDroid]     at md5da1044ae077a2d5a79e87e5c6bedf113.LoginActivity.onCreate(LoginActivity.java:31)
[MonoDroid]     at android.app.Activity.performCreate(Activity.java:5990)
[MonoDroid]     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
[MonoDroid]     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
[MonoDroid]     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
[MonoDroid]     at android.app.ActivityThread.access$800(ActivityThread.java:151)
[MonoDroid]     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
[MonoDroid]     at android.os.Handler.dispatchMessage(Handler.java:102)
[MonoDroid]     at android.os.Looper.loop(Looper.java:135)
[MonoDroid]     at android.app.ActivityThread.main(ActivityThread.java:5254)
[MonoDroid]     at java.lang.reflect.Method.invoke(Native Method)
[MonoDroid]     at java.lang.reflect.Method.invoke(Method.java:372)
[MonoDroid]     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
[MonoDroid]     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
[MonoDroid] Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.appcompat.R$styleable" on path: DexPathList[[zip file "/data/app/org.cancer.fundraising-1/base.apk"],nativeLibraryDirectories=[/data/app/org.cancer.fundraising-1/lib/x86, /vendor/lib, /system/lib]]
[MonoDroid]     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
[MonoDroid]     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
[MonoDroid]     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
[MonoDroid]     ... 18 more
[MonoDroid]     Suppressed: java.lang.ClassNotFoundException: android.support.v7.appcompat.R$styleable
[MonoDroid]         at java.lang.Class.classForName(Native Method)
[MonoDroid]         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
[MonoDroid]         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
[MonoDroid]         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
[MonoDroid]         ... 19 more
[MonoDroid]     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
[Mono] Assembly Ref addref GoogleAnalytics.Core[0xb429abe0] -> System.Net.Http[0xaed233a0]: 3
[Mono] Assembly Ref addref GoogleAnalytics.Core[0xb429abe0] -> System.Core[0xb4387580]: 7
[Mono] Assembly Ref addref System.Net.Http[0xaed233a0] -> System[0xb4387760]: 10
[Mono] Assembly Ref addref System.Net.Http[0xaed233a0] -> System.Core[0xb4387580]: 8
[mono-rt] [ERROR] FATAL UNHANDLED EXCEPTION: Java.Lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/appcompat/R$styleable; ---> Java.Lang.ClassNotFoundException: Didn't find class "android.support.v7.appcompat.R$styleable" on path: DexPathList[[zip file "/data/app/org.cancer.fundraising-1/base.apk"],nativeLibraryDirectories=[/data/app/org.cancer.fundraising-1/lib/x86, /vendor/lib, /system/lib]]
[mono-rt]
[mono-rt]   --- End of managed exception stack trace ---
[mono-rt] java.lang.ClassNotFoundException: Didn't find class "android.support.v7.appcompat.R$styleable" on path: DexPathList[[zip file "/data/app/org.cancer.fundraising-1/base.apk"],nativeLibraryDirectories=[/data/app/org.cancer.fundraising-1/lib/x86, /vendor/lib, /system/lib]]
[mono-rt]   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
[mono-rt]   at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
[mono-rt]   at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
[mono-rt]   at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:118)
[mono-rt]   at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
[mono-rt]   at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59)
[mono-rt]   at md5da1044ae077a2d5a79e87e5c6bedf113.LoginActivity.n_onCreate(Native Method)
[mono-rt]   at md5da1044ae077a2d5a79e87e5c6bedf113.LoginActivity.onCreate(LoginActivity.java:31)
[mono-rt]   at android.app.Activity.performCreate(Activity.java:5990)
[mono-rt]   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
[mono-rt]   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
[mono-rt]   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
[mono-rt]   at android.app.ActivityThread.access$800(ActivityThread.java:151)
[mono-rt]   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
[mono-rt]   at android.os.Handler.dispatchMessage(Handler.java:102)
[mono-rt]   at android.os.Looper.loop(Looper.java:135)
[mono-rt]   at android.app.ActivityThread.main(ActivityThread.java:5254)
[mono-rt]   at java.lang.reflect.Method.invoke(Native Method)
[mono-rt]   at java.lang.reflect.Method.invoke(Method.java:372)
[mono-rt]   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
[mono-rt]   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
[mono-rt]   Suppressed: java.lang.ClassNotFoundException: android.support.v7.appcompat.R$styleable
[mono-rt]       at java.lang.Class.classForName(Native Method)
[mono-rt]       at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
[mono-rt]       at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
[mono-rt]       at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
[mono-rt]       ... 19 more
[mono-rt]   Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
[mono-rt]
[mono-rt]   --- End of inner exception stack trace ---
[mono-rt]   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0xa047bf80 + 0x0002b> in <filename unknown>:0
[mono-rt]   at Android.Runtime.JNIEnv.CallNonvirtualVoidMethod (IntPtr jobject, IntPtr jclass, IntPtr jmethod, Android.Runtime.JValue* parms) <0xa2007008 + 0x000b3> in <filename unknown>:0
[mono-rt]   at Android.App.Activity.OnCreate (Android.OS.Bundle savedInstanceState) <0xa1018918 + 0x0014f> in <filename unknown>:0
[mono-rt]   at ACS.FundRaising.Android.MvxActionBarEventSourceActivity.OnCreate (Android.OS.Bundle bundle) <0xa047b4e0 + 0x00037> in <filename unknown>:0
[mono-rt]   at ACS.FundRaising.Android.LoginActivity.OnCreate (Android.OS.Bundle bundle) <0xa047b278 + 0x0001b> in <filename unknown>:0
[mono-rt]   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_savedInstanceState) <0xa116f9b0 + 0x00057> in <filename unknown>:0
[mono-rt]   at (wrapper dynamic-method) System.Object:dd5e6f9d-f207-497c-b5c3-0a2c9dac76e7 (intptr,intptr,intptr)
[mono-rt]   --- End of managed exception stack trace ---
[mono-rt] java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/appcompat/R$styleable;
[mono-rt]   at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:118)
[mono-rt]   at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
[mono-rt]   at android.support.v7.app.AppCompatActivity.onCreate(AppCompa
</code>
Comment: Have you tried deleting all packages, restore them again. Also delete your local repo for the java files Xamarin download for Appcompat, and clear your obj and bin folders.
Comment: I have tried upgrading to 4.0.0-beta7 in MvvmCross still same problem.
Answer: In my case a solution Clean was necessary to get it working.
Comment: @CyprienAutexier no need to Uninstall the app yourself as Visual Studio does it for you before deploying the application on the emulator or the phone.
Comment: It obviously does not remove all files.
Answer: This issue is resolved by Re-Cloning the repository.  Still I don't know what caused the issue but I ended up wasting lot of time.  I tried things like;

Removing and downloading packages
Deleting Obj/Bin
Deleting appcompat from android SDK install folder and re-downloading it
Using component instead of package

Probably build output generated some garbage resulting in such issue.


Retornar view que está em outro diretório

Question: Adicionei uma pasta dentro de outra pasta na pasta views, desta forma:

Views/Cadastro/Perfil

Dentro da pasta perfil estão os arquivos .cshtml. Porém, quando tento acessar os arquivos .cshtml recebo um erro na aplicação, já tentei esta solução: Como direcionar uma Action para uma view dentro de uma pasta? e não consegui resolver, o AP fala no final, que tenho que criar rota, mas não consigo.
Meu controller está da seguinte forma:
public ActionResult Perfil()
{
    var perfils = db.Perfil.Where(p => p.Nome != "Administrador" && p.IDStatus == 1).ToList();
    return View("Perfil/"+perfils);
}

Recebo o seguinte erro:
Comment: Poste a forma que você está fazendo em seu controller. Qual o erro que apresenta?
Comment: Não tem problema, no início é assim mesmo. Caso tenha algo a acrescentar, você sempre poderá editar a sua própria pergunta. Não utilize o campo de respostas para isso.
Comment: Bem vindo ao [pt.so], faça um [tour], para aprender um pouco mais sobre o funcionamento do site para assim aumentar suas chances de conseguir uma boa resposta.
Answer: Neste caso, você não precisa alterar a rota para exibir sua view, basta retorná-la em sua action, desta forma:
public ActionResult Perfil()
{
    var perfils = db.Perfil.Where(p => p.Nome != "Administrador" && p.IDStatus == 1).ToList();
    return View("Perfil/Perfil",perfils);
}

Neste caso, como você quer apenas retornar a view, mas não alterar a rota, basta retornar a view Perfil que está dentro do da pasta Perfil.
Comment: Randrade desculpe mas acho que não fui claro o suficiente: O Meu controller vai chamar a action Perfil, mas está action está dentro de outra pasta com o nome perfil, desta forma:

Views/Cadastro/Perfil/Perfil.cshtml ou seja Perfil.cshtml é minha action.
Comment: ok posso sim, vou fazer agora


Java Swing combo box selection and link to other combo boxes

Question: Here is the scenario: I have a table in database with 3 columns (id, name, age). I've created 3 swing comboboxes and a button that sends a "select statement" to the database and fills the comboboxes out with addItem(...).
Now i wanna know how to link comboboxes such that when I select a value from lets say, the second combobox that fetches "name", the appropriate "age" value appears in the third combobox.
My ActionEvent for the button:
 jComboBox1.addItem(search.getInt("ID"));
 jComboBox2.addItem(search.getString("NAME"));
 jComboBox3.addItem(search.getString("AGE"));

** search is the ResultSet I acquire!
Thanks in advance.
Answer: You should implement a custom ComboBoxModel for such operations.
You can put the logic of your choices inside setSelectedItem method:
public class YourComboBoxModel implements ComboBoxModel{
    public void setSelectedItem(Object anItem){

    }
    public Object getSelectedItem() {...}
    public Object getElementAt(int index){...}
    public int getSize() {...}
}

and add the desired ComboBoxModel to the relative JComboBox:
YourComboBoxModel model = new YourComboBoxModel();
JComboBox box = new JComboBox();
box.setModel(model);

Comment: +1 for changing models; `DefaultComboBoxModel` may be sufficient. There's a related example [here](http://stackoverflow.com/questions/3191882).
Comment: or http://stackoverflow.com/questions/6261017/how-to-add-different-jcombobox-items-in-a-column-of-a-jtable-in-swing/6261853#6261853, or http://stackoverflow.com/questions/6246005/jcombobox-change-another-jcombobox/6246655#6246655 +1
Comment: Let me try these and get back to ya! After-all still in the process of learning! Tnx


java Affine Transform correct order

Question: I am having trouble figuring out the correct order of transformations to apply on elements in my app. The app has elements which have parent/child relations and each element has a transformation (each element is drawn in local space and then transformed).
What i want to archive is that if i transform the parent all its child should also get transformed (so if you rotate the parent, the child should rotate around the parent).
The code below does just that but the problem is when i rotate the parent and then want to move the child. It moves in the wrong direction (due to its parent transformation ). I've tried changing the sequence of the transformations but no luck (i know i should first translate and then transform but then the child is rotated around its own axis - instead of parents).
The code:
 Element e;
 AffineTransform t = new AffineTransform();
 AffineTransform t3 = new AffineTransform();

 for (i = 0; i < el.size(); i++)
 {
    e = el.get(i);
    t3.setToIdentity();
    t.setToIdentity();
    tmp = e.getParent();
    while(tmp != null)
    {
         t.translate(tmp.getX(), tmp.getY());
         t3.rotate(Math.toRadians(tmp.getAngle()),tmp.getAnchorX(), tmp.getAnchorY());
         tmp = tmp.getParent();
    }

    t.concatenate(t3);
    t.translate(e.getX(), e.getY());

    t.rotate(Math.toRadians(e.getAngle()),e.getAnchorX(), e.getAnchorY());

    e.draw(g2d,t);
}

The problem:
 - given two elements (one child of other)
 - parent is rotate (by 40 degrees)
 - child is then move by 10px
How can i concatenate transformations so that when i move the child it wont move in the rotated direction?
EDIT:
The code that Torious posted (not working yet):
public AffineTransform getTransformTo(Element ancestor) {
    AffineTransform t = (AffineTransform)getAffineTransform().clone();
    Element parent = getParent();
    while (parent != null && parent != ancestor) {
        t.preConcatenate(parent.getAffineTransform());
        parent = parent.getParent();
    }
    return t;
}

public void translateInAncestorSpace(Element ancestor, Point translation) {
    AffineTransform fromAncestor = getTransformTo(ancestor); // to ancestor space
    try
    {
        fromAncestor.invert();
    } catch(Exception e)
    {
       e.printStackTrace();
    }
    translation = (Point)fromAncestor.transform(translation, new Point());

    Transform t1 = new Transform();
    t1.translate(translation.x,translation.y);
    transform(t1);
}

Output of the code:
 Moving by [x=1,y=1] old position [x=22,y=40]
 Moved by [x=-21,y=-39] new position [x=1,y=1]
 Moving by [x=2,y=2] old position [x=1,y=1]
 Moved by [x=1,y=1] new position [x=2,y=2]
 Moving by [x=4,y=3] old position [x=2,y=2]
 Moved by [x=2,y=1] new position [x=4,y=3]

Comment: For better help sooner, post an [SSCCE](http://sscce.org/). BTW - Do you have a question?
Answer: Something like this:
// get composite transform for 'e'
t.setToIdentity();
t.translate(e.getX(), e.getY());
t.rotate(...);

tmp = e.getParent();
while (tmp != null) {

    // get composite transform for parent
    t3.setToIdentity();
    t3.translate(tmp.getX(), tmp.getY());
    t3.rotate(...);
    tmp = tmp.getParent();

    t.preConcatenate(t3); // t3 is applied after t
}

e.draw(g2d, t);

Edit: For moving an element in 'global space' while it's actually a child of another element, I'd suggest transforming the desired move to element space so it can simply be added to its translation:
(untested code)
// Element.getTransformTo: get transform to ancestor or root (null)
public AffineTransform getTransformTo(Element ancestor) {
    AffineTransform t = getCompositeTransform();
    Element parent = getParent();
    while (parent != null && parent != ancestor) {
        t.preConcatenate(parent.getCompositeTransform());
        parent = parent.getParent();
    }
}

// Element.translateInAncestorSpace
// ancestor may be null for root/global space
public void translateInAncestorSpace(Element ancestor, Point translation) {
    AffineTransform fromAncestor = getTransformTo(ancestor); // to ancestor space
    fromAncestor.invert(); // from ancestor space

    // [NEW] re-apply element rotation since translation occurs after rotation
    fromAncestor.rotate(Math.toRadians(angle), anchor.x, anchor.y);

    translation = fromAncestor.deltaTransform(translation, new Point());

    // translation is now in element space; add to existing translation
    element.setX(element.getX() + translation.x);
    element.setY(element.getY() + translation.y);
}

// example usage:
// (this should move the element 10px to the right, regardless
// of parent transforms)
element.translateInAncestorSpace(null, new Point(10, 0));

Also consider implementing an AffineTransform Element.getCompositeTransform() method, which will make your life easier in the end.
Also consider rendering your 'element tree' from the root node to the leaf nodes, so you'd get something like this:
public void render(Element node, AffineTransform transform) {

    AffineTransform nodeTransform = node.getCompositeTransform();
    nodeTransform.preConcatenate(transform);

    node.draw(g2d, nodeTransform);

    for (Element child : node.children())
        render(child, nodeTransform);
}

Comment: I edited my answer. I think this is the 'cleanest' approach to solving the problem. Let me know if it works/fails.
Comment: thank you very much. You can remove the "untested" as it works. The problem with the "element tree" is that i cant render the elements as a tree because elements have to be rendered ordered by z index.
Comment: spoke to soon without properly testing it.. The problem is that when the parent is rotated by 40 degrees and you want to move the child by 10px it will move in the rotated direction.
Comment: That's supposed to happen with the code I posted, since the child is inside the parent's coordinate system. Can I ask why you want to translate independently but rotate dependently?
Comment: elements are moved on mouse events and if you move a child it will move in a undesired way. The rotation must be dependent because elements support keyframe animations (so only movement has to be independent).
Comment: i have implemented the code but something is off. Now even one element cant be moved (its stuck to global position 0,0). Here is a output of translateInAncestorSpace:
Moving by java.awt.Point[x=1,y=1] old position java.awt.Point[x=22,y=40]
Moved by java.awt.Point[x=-21,y=-39] new position java.awt.Point[x=1,y=1]
Moving by java.awt.Point[x=2,y=2] old position java.awt.Point[x=1,y=1]
Moved by java.awt.Point[x=1,y=1] new position java.awt.Point[x=2,y=2]
Comment: Try `translation = fromAncestor.deltaTransform(...)` instead of `translation = fromAncestor.transform(...)`
Comment: the moving is now ok now but if the element is rotated the move is also rotated (it should be parallel to x an y axis).
Answer: Ok, I think I understand what you want now. The code below should (untested) concatenate translations, but not rotations. Each element is affected only by its own rotation.
I've posted this as a new answer since the code's intention is different from the code in my previous answer.
With this code, just set an element's x and y to translate it.
// set e's translation
t.setToIdentity();
t.translate(e.getX(), e.getY());

// add ancestor translations (order is irrelevant)
Element parent = e.getParent();
while (parent != null) {
    t.translate(parent.getX(), parent.getY());
    parent = parent.getParent();
}

// append e's rotation (applied first)
t.rotate(...);

e.draw(g2d, t);

Is this what you mean?
Comment: each element is affected by its own and its parents rotation. Your previous answer was on track. The only problem is when element is being moved because it doesnt move in the x,y direction. For example one element at 10,10 and angle 30, and other element is a child of the first one at 10,10 and angle 30 (his global values are 20,20 and 60). And i want to move the child to the right by 10 px. But if i move the element by 10px to the right it moves 10px rotated by 60 degrees.
Comment: What does your `transform()` method do? Maybe you should just set x/y like I did in `translateInAncestorSpace()` instead of calling `transform()`.
Comment: it just adds dx and dy to the current position. Same as your code.
Comment: the only solution i currently have is to drop the transformation and store only global transformations per element (but then i have to update every child when a parent changes).
Comment: I've added a line marked `[NEW]` in a comment in my original answer. Let me know if it works.
Comment: jup it solved it. Thank you very much you have been really kind and helpful!

java Affine Transform correct order


Why oughtn't listeners try to hear where tone rows start and stop?

Question: David McCleery. p. 27, Liner note to Discover Music of the Twentieth Century.

Between
  1912 and 1923 he [Schoenberg] wrote very few works, dedicating his time instead to developing the
  twelve-tone technique which would provide him with the framework he needed for atonal
  composition. The fruition of all this work can be found in the last of his Five Piano Pieces, Op.
  23 – a Waltz (CD 1, track 2). It is based strictly on a twelve-note row, but the listener should
  not try to hear where the row starts and stops; the serial construction is more a framework
  within which the composer can work than a device to help the listener appreciate the piece.

Is McCleery wrong that listeners "should
not try to hear where the row starts and stops"?

I know that he's discussing Schoenberg in this quote, but I think McCleery's wrong as Gil Shaham and Leonard Bernstein (at 1:08:01 in his 5th of 6 Norton Lectures) expound Berg's Violin Concerto by spotlighting Berg's (perhaps tonal, triadic, unoriginal) tone row. Why would they do so, if listeners oughtn't track tone rows?

In general, what are the cons of following tone rows for listeners?
What are the pros?
Answer: One possibility is the distinction between the composers being discussed. Schoenberg was more free with his use of the twelve-tone method, often repeating or reordering pitches. (He wasn't the only serial composer that did this; I believe it was Boulez that said he used serialism as a starting point and felt comfortable making adjustments later.) As such, sometimes it can be more confusing to try to spot where Schoenberg's row forms begin and end, because he had a tendency to obfuscate the rows a bit.
Contrast Schoenberg's compositional style with Webern's. Webern was surgically precise with his use of the row forms; you're hard pressed to find anything "out of line" (or perhaps "out of row") in his music. And for what it's worth, I think Webern would have argued that you should listen for the row forms. More than that, he believed that you could do it; he famously envisioned a future where the mail carrier would be whistling twelve-tone rows as they walked their route.
As for Berg, he often split the difference between Schoenberg and Webern; he wasn't always as strict as Webern, but he was also not as loose as Schoenberg. This may be why Bernstein and Shaham encourage you to listen to the row forms in the Berg concerto. (Keep in mind too that this particular row form is very easy to identify, depending on whether it starts by step or skip. I'd also hesitate to call that row form "unoriginal"!)
A big pro of listening for row forms is that these forms often delineate the form. Throughout music history, form is typically regarded as the most important emotional element of the piece. Understandably, then, identifying the row forms to determine the form is of prime importance (pardon the pun).
One possible con is the same drawback we encounter whenever we focus too much on one aspect of anything: we run the risk of falling victim to perceptual blindness.
Lastly, with questions like this, there's always the possibility that McCleery is simply wrong about this, no matter who the composer in question is.
Comment: Another typically recondite answer from Richard.  I'd just add that another good reason to not try to hear where the 12 tone row starts and stops is that it's unnatural: we don't hear 12 tone rows as musical units, if we're normal mortals and not music majors or worse, because they are not related to any natural musical structure.  And no, I'm not holding my breath on hearing my post person whistling tone rows.  Greg Bear, in his great sci fi novel _Queen of Angels,_ similarly envisions his main character in the year 2048 humming "pop twelvetone", but I won't hold my breath on that either.


Views, ViewModels, "WindowViewModels" ...what am I missing here?

Question: In a presentation logic layer (PLL), I have so-called "view model" classes that implement /extend interfaces defined in the business logic layer (BLL), like this:
namespace BLL.Abstract.POCO
{
    // also implemented in data access layer (DAL) by data model entities
    public interface ISomeDomainModelEntity
    {
        string Name { get; set; }
        string Description { get; set; }
    }
}

namespace PLL.Abstract.ViewModels
{
    public interface ISomeDomainModelEntityViewModel
                     : ISomeDomainModelEntity, INotifyPropertyChanged
    {
        bool IsSelected { get; set; }
    }
}

namespace PLL.Concrete.ViewModels
{
    public class SomeDomainModelEntityViewModel
                 : ViewModelBase, ISomeDomainModelEntityViewModel
    {
        private string _name;
        private string _description;
        private bool _isSelected;

        public string Name { get { return _name; } set { _name = value; NotifyPropertyChanged(() => Name); } }
        public string Description { get { return _description; } set { _description = value; NotifyPropertyChanged(() => Description); } }
        public bool IsSelected { get { return _isSelected; } set { _isSelected = value; NotifyPropertyChanged(() => IsSelected); } }
    }
}

Note that ViewModelBase is an abstract class which allows for this fancy strongly-typed INotifyPropertyChanged implementation.
The above implementation's IsSelected property is clearly only needed in the presentation layer (visualize a couple dozens of these objects displayed in a list with an ItemTemplate which features a ListBox that binds its IsChecked property to IsSelected), and the presentation logic knows how to use it before returning to the business logic layer.
The problem I'm having, is that I find the name "ViewModel" clashes with this:
namespace PLL.Abstract.ViewModels // hmmm...
{
    public interface ISomeWindowViewModel
    {
        ObservableCollection<ISomeDomainModelEntityViewModel> SomeItems { get; }
    }
}

The implementation of ISomeWindowViewModel is ultimately assigned to the view's DataContext property:
namespace PLL.Concrete.ViewModels
{
    public class SomeWindowViewModel : WindowViewModelBase, ISomeWindowViewModel
    {
        private readonly ObservableCollection<ISomeDomainModelEntityViewModel> _items;

        public SomeWindowViewModel(IView view, ObservableCollection<ISomeDomainModelEntityViewModel> items)
            : base(view)
        {
            _items = items;
        }

        public ObservableCollection<ISomeDomainModelEntityViewModel> SomeItems { get { return _items; } set { _items = value; } }
    }
}

namespace PLL.Abstract
{
    public abstract class WindowViewModelBase : ViewModelBase
    {
        public IView View { get; private set; }

        protected WindowViewModelBase(IView view)
        {
            View = view;
            View.DataContext = this;
        }
    }
}

This is the result of a major refactoring I've started after reading about how DI should be applied to WPF in Mark Seeman's Dependency Injection in .NET (excellent read so far, not finished yet), and while at first it seemed somewhat backwards to inject the View implementation into the ViewModel's, I can appreciate the gained control/simplicity with handling the displaying and closing of the view. Before the refactoring I had a working application with a BLL that was tightly coupled with DAL and PLL; now the BLL has no dependencies whatsoever and that's awesome.
I'm still in the process of reconfiguring the composition root (using Ninject.Extension.Conventions), so at the end of the day I might realize that I have a couple adjustments to make in order to make it all work... and it could hurt, but I'm ready for it!
So the question(s) is/are as follows:

I feel like I have way too many interfaces, but I'm totally green with DI configuration using conventions (well, totally green with DI altogether!); configuring the IoC container by convention seems much easier when types implement interfaces... But is this overkill?
Is the term "ViewModel" overused here? Or rather, is the distinction between "ViewModel" and "WindowViewModel" warranted or I'm missing something? Is it normal that a ViewModel "contains" other ViewModels? If not, is it ok to come up with some "WindowViewModel" name for a ViewModel that's used as a DataContext in a View?
Is there any blatant architectural flaw visible here that will end up turning the code base into a mess? The idea is to implement MVVM with DI as SOLIDly as possible, but I think I have a LOT to learn still.
This question from last year popped up in the "Similar Questions" list as I was typing this post, and is really starting to blur things even further in my mind - the accepted answer and other comments radically contradict what I've been reading lately. Specifically, that a ViewModel class should be injected with some IView implementation - this question/answer+comments is saying the exact opposite, which is what I had in the first place (a View injected with some IViewModel implementation). Looks like both ways are totally acceptable and it's only a matter of personal preference?
Answer:
In my opinion, too many. Architecture should be flexible and you might not keep sticking to one of technique, like IOC, when you smell something. On one hand I did not see the benefit of ISomeDomainModelEntityViewModel, ISomeWindowViewModel and IObservableCollection, there is only one class for each interface, except DI and on the other hand, interface is not essential for DI. I think you might take a look Prism examples to see how they construct ViewModel with DI and when to use interfaces. Usually, if you want to use DI to construct a ViewModel, all dependencies of the ViewModel are services, defined in interface and use IOC to resolve these services. Since these services like have external dependencies so that mocking these interfaces to test is easy. However, most of ViewModel does not have interfaces since they are consumed mainly by View and other ViewModels.
I think ViewModel can contain other ViewModel, such as A main ViewModel contains children for each pages.
Not obvious. Besides interfaces, personally I do not think it is a good way to put IObservableCollection in IOC.
Personally I think injecting IView will break MVVM since ViewModel should not know View. Even an IView, ViewModel have the reference to the View. However in some scenarios if that ViewModel have an IView can make many things much easier, why not? As I said, architecture should be flexible.

Hope it can help.
Comment: Oops, IObservableCollection is a typo - it's really an ObservableCollection, which the view needs for binding.
Comment: About #2: I guess the question rises from #4, since I happen to have VM's that need an IView and others that don't... hence the gut-feeling "need" to make a distinction.


Multilingual best practices on SQL Server, EF and MVC combinations

Question: ASP.NET MVC, resource management is look like enough for application multlingual multiculture support.
But I am wondering practices about data.
User stories;

User set culture as en-US and see all product items in English.
User set culture as fr-FR and see all product items in French.
User set culture as ru-RU and see all product items in Russian.
User doesn't have right change culture settings and application never reach multilingual resources, it will use default language and culture.
Comment: It may help: http://stackoverflow.com/questions/119568/best-practice-to-make-a-multi-language-application-in-c-winforms
Answer: I'm not sure this is exactly what you're asking about, but if you want to have localization in your DB-level, it can be done using VIEWs that rely on CONTEXT_INFO.
This way you always query the same VIEW, but it would return different results based on the CONTEXT_INFO.
You can read more about this here:
Database Localization - Lookup lists - smarter way
Answer: There may be a more elegant way to do this localization in the database, but I just store the different-language data values in tables like this:
<code>            WIDGETS
            widgetid
            widgetname nvarchar (default English)

            WIDGETSLOCAL
            widgetid      foreign key references WIDGETS(widgetid)
            language_code
            widgetname  nvarchar
            unique composite index on (widgetid, language_code)
</code>
And then I either create separate views  (e.g. view_WIDGETS_enus, view_WIDGETS_ruru) or use the language code in the WHERE-clause,  or pass the user's language code to a stored-procedure. Our databases are not properly "localized" in the strict sense of the word; we just have several different translations available based on the primary native languages of our user-base, which happen to be English, Spanish, and French.
For dates, we always use the US-format but with the month abbreviated:  15 MAR 2010  rather than switching between dd/mm/yyyyy and mm/dd/yyyy formats.  Our database does not contain any money columns so we don't encounter decimal or currency formatting issues.


Variance of data from small versus large countries

Question: In considering (for example) homicide rates reported annually for each country, it occurs to me that the U.S., being larger in population, might thereby be expected to have a rate closer to the worldwide mean.
However, I don't know how to evaluate that idea quantitatively. What kind of additional data (if any) and calculations would be required to support that idea (not sure I should call it a hypothesis, because it relates to the model rather than to the world).
Another way of thinking about this: with respect to statistics reported per country, does the U.S. look like a group of smaller countries combined?
Comment: Could you please describe the objective of the regression you are trying to create?
Comment: There may be a case for using weighted least squares regression to address heteroscedasticity in respect of the variances of homicide rates in different countries, but it is difficult to advise without more detail on what you are trying to do. 'Evaluate that idea quantitatively' is rather vague.
Comment: To Jack Ryan: re your inquiry, let me explain. I am considering the implications of mediocre U.S. scores in measures of well-being -- including, (to name a few examples) high school math achievement, life expectancy, number of murders, low birth weight infants and so forth.
Answer: Even small countries are generally large enough that nationwide parameters (such as the underlying homicide rate) can be estimated pretty accurately on a year-by-year basis.  Any observed differences between countries are therefore likely due to genuine differences between the countries rather than statistical noise.  True, the CI for the US homicide rate will be narrower than the corresponding CI for Sweden, but both are likely to be very small.
It's true that the world-wide mean will be more greatly influenced by the rates in the large countries (China and India much more than the US), but I'm not sure what you would do with this.  I guess it might be interesting if, for instance, you found that fluctuations in the global homicide rate were more closely correlated with fluctuations in the US rate than the Chinese rate.  Is that the sort of thing you had in mind?
Comment: Your first paragraph gives me exactly what I wanted to know.


how to display the pic of a user from twitter

Question: I am trying to make an sample web app using php mysql, where if a user enters a twitter username, he can see the profile pic of that particular user.
Which api could help to implement this.
Answer: If you know the username, it's pretty easy to get the profile pic in Twitter: just check the url:
<code>https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger
</code>
... where 'twitterapi' should be replaced by the actual username.
Here's more to read.
Comment: That's reasonable of Twitter to recommend not using the links as img src: they are not the image hosting site, after all. ) I suppose it's best to collect the picture by following the link, save in into some temporary location, then use that location as actual image source.
Comment: hi, one more doubt on ths.. i read a Tutorial in this site, which gets the demo here.. http://www.queness.com/resources/html/jstwitterhashtag/

But Twitter API says not to use as image source.. I want the twitter user profile pic to be shown to the left side of the tweet which is missing in the demo.
Comment: any means how you could do it? again this would only be displaying some 10 posts at a time and forget. So how to create a temporary storage. Is there a way out in MysQL or PHP
Comment: I think i found some answer over here.. http://stackoverflow.com/questions/2069959/temporary-store-image-in-php-only-while-displaying-on-web-page

Any ways Thanks.. for the Answer.


Insert current date into a date column using T-SQL?

Question: I'm trying to insert a date when a user decides to deactivate or activate an UserID. I'm trying to use a SP to trigger that but apparantly this is harder than I thought it would be.
I can do a
SELECT GETDATE()

to get the date but is there a way to insert that information from GETDATE and put it into a column I want?
Answer: Couple of ways. Firstly, if you're adding a row each time a [de]activation occurs, you can set the column default to GETDATE() and not set the value in the insert. Otherwise,
UPDATE TableName SET [ColumnName] = GETDATE() WHERE UserId = @userId

Comment: Yea I can leave it blank. I'll try that.
Answer: To insert a new row into a given table (tblTable) :
INSERT INTO tblTable (DateColumn) VALUES (GETDATE())

To update an existing row :
UPDATE tblTable SET DateColumn = GETDATE()
 WHERE ID = RequiredUpdateID

Note that when INSERTing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL constraint - so you may need to provide values for other columns eg...
 INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())

Answer: UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID

If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE() as the default value for that column, and don't allow NULLs
Answer: If you're looking to store the information in a table, you need to use an INSERT or an UPDATE statement. It sounds like you need an UPDATE statement:
UPDATE  SomeTable
SET     SomeDateField = GETDATE()
WHERE   SomeID = @SomeID

Answer: You could use getdate() in a default as this SO question's accepted answer shows. This way you don't provide the date, you just insert the rest and that date is the default value for the column.
You could also provide it in the values list of your insert and do it manually if you wish.


How does one show that $\prod_{k=1}^{\infty}\left(\prod_{j=1}^{\infty}{(2j)^{2^k}-1\over (2j)^{2^k}+1}\right)^{1/2^k}={2\over \pi}?$

Question: Given this double infinite products

$$\prod_{k=1}^{\infty}\left(\prod_{j=1}^{\infty}{(2j)^{2^k}-1\over (2j)^{2^k}+1}\right)^{1/2^k}={2\over \pi}\tag1$$

How can we prove $(1)$?
An attempt:
Take the log
$$\sum_{k=1}^{\infty}{1\over 2^k}\sum_{j=1}^{\infty}\ln\left({(2j)^{2^k}-1\over (2j)^{2^k}+1}\right)=\log{2\over \pi}\tag2$$
Not sure how to handle $$\sum_{j=1}^{\infty}\ln\left({(2j)^{2^k}-1\over (2j)^{2^k}+1}\right)\tag3$$
Recall $(4)$, maybe it could be of some use for $(3)$
$$\ln{1+x\over 1-x}=\sum_{n=1}^{\infty}{2\over (2n-1)}x^{2n-1}\tag4$$
Comment: Indeed, what happened when you used (4) (for $|x|<1$) in each term of the series in (3)?
Comment: Hint : $${(2j)^{2k}-1\over(2j)^{2k}+1} = 1-{2\over (2j)^{2k}+1}$$
Comment: @Furrane Really? Are you able to follow on your hint?
Answer: $$\sum_{j\geq 1}\log\left(\frac{(2j)^{2^k}-1}{(2j)^{2^k}+1}\right) = \sum_{j\geq 1}\log\left(\frac{1-\frac{1}{(2j)^{2^k}}}{1+\frac{1}{(2j)^{2^k}}}\right)=-\sum_{j\geq 1}\sum_{m\geq 0}\frac{2}{(2m+1)(2j)^{2^k(2m+1)}}\tag{1}$$
by multiplying both sides of $(1)$ by $\frac{1}{2^k}$ and summing over $k\geq 1$ we are left with
$$ -\sum_{j\geq 1}\sum_{m\geq 0}\sum_{k\geq 1}\frac{2}{2^k(2m+1)(2j)^{2^k(2m+1)}}=-\sum_{j\geq 1}\sum_{h\geq 1}\frac{2}{2h(2j)^{2h}}=\sum_{j\geq 1}\log\left(1-\frac{1}{4j^2}\right)\tag{2}$$
and the claim follows from Wallis product.
Comment: Nice catch! (the penultimate equality) (+1)
Comment: Jack back at it again with the witchcraft


Error while trying to copy Worksheet

Question: I am having the error "Copy Method of Worksheeet class failed" on this line:
.Sheets("Blank Forecast Sheet").Copy After:=.Sheets("Button Sheet")

I've looked around and couldn't find any solution. This code is ,as can be seen, supposed to add new sheets that I will rename, once, I get this problem solved.
Sub addnewsheet()

Dim wbook As Workbook
Set wbook = Application.ActiveWorkbook

Dim newsheet As Worksheet
Dim datasheet As Worksheet

Dim m As String
Dim y As Integer

m = Format(Date, "mmmm")
y = Format(Date, "yyyy")

With wbook
.Sheets("Blank Forecast Sheet").Copy After:=.Sheets("Button Sheet")
End With

End Sub

Comment: Have you verified your sheet names?  Your code works for me.
Comment: @BrianMStafford what do you mean by verified? I did check if I had any misspellings, extra spaces, or any other errors in the names of the sheets
Answer: Use ThisWorkbook instead of wbook and .Worksheets instead of .Sheets:
Sub addnewsheet()

Dim newsheet As Worksheet
Dim datasheet As Worksheet

Dim m As String
Dim y As Integer

m = Format(Date, "mmmm")
y = Format(Date, "yyyy")

With ThisWorkbook
    .Worksheets("Blank Forecast Sheet").Copy After:=.Worksheets("Button Sheet")
End With

End Sub

Comment: Please could you state the solution or rather the origine of your problem in a closing statement ? As far as we know your code, despite some imperfections, was working all along.
Comment: Glad to help. Which of the two was it exactly? And may you mark the question as answered so other people can see that there is a solution :)
Comment: Changing the names to `ThisWorkbook` and `.Worksheet`, both helped, though I did not check which specifically worked. Thank You

Error while trying to copy Worksheet


Find the acute angle of intersection of the curves $y=\cos x$ and $y=e^{-x}$ at the point $(0,1)$.

Question:
Find the acute angle of intersection of the curves $y=\cos x$ and $y=e^{-x}$ at the point $(0,1)$.

My method:
$y=\cos(x)$   $(0,1)$
$1=\cos(0)$
$=0$
$\frac{dy}{dx}=-\sin(x)$
$=-\sin(0)$
$=0$
I did the above step exactly from the example given in the text book, but I can't get the answer.
The answer is $45^{\circ}$
Help me out by step by step solution. thanks
Comment: $\sin 0$ is not 1!
Answer: $$f(x)=\cos x\Longrightarrow f'(x)=-\sin x\Longrightarrow f'(0)=0=:m_1$$
$$g(x)=e^{-x}\Longrightarrow g'(x)=-e^{-x}\Longrightarrow g'(0)=-1=:m_2$$
So you have that the functions' tangent lines at $\,(0,1)\,$ have slopes $\,0\,$ (this means the tangent line of $\,f\,$ at this point is horizontal)  and $\,-1\,$ , so what's the acute angle between two lines with these slopes?
Yup, it is $\,45^\circ\,$ , as you can readily check. Of course, you can use the formula
$$\tan\alpha = \arctan\left|\frac{m_1-m_2}{1+m_1m_2}\right|=\arctan\frac{1}{1}=\frac{\pi}{4}\text{radians}=45^\circ$$with $\,\alpha\,=$ the angle between the curves.
Comment: why is $45^{\circ}$, it is because $tan(1)=45^{\circ}$? thx
Comment: Yes, of course. Rememer that $$\sin 45^\circ=\cos 45^\circ=\frac{\sqrt 2}{2}\Longrightarrow \tan 45^\circ=1$$
Comment: sorry, how come $\frac{\pi}{4}$ ? thx
Comment: because If i have $-2$ how about that?
Comment: $\,\pi/4\,$ is the measure of an angle of $\,45^\circ\,$ in radians. If you haven't studied yet this forget it. About your question "if I have -2 how about that?" I'm not sure I understand, but you can always evaluate $\,\arctan -2\,$...
Answer: $\frac{dy}{dx}$ at $P$, where is the slope of the tangent to the curve in concern, at $P$.
For $y=\cos x$ you were almost there. $\sin 0$ is correct, but it's equal to 0.
For the other one, however, $\frac{dy}{dx}=-e^{-x}$ and that's $-e^0=-1$ so take tan inverse of the answers ($0$ and $-1$) and take the difference. i.e., $0^o$ and $-45^o$. It gives you the answer!


tensorflow rnn_decoder perform softmax on each decoder_output

Question: I tried to write my own estimator model_fn() for a GCP ML Engine package. I decoded a sequence of outputs using embedding_rnn_decoder as shown below:
outputs, state = tf.contrib.legacy_seq2seq.embedding_rnn_decoder(
    decoder_inputs = decoder_inputs,
    initial_state = curr_layer,
    cell = tf.contrib.rnn.GRUCell(hidden_units),
    num_symbols = n_classes,
    embedding_size = embedding_dims,
    feed_previous = False)

I know that outputs is "A list of the same length as decoder_inputs of 2D Tensors" but I am wondering how I can use this list to calculate the loss function for the entire sequence?
I know that if I grab outputs[0] (ie. grab only the first sequence output) then I could loss by following:
logits = tf.layers.dense(
    outputs[0],
    n_classes)
loss = tf.reduce_mean(
    tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=labels)

Is it appropriate to generate a loss value for each out the items in output and then pass these all to tf.reduce_mean? This feels inefficient, especially for long sequences -- are there any other ways to calculate the softmax at each step of the sequence that would be more efficient?
Comment: Is this information useful? https://www.tensorflow.org/tutorials/seq2seq#sampled_softmax_and_output_projection
Comment: No, that does not help. My issue is not solved by sampled softmax. My issue is that I need to perform multiple iterations of softmax (on each output of the RNN). I would need to calculate the loss (or sampled softmax loss) at each step in the sequence and that is where I am not sure how to do this properly.
Answer: I think you're looking for sequence_loss (currently in contrib/ a type of incubation).
Answer: It looks like the solution to my problem is to use sequence_loss_by_example
Comment: That is in a package called "legacy". I've added a link to the non-legacy version, but note that it, too, is in contrib/ (a type of incubation).
Comment: I was using the "legacy" package to generate my outputs, so the legacy package seems like hte more appropriate metric to rely on for this question
Comment: Staying within the same package is probably a good idea. Consider moving off of legacy at some point. I suspect they don't update it with bug fixes or performance enhancements.


Translations string email not work

Question: in D8 (multilanguage site, with two languages) i wanna send email for registration, etc by user preference of language of user (People -> Edit people -> Language Settings)
I've enabled all modules for translations and translations are saved correctly (see the attachment).
I followed this guide: https://www.valuebound.com/resources/blog/how-to-send-mail-programmatically-drupal-8
but not work for me.
The language code passed for the email is correct but the email is always send in default language (in my case, english).
Answer: Be sure that the string you sent by mail is already translated in the target language. Otherwise it will not work. You can check it here http://youwebsite.com/admin/config/regional/translate
Comment: Hi Stephane, translation for email is at this url http://yourwebsite.com/language-default-code/admin/config/people/accounts/translate/language-code-for-translations/edit (in my case, language-default-code = en and language-code-for-translations = it)
Answer: For solve this problem, in hook_mail insert this:
<code>    $token = \Drupal::service('token');
    $language_manager = \Drupal::languageManager();
    $language = $language_manager->getLanguage($user->getPreferredLangcode());
    $original_language = $language_manager->getConfigOverrideLanguage();
    $language_manager->setConfigOverrideLanguage($language);
    $mail_config = \Drupal::config('user.mail');

    $subject = $token->replace($mail_config->get($key . '.subject'), [
        'user' => $user
    ]);

    $body = $token->replace($mail_config->get($key . '.body'), [
        'user' => $user
    ]);

    $language_manager->setConfigOverrideLanguage($original_language);
</code>

Translations string email not work


Imagem ocupar toda coluna

Question: Tenho a seguinte estrutra html:

Ultimas Notícias

                            Lorem ipsum dolor sit amet

                            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor ipsum minima minus
                                modi nobis quisquam tempora temporibus? Ad aspernatur dolorum maxime nesciunt omnis
                                reprehenderit suscipit.

Resultando em:

Quero fazer com que a imagem ocupe todo espaço da coluna, que seria a parte preta escura (porem a parte preta escura deve alinhar com o Ultimas noticias e não sair para fora do card)
Comment: Fala Igor editei a resposta com a imagem centralizando no Pai
Answer: Na realidade o col-3 do bootstrap poe essa margem.
Neste caso você teria que remover ou criar uma classe para tirar (forçar) a remoção do margin (ou padding).
Use o inspetor do seu navegador para saber qual a margem ou padding que está no elemento com col-3.
Ou use alguma classe nativa do bootstrap para remover. Talvez já tenha algo pronto que zere a propriedade em questão.
Comment: consegui remover a borda, a questão é que se eu colcoar uma imagem maior que o tamanho ele ultrapassa, quero que ele fique dentro
Answer: Jovem vc pode usar overflow:hidden na div assim se a imagem for maior que o Pai ela vai "cortar" e não ficar interferindo nos demais elementos.
Veja o Exemplo. Aproveitei e retirei o padding default que o Bootstrap coloca nas divs
OBS1: Repare que eu coloquei na imagem os tamanho de height: 100% e width: 120% para vc ver que mesmo sendo maior ela não fica para fora da div
OBS2: Para centralizar a imagem entre transform:translate() para centralizar a imagem dentro da div

.clip {
    overflow: hidden;
    padding: 0;
    position: relative;
}
.clip img {
    height: 120%;
    width: 120% !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous" />

Ultimas Notícias

                        Lorem ipsum dolor sit amet

                        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor ipsum minima minus
                            modi nobis quisquam tempora temporibus? Ad aspernatur dolorum maxime nesciunt omnis
                            reprehenderit suscipit.

Se precisar coloque regras de resposividade dentro dos @media
Comment: ocultei como eu centralizo ela ?
Answer: Acredito que você consiga resolver o seu problema através da utilização da classe card-img presente no Bootstrap, e adicionando em seu css o seguinte código:
.card-img {
  width: 100%;
  height: auto;
}

É interessante ler a documentação do Bootstrap 4 sobre Cards também. Manda um feedback se funcionou ou não, e podemos olhar outras soluções. Sugiro postar o CSS do seu código também para que possamos ver o que foi feito.
Answer: Eu sugeria usar a imagem como background, assim ela iria ocupar toda a div e não perderia o aspect ratio (proporção), se ajustando automaticamente à dimensão da div e adicionar o estilo inline direto na tag.
Basta criar e adicionar uma classe na div:

.imagem{
   background-size: cover !important;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Ultimas Notícias

                         Lorem ipsum dolor sit amet

                         Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor ipsum minima minus
                             modi nobis quisquam tempora temporibus? Ad aspernatur dolorum maxime nesciunt omnis
                             reprehenderit suscipit.

Comment: mas irei colocar as imagens dinamicamente com php, é possivel alterar ?
Comment: Vou editar a resposta...
Comment: Pronto. Você pode colocar o backgound inline direto na div.
Comment: Essa opção realmente ficou melhor, a imagem se encaixa dentro da div. obrigado

Imagem ocupar toda coluna


java.lang.AssertionError when executing unit test when using my own model as parameter

Question: I got a AssertionError when I execute the unit test. response.getBody() is null.
Here is unit test method;
public void when_CustomerNumNotNull_Expect_TspResult() {
   /*
     some code
   */

    TspResultDto tspResultDto = new TspResultDto();

    tspResultDto.setTspResult("blabla");

    Mockito.doReturn(tspResultDto).when(creditService)
        .getTspResult(tspInputDto);

    ResponseEntity<TspResponse> response = creditController
        .getTspResult(TspRequest);

    Assert.assertNotNull(response.getBody()); // error occured this line because body null.
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
    //Assert.assertEquals(true, response.getBody().isHrResult());
  }

    }

TspInputDto and TspRequest are my model Class.
But I don't get an error when I run it with a single parameter like below without needing the model class.
Mockito.doReturn(newCreditApplicationDto).when(creditService)
        .getNewCreditApplicationNo(customerNum);

    ResponseEntity<NewCreditApplicationResponse> response = creditController
        .getNewCreditApplicationNo(customerNum);

    Assert.assertNotNull(response.getBody());
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

Here is controller;
public ResponseEntity<TspResponse> getTspResult(
      TspRequest tspRequest) {

    TspInputDto tspInputDto = creditDemandRestMapper
        .toTspInputDto(tspRequest);

    TspResultDto tspResultDto = creditService
        .getTspResult(tspInputDto);

    TspResponse tspResponse = creditDemandRestMapper
        .toTspResponse(tspResultDto);

    return new ResponseEntity<>(tspResponse, HttpStatus.OK);

  }

Here is service;
public TspResultDto getTspResult(
      TspInputDto tspInputDto) {

    TspResultDto tspResultDto = new TspResultDto();

    /*
       Some code here...
    */
    return tspResultDto;
  }

Where am I doing wrong?
Comment: Question is little unclear, please provide more details regarding CreditController and CreditService. Also in creditController, you are passing TspRequest.
Comment: Service and Controller  added to be more clear.
Answer: In this line:
Mockito.doReturn(tspResultDto).when(creditService)
        .getTspResult(tspInputDto);

you set the mock to return your tspResultDto object if the argument equals() to tspInputDto, meaning it should be an equal object (in terms of equals() comparison). Probably your TspInputDto class doesn't have equals method defined properly.
Anyways, I'd propose to rewrite this line of code using argThat matcher:
Mockito.doReturn(tspResultDto).when(creditService)
        .getTspResult(ArgumentMatchers.argThat(tspInputDto ->
            // condition for provided tspInputDto
        ));

Comment: If it has equals, correct me if am wrong, you would still need to not have a plain object, but rather want to use ArgumentMatchers#eq in mocked method  argument
Comment: I believe Mockito is smart enough to assume `eq()` if only one argument is present. It's when you have other arguments with different matchers, then Mockito would explicitly complain, and you'd need to specify the `eq()` matcher explicitly.
Answer: Have you mocked the creditController? If you haven't then it will not give you response mock object.


View filtered by a Date field's value being in "last month" shows July content on July 31

Question: A View is filtered by a Date field's value.  The Date field's month must be last month in order to match the filter.

On every day except July 31 it would return results from last month.  It should have returned results matching June.  We have tried "-1 month" but that didn't work either.
Why on July 31 does it jump ahead a month?
Comment: May be problem in date.timezone settings in your php.ini
Answer: Try to use 'last day of last month' or 'first day of last month'.
Comment: First day of last month did it!
Answer: You can do this by adding "-1 months" relative value. you can get any month records just need to use + - no. of month to get previous or next months data.


Does $\cos(n^2)/n^2+5$ diverge or converge?

Question: In my opinion it converges by comparison test... but I am not sure. Also I was trying ratio test where I have got $\cos (1)=1$ and that's why it is converge
Comment: Are you talking about a series or a sequence?
Comment: Whats your interval of interest?
Answer: Yes it converges since its absolute value is bounded by ${1\over{n^2+5}}$ which converges towards zero, so it converges towards zero.
Comment: yes, since the serie $\sum{1\over{n^2+5}}$ converges.
Comment: Does this work both for series and sequences?
Comment: Yes but i was thinking what if it was a sequence...?
Comment: it converges towards zero.
Comment: Yup..that is the thing!


Find min and maxima

Question: Find local min and maxima of $ \sin(x^3)$ on the interval $]-2,2[$.
I take the derivative and get:
$$3x^2 \cdot \cos (x^3)$$
I set this equal to zero and get $$x^3 = \cos^{-1}(0)$$
$$ \Rightarrow x^3 = \frac{\pi}{2}+k \cdot \pi$$
I'm not sure what the easiest way to proceed from here would be? Taking the third root confuses me more than just keeping it on this format..I think.
Answer: Setting the derivative equal to zero gives you $$3x^2\cdot\cos(x^3)=0$$
and this is zero only when $x=0$ or $\cos(x^3)=0$.
$x=0$ can't be a local minimum, because $\sin(x^3)$ is an odd function, so it remains to solve $\cos(x^3)=0$ on $]\!-\!2,2[$.
Note that $\cos^{-1} t$ has a specific meaning, it's the inverse of $\cos t$ restricted to $[0,\pi]$. So just say that $\cos t=0$ for $\displaystyle t=\frac\pi2+k\pi$, where $k\in\mathbb Z$ and you want to solve
$$x^3=\frac\pi2+k\pi$$
on $]\!-\!2,2[$. But $x^3$ is one-to-one and transforms that interval into $]\!-\!8,8[$. Can you find all values of $k$ such that $\displaystyle\frac\pi2+k\pi\in\ ]\!-\!8,8[$ ?
Comment: Can you detail better how "$x^3$ transforms the interval" and what does it mean exactly that $sin$ is an odd function? I'm seeing it has something to do with distance from x being the same?
Comment: @Paze You only really need that $x^3$ is increasing, so $-20$ on $(0,\pi)$ implies $\sin(x)<0$ on $(-\pi,0)$ and there clearly can't be a minimum.
Answer: There is no need to compute any derivative: the expression is maximum when
$$
x^3 = \frac\pi 2 + n\pi, n\in\Bbb Z.
$$
Comment: nice and simple
Answer: Because it is $ \sin$  of something ($ \sin(X)$) the minimum is always -1 and the maximum is +1.

As you can see in this interval it has exactly 3 minimums and 3 maximums if the interval is closed and 2 if the interval is open like in your case.
Comment: We are working on the open interval so only 2 minimums and 2 maximums.
Comment: yes, right. I edit my post.

Find min and maxima


Simplification of $ \sqrt{(1-x^2)}$ to $(1-\frac{x^2}{2})$

Question: While following a proof from an electrical engineering book (Design of Analog CMOS Integrated Circuits, second edition from Behzad Razavi ), I came across a simplification which I found curious. In equations 14.18 to 14.19 they state that the following holds for small values of $x$:
$$
\sqrt{1-x^2} \approx \left(1-\frac{x^2}{2}\right)
$$
I can see that this appears to be the case after simulating this in matlab but it seems unintuitive to me, and I was wondering if anyone here knows the kind of mathematical terms I can use to find some kind of proof for this (or the proof itself).
Comment: It's Taylor series of first order - $\sqrt{1-x}=1-x+\text{O}(x^2)$ or linear approximation.
Answer: Term to look for: linear approximation
In general, the best linear approximation for a differentiable function near a point $c$ is
$$
f(x) \approx f(c) + f'(c)\;(x-c)
$$
This is essentially the definition of the derivative.  And you should find this in your calculus book soon after the definition of derivative.
Now if $f(x) = \sqrt{1-x}$ and $c=0$, we get $f(0)=1$ and $f'(0)=-\frac{1}{2}$.  So
$$
\sqrt{1-x} \approx 1 - \frac{x}{2}
$$
To get your case, substitute $x^2$ for $x$.
Comment: I think you could go a bit further and show that $(1+x)^r \approx 1+rx$.
Answer: Every smooth function can be locally approximated by its tangent (as a consequence of Taylor's theorem).
$$\sqrt{1-t}\approx 1-\frac t2.$$
Hence for small $x$,
$$\sqrt{1-x^2}\approx 1-\frac{x^2}2.$$

The next approximation order is parabolic, corresponding to the "osculatrix parabola" (i.e. same tangent and same curvature)
$$\sqrt{1-t}\approx 1-\frac t2-\frac{t^2}8,$$
and
$$\sqrt{1-x^2}\approx 1-\frac{x^2}2-\frac{x^4}8,$$
Answer: Use the Taylor series expansion  at $x=0$ to get $\sqrt{1-x^2}\approx1-\frac{x^2}2+o(x^4)$.


Projective plane homeomorphic to a cone

Question: I'm studyig algebraic topology and I am having several issues when comes to work out the exercises, in this case, the problem is from Bredon's Topology and Geometry. The statement of the exercise is: Show that the projective plane $\mathbb R\mathbb P^2$ is homeomorphic to the mapping cone of the map $z \rightarrow z^2$ of the unit circle in the complex number to itself.
So if I define $f:S^1\rightarrow S^1$ with $f(z)=z^2$, I know that the cone is $M_f/(S^1\times\{1\})$, where $M_f=S^1\times [0,1]\sqcup_{f_0}S^1$, $M_f$ is the cilinder, and $\sqcup_{f_0}$ means the equivalence relation $f(z)\sim (z,0)$ in the disjoint union.
So in this particular example I see that the map $f$ twist the upper circle when making the cilender, and complete two turns over the circle (for example I saw what happens to the points $(1,0)\sim 1$, $(-1,0)\sim 1$, $(i,0)\sim -1$, and $(-i,0)\sim -1$).
After this deformation (the twist part), to get the cone I just glue the top part (where I kept the points as they were) all together into a single point. So what I get is this weird space, and I can't even imagine how to find an homeomorphism from this to $\mathbb R\mathbb P^2$.
Any tips or how to look for this homeomorphism?
Thanks in advance.
Comment: What's your definition of $\mathbb{R}P^2$?  (It's perfectly fine to define it as this mapping cone.)
Comment: Ok, I didnt know this definition, but I use the most usual, as $\mathbb R\setminus \{0\}/\sim$ where $x\sim y$ if there is a $\lambda \in \mathbb R\setminus \{0\}$ such that $x=\lambda y$. I also have proved the same relation o the sphere $S^2$, and the relation of antipodals of the boundary of $D^2$.
Answer: OK, here's how you can construct the map.  Since you've already shown that $\mathbb{R}P^2 \cong D^2/{\sim}$ where the antipodal points on the boundary are identified, I will produce a map $$C_f = (S^1 \times [0,1] \sqcup_{f_0} S^1)/(S^1 \times \{1\}) \to D^2/{\sim}.$$
First, define a map $S^1 \times [0,1] \to D^2$ by $$(\theta, r) \mapsto (1-r)e^{i\theta}.$$  Composition with the quotient map $D^2 \to D^2/{\sim}$ gives a map $S^1 \times [0,1] \to D^2/{\sim}$.
Second, define a map $S^1 \to D^2/{\sim}$ by $\theta \mapsto e^{i\theta/2}$.  Ordinarily, this would not be a well-defined function from the circle to the disk $D^2$.  Why is it OK in this case?
Now I can glue these two functions together to get a function $$M_f = S^1 \times [0,1] \sqcup_{f_0} S^1 \to D^2/{\sim}.$$  You should check that the points identified by $f_0$ are sent to the same point in the target, so that this map is indeed well-defined.
Next, observe that the points in $S^1 \times \{1\}$ are collapsed to a point.  So the map above factors through $$M_f/(S^1 \times \{1\}) = C_f \to D^2/{\sim}.$$  This is your desired map.
A quick way to show that this is a homeomorphism is to recall that a continuous bijection from a compact space to a Hausdorff space is automatically a homeomorphism.  So you just need to just the map just constructed is a bijection.  It's clear that this map is surjective, and checking injectivity requires a bit more work which you should really work out yourself, because it explains some of the possibly opaque choices I've made along the way.
So there are two ways you should do after reading this answer.  First, do verify that the map is well-defined (I've pointed out the places that need checking) and show the last bit about the injectivity.  Second, try to visualize what is happening geometrically -- this is valuable intuition that may help you later on -- and see whether you could have come up with this answer yourself now that you know what is happening geometrically.  Write back if you want more clarification!
Answer: The projective plane can be thought of as the northern hemisphere with opposite points of the equator identified.  The northern hemisphere is a disk and the degree 2 map on its boundary precisely achieves the identification of "opposite" points, so you get your mapping cone almost for free.

Projective plane homeomorphic to a cone


Spring-data-redis: cacheManager configuration issue

Question: I am using redis as my spring cache implementation. And the official doc says we should configure the cache manager like this:

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
        c:template-ref="redisTemplate">

And it works fine when version of jedis = 2.0.0 and version of spring-data-redis = 1.0.2.RELEASE.
But in more recent versions (e.g. jedis = 2.5.2 and spring-data-redis = 1.3.4.RELEASE), the config above is not working. Instead, it throws the an exception, saying "loadCaches must not return an empty Collection".
Then I referred to it and googled it again, and now the configuration file is something like this:

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
        c:template-ref="redisTemplate">
    <property name="cacheNames">
        <map>
            <bean id="someid" class="someclass" p:name="somename"/>
        </map>
    </property>
</bean>

Now it doesn't complain about empty collection, but something else about initialization.
So there are another 2 questions here:

Inside the cacheNames property, I see others are using "list", "set" and "map". What are the differences?
How to configure the bean inside?

I have been struggling with this bean setup for a couple of days.. Could you please help me on them? Thanks in advance
Answer: As a hint, please see the org.springframework.cache.annotation.EnableCaching annotation.
Inside it talks about the CacheManager interface and how it works.
As a quick 'get you going', you need to specify the names of the caches that you will want to be using (such as when you use @CacheConfig(cacheNames='...') or @Cacheable(value = '...'). The idea is that you are creating logical groupings of related 'things' to be cached, ie: Books, Cars, Loans, etc.
In a BookService, you would use something like @CacheConfig(cacheNames='Books').
Hope that helps!
Answer: I have faced the similar issue on using Jedis with spring-data-redis. One of the finding which I have is, spring-data-redis is very specific about Jedis version. For my case, Spring-data-redis 1.5.0.RELEASE is compatible with Jedis 2.6.2.
For your case, as refer to the link below, look for compile dependencies section, you will find out 1.3.4.RELEASE is compatible with Jedis 2.4.1. I believe your problem will be solve once you change your POM file Jedis version.
http://mvnrepository.com/artifact/org.springframework.data/spring-data-redis/1.3.4.RELEASE


Jena/Sparql/Arq: injecting some statements in the model during the query

Question: I have build a small RDF model: it only contains  a few triples describing some items on the human genome.
I want to retain only those items overlapping some genomic segments (say a "gene"), stored in another relational database. This database of genes is far too big to be inserted in my inital RDF model.
Is there any way to extend ARQ to inject some new Statements (the RDF statements  describing the only genes overlapping the items) in my model during the query ?
input:
uri:object1  my:hasChromosome "chr1" .
uri:object1  my:hasStartPosition "1235689887" .
uri:object1  my:hasEndPosition "2897979879" .
uri:object1  dc:title "my variation" .

output:
uri:object1  my:hasChromosome "chr1" .
uri:object1  my:hasStartPosition "1235689887" .
uri:object1  my:hasEndPosition "2897979879" .
uri:object1  dc:title "my variation" .
uri:gene1  dc:title "GeneName" .

I've read about http://jena.sourceforge.net/ARQ/arq-query-eval.html but I'm lost: which mechanism of extension should I choose ? Property ?  Is there any more complete example on web ?
Thanks,
Comment: Also, you're looking at the old Jena site. Jena is now an Apache project: http://jena.apache.org/documentation/
Comment: Try SPARQL Update (http://www.w3.org/TR/sparql11-update/) instead of ARQ.
Answer: Details are a bit thin here. Start simple, using a custom function. That will let you do external lookups in FILTERs or, using BIND, retrieve values.
For updating you might want to consider SPARQL Update.
Finally, you said

I want to retain only those items overlapping some genomic segments (say a "gene"), stored in another relational database.

So perhaps something like:
PREFIX my: <...>
PREFIX f:  <java:com.example.DBFunctions.>

DELETE { ?missing ?p ?o } # Purge the non-overlapping objects
WHERE {
    ?missing my:hasChromosome ?chr ;
             my:hasStartPosition ?start ;
             my:hasEndPosition ?end .
    FILTER (!f:overlaps(?chr, ?start, ?end)) # true if not overlapping
}

Ok, I'm guessing here but I hope that helps a little.
Comment: I know about creating a custom function (http://plindenbaum.blogspot.fr/2008/11/taxonomy-and-semantic-web-writing.html)  but that is not what I need. As I said, I want to inject some new statements that are not part of the initial RDF model. the data for "gene"  would be stored elsewhere, not in a RDF datastore.
Comment: Ah, I think I've completely misunderstood. When you say "inject some new Statements" you mean something "make it appear that the queried model is rdf model + stuff in relation db"?
Answer: You have two datastores. One a small dataset in a Jena in memory Model, and a large set of gene related data in a relational database. You want to write a sparql query as if the large set of data is local without actually importing it. (The actual data transformation you want to do is a bit vague.)
In SPARQL 1.1 you can do this using the SERVICE keyword between sparql endpoints. To be able to use your relational database of gene data as a SPARQL endpoint you need a SPARQL to SQL translator such as D2RQ or convert the data to RDF and load it into a general purpose SPARQL capable triple-store.
Once the gene data is available in a SPARQL endpoint.
PREFIX my: <...>
PREFIX f:  <java:com.example.DBFunctions.>

INSERT { ?missing a my:Gene } # mark a region as a gene
WHERE {
    ?missing my:hasChromosome ?chr ;
         my:hasStartPosition ?start ;
         my:hasEndPosition ?end .
    SERVICE<http://localhost:????/gene_data/sparql>{
       ?gene a my:Gene .
         my:hasStartPosition ?gStart ;
         my:hasEndPosition ?gEnd .
       #Detect overlap.
       FILTER( !(?start > ?gEnd || ?end < ?gStart) ) .
    }
}

The other option is to do the filter as @user205512 shows by using a custom function. Where the filter java code uses JDBC to connect to the relational database.


Which string instruments/playing techniques were used for Nashville Sound country music?

Question: I've been delving into the history of a particular style of country music called "Nashville Sound" recently, which involved a lot of string sections in songs.  Some websites describe them as being "Lush strings" or "smooth strings", but never actually go into detail on which instruments were used.  Does anyone have any ideas as to which strings were actually used for these songs?  Maybe they're just violins played in a specific style I don't know about, so if that is the case can anyone point me in the right direction?  Thanks!
Here are some examples:
Answer: I don't have much knowledge of country music history but since you have no answers and this type of string writing transcends genres I'll tell you a bit about the strings on these recordings. Both songs are very different in the way they use the strings.
"Welcome to my World" contains a string orchestra of first and second violins, violas and cellos. There isn't a standard number of players used for string recordings, it is up to a combination of the arranger/orchestrator, producer, studio size and budget. Usually a recording string section will be smaller than one in a symphony orchestra but the proportions of players are similar. A typical set up may be 12 or 16 violins split between first and seconds, 4 or 6 violas and 4 or 6 cellos. There could be many more or less players based on the factors I mentioned earlier. Basses are sometimes used but not nearly as much as the others and I don't hear any here. If you listen with headphones you will clearly hear the violins are all panned towards the center and the lower strings more to the right. It is not hard to pick out the low and high string sections throughout the song. At the very end of the song you can hear the high strings play a line and hold their note then the low strings play a descending line to finish the song.
On "I'm Sorry" there is only a single section of violins. If I had to guess I would say it is about 6 to 8 players. The string arrangement is much simpler, the strings only play high unison lines, usually as a call and response to either the vocal or the chorus. There are no lush chordal passages like on the first recording. In this case the string section is treated more like a single instrument playing melodic accompanying lines.


Order php/mysql results based on google api calculated distance

Question: It's my first question here, and english is not my main language, so... Sorry if i make any grammar mistake!
I have a very simple php script that does a echo of a
 of addresses from the Mysql database.
It's a database made with data from another software, so i don't have the Lat/Lon stored on it.
I can determine my distance from the address that i clicked with the Google API getting my current location, and using the google.maps.Geocode to convert the address into coordinates, then calculating the distance between us using google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(lat,lon), new google.maps.LatLng(lat2,lon2), receiving a result in meters.
But how can i sort the
 based on distance? Is it possible with php + js?
I know this is probably something simple to do, but i'm just a beginer with web developing, and i couldn't figure this out yet. =/
Comment: Geocode your locations as you add them to database and do [Geo Distance searches](https://www.scribd.com/presentation/2569355/Geo-Distance-Search-with-MySQL)
Comment: What do you mean by sort here? do you mean to sort the UL asc and desc by distance?
Comment: @AbidNawaz Exactly
Comment: can you please post the calculated distances format ?
Comment: @AbidNawaz The Api give's a result in Meters like '658.7599605058606'
Comment: Perhaps this would be a good time to read [What topics can I ask about](http://stackoverflow.com/help/on-topic) and [How to ask a good question](http://stackoverflow.com/help/how-to-ask) and [The perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). SO is **not a free coding or tutorial service**! You have to show that you've put some efford into solving your own problem. And at least post the code that you have. We can't possibly answer your question since we have no idea if or how it'll fit your situation.
Comment: @icecub Really? Really? Do i really need to put a script that just do a Select and displays the result as a list? All the API that i've used to calculate the coordinates and results are in the question, If i'm here asking something, its' because i'm trying to do this for days and could not figure out how. I'm not asking for a free coding or tutorial service, i'm just asking a question...
Comment: Relax m8. I'm not trying to be an ass here. There's nothing wrong with asking a question. There is something wrong with not showing us what you've already tried yourself. If you've been on it for days, like you say, I'm pretty sure you've tried several codes that didn't produce the result you were expecting. Show those to us! We can see where it went wrong and tell you how to fix it. Hover your mouse over the downvote button on your question. What does it say? Then tell me, where is the research efford in your question? I'm giving you those links so you can improve on your next questions.
Answer: This way you can sort the UL list of distances.

function sortUnorderedList(ul, sortDescending) {
  if (typeof ul == "string")
    ul = document.getElementById(ul);

  var lis = ul.getElementsByTagName("LI");
  var vals = [];

  for (var i = 0, l = lis.length; i < l; i++)
    vals.push(lis[i].innerHTML);

  vals.sort();

  if (sortDescending)
    vals.reverse();

  for (var i = 0, l = lis.length; i < l; i++)
    lis[i].innerHTML = vals[i];
}

var desc = false;
document.getElementById("test").onclick = function() {
  sortUnorderedList("list", desc);
  desc = !desc;
  return false;
}
<input type="button" id="test" value="Sort List (click again to reverse)" />

658.7599605058606

658.7599605058602

658.7599605058607

657.7599605058606

659

Comment: So simple and i couldn't figure this out by my self... I think im getting too old to do this =/ Thank You very much! It worked perfectly!


Seasonal ARIMA model mathematical equation

Question: I am trying to write a mathematical equation for a seasonal ARIMA model of ARIMA (0,0,1)(0,1,1) where the values are recorded quarterly.
I have tried to follow other examples but i cant seem to get my head around these specific examples and cant apply them to my model.
Any help would be greatly appreciated
Comment: Try looking up similar questions here at Cross Validated (see the column on the right or just search relevant keywords), there should be a few that fit your problem closely.
Comment: This question is unanswerable at present. It seems you looked at "other examples", which? Can you link to them? You couldn't "get [your] head around" them, why not? We can answer questions that might otherwise be duplicates if we know what part of the duplicate you didn't understand, otherwise we'd just have to copy the information in toto, which obviously wouldn't help you.
Answer: EDITED TO USE A QUARTERLY SERIES/MODEL
I took quarterly series (in logs) and estimated your model and obtained   . I also asked for a pure right hand side ( regression form ) version and obtained   This second form is usable by "beginners" in time series as it often clears up the fog and aids understanding/comprehension. A third way is to restate the ARIMA model as a PDL/ADL in the history of the series since ARIMA models are simply optimal weighted averages of the past. You can (in this case ) obtain those weights (coefficients of the past) by dividing [1-B4] by  [1+.727B1][1-.708**4]. These are called the pi weights  .  Thus the question "How many values should I use in my weighted average and what weights should I apply" is answered by ARIMA.
See Seeking certain type of ARIMA explanation for a more detailed discussion of the equivalence of ARIMA and weighted averages.
Comment: Why not leave a comment linking to your previous answer, or write a new answer with some basic information and a link to it? Copying and pasting your previous answer doesn't seem appropriate.
Comment: I'm not sure how this addresses the question, isn't the Box and Jenkins [airlines data set](http://calcnet.mth.cmich.edu/org/spss/Prj_airlinePassengers.htm) monthly not quarterly? To the extent that the OP's question is not a duplicate, it requires quarterly data.
Comment: @silverfish as you correctly said the airline series is monthly but the "message" remains the same for any seasonality. The OP did not specify the seasonality.
Comment: @silverfish upon closer reading he did ask for quarterly .... One can simply substitute a 4 for my 12 to deal with that. I will edit my answer appropriately.


Using difference quotient to calculate derivative

Question: As of late, I've been trying to use the difference quotient to calculate the derivative of the following function:
$$ f(x) = \frac{x}{\sqrt{x^2+2}} $$
When calculating the limits, the function becomes very complicated. I tried to factorise out the h from the numerator from the expression shown below but I can't straighten out the rest of the equation.
$$ \lim_{h\to 0} \frac{\frac{x+h}{\sqrt{(x+h)^2+2}} - \frac{x}{\sqrt{x^2+2}}}{h} $$
How do I calculate the derivative using this method in an efficient manner? Thank you for your help.
Answer: It just requires a bit of algebra. I don't know if there is a slicker way to prove this.
\begin{align}
&\frac{x+h}{\sqrt{(x+h)^{2} + 2}} - \frac{x}{\sqrt{x^{2} + 2}} \\
&=\frac{(x+h)\sqrt{x^{2} + 2}-x\sqrt{(x+h)^{2} + 2}}{\sqrt{x^{2}+2}\sqrt{(x+h)^{2} + 2}} \quad \text{cross multiplication} \\
&= \frac{(x+h)\sqrt{x^{2} + 2}-x\sqrt{(x+h)^{2} + 2}}{\sqrt{x^{2}+2}\sqrt{(x+h)^{2} + 2}} \cdot \frac{(x+h)\sqrt{x^{2} + 2}+x\sqrt{(x+h)^{2} + 2}}{(x+h)\sqrt{x^{2} + 2}+x\sqrt{(x+h)^{2} + 2}} \quad \text{conjugate} \\
&=\frac{h(4x + 2h)}{\sqrt{x^{2}+2}\sqrt{(x+h)^{2} + 2}[(x+h)\sqrt{x^{2} + 2}+x\sqrt{(x+h)^{2} + 2}]} \\
&\implies \lim_{h \to 0} \frac{1}{h} \cdot \frac{h(4x + 2h)}{\sqrt{x^{2}+2}\sqrt{(x+h)^{2} + 2}[(x+h)\sqrt{x^{2} + 2}+x\sqrt{(x+h)^{2} + 2}]} \\
&=\lim_{h \to 0} \frac{4x + 2h}{\sqrt{x^{2}+2}\sqrt{(x+h)^{2} + 2}[(x+h)\sqrt{x^{2} + 2}+x\sqrt{(x+h)^{2} + 2}]} \\
&=\frac{2}{(x^{2}+2)^{3/2}}
\end{align}
Answer: For brevity, let us denote $x_h:= x+h$.
Multiplying/dividing by the conjugate sum to get a difference of squares, the numerator becomes
$$\frac{x_h^2}{x_h^2+2}-\frac{x^2}{x^2+2}.$$
Then reducing to the common denominator, the numerator is
$$x_h^2(x^2+2)-x^2(x_h^2+2)=2x_h^2-2x^2=2h(x_h+x),$$
which tends to $4hx$ while the denominator $(x_h^2+2)(x^2+2)$ tends to $(x^2+2)^2$. Now the conjugate sum was
$$\frac{x_h}{\sqrt{x_h^2+2}}+\frac{x}{\sqrt{x^2+2}}\to\frac{2x}{\sqrt{x^2+2}}.$$
Putting all together,
$$f'(x)=\frac{4x}{(x^2+2)^2}\frac{\sqrt{x^2+2}}{2x}=2(x^2+2)^{-3/2}.$$
Comment: So simpler than mine ! Cheers :-(
Comment: @ClaudeLeibovici: I made it simple mainly by avoiding a full development. Maybe a cheat :) Cheers.
Answer: Let us anticipate a little and use the general product formula $(uv)'=u'v+uv'$, which immediately implies $(u^2)'=2u'u$.
Now we can rewrite the initial identity
$$f^2(x)(x^2+2)=x^2$$
and take for granted that $(x^2+2)'=(x^2)'=2x$ which are quite easy to establish.
Then if we differentiate both members,
$$2f'(x)f(x)(x^2+2)+f^2(x)2x=2x$$ and
$$f'(x)=\frac{2x(1-f^2(x))}{2f(x)(x^2+2)},$$
which leads to the desired result.

Proof:
$$(u(x)v(x))'=\lim_{h\to0}\frac{u(x+h)v(x)-u(x)v(x+h)}h=\\
\lim_{h\to0}\frac{u(x+h)v(x)-u(x)v(x)+u(x)v(x)-u(x)v(x+h)}h=\\
\lim_{h\to0}\frac{u(x+h)-u(x)}hv(x)+\lim_{h\to0}u(x)\frac{v(x+h)-v(x)}h=\\
u'(x)v(x)+u(x)v'(x).$$
Comment: This one is really elegant ! Thanks for providing this solution. Cheers.
Answer: Mattos gave the elegant way of doing it rigorously.
There is another way I just propose for your curiosity considering $$\frac{x+h}{\sqrt{(x+h)^2+2}}=\frac{x+h}{\sqrt{x^2+2+2hx+h^2}}=\frac{x+h}{\sqrt{x^2+2}\,\sqrt{1+\frac{2hx+h^2}{x^2+2}}}$$ Use the generalized binomial theorem or Taylor expansion or equivalents $$\frac 1 {\sqrt{1+a}}=1-\frac{a}{2}+O\left(a^2\right)$$ So $$\frac 1 {\sqrt{1+\frac{2hx+h^2}{x^2+2}}}\sim 1-\frac{2hx+h^2}{2(x^2+2)}$$ this makes $$\frac{x+h}{\sqrt{(x+h)^2+2}}\sim\frac {x+h}{\sqrt{x^2+2}}\left(1-\frac{2hx+h^2}{2(x^2+2)} \right)$$ $$\frac{x+h}{\sqrt{(x+h)^2+2}}=\frac {x}{\sqrt{x^2+2}}\left(1-\frac{2hx+h^2}{2(x^2+2)} \right)+\frac {h}{\sqrt{x^2+2}}\left(1-\frac{2hx+h^2}{2(x^2+2)} \right)$$ $$\frac{x+h}{\sqrt{(x+h)^2+2}} - \frac{x}{\sqrt{x^2+2}}=-\frac {x}{\sqrt{x^2+2}}\left(\frac{2hx+h^2}{2(x^2+2)} \right)+\frac {h}{\sqrt{x^2+2}}\left(1-\frac{2hx+h^2}{2(x^2+2)} \right)$$
$$\frac{\frac{x+h}{\sqrt{(x+h)^2+2}} - \frac{x}{\sqrt{x^2+2}}}{h}=-\frac {x}{\sqrt{x^2+2}}\left(\frac{2x+h}{2(x^2+2)} \right)+\frac {1}{\sqrt{x^2+2}}\left(1-\frac{2hx+h^2}{2(x^2+2)} \right)$$ Now, making $h \to 0$, the limit is then $$-\frac {x}{\sqrt{x^2+2}}\left(\frac{x}{x^2+2} \right)+\frac {1}{\sqrt{x^2+2}}=\frac 2 {(x^2+2)^{3/2}}$$
Edit
When I posted my answer, I just saw Yves Daoust's answer. It is much simpler that mine. However, I do not delete it since, as said, it was done for your curiosity.
Comment: Yep, good attempt, but unfortunately it doesn't simplify nicely.