text:
Q: Normality, Ordinary Least Squares (OLS) and Geographically Weighted Regression (GWR) Most of the publications I have reviewed, conduct both OLS and GWR for comparison, and prior to analysis, ensure dependent and explanatory variables are normally distributed. Can someone explain why this is necessary for GWR? Are both OLS and GWR parametric? Is there a non-parametric version of GWR?

A: No, GWR is a frequentist, linear method but there is flexibility in how you define the distributional form of the model (ie., Poisson, Binomial, Gaussian). The GWR is a local regression that emphases 2nd order variation whereas OLS is a first order model. The general motivation in running both is to draw inference about first (global) and second (local) order process but, more directly GWR is specified to account for nonstationarity.
As far a normality, heteroscedasticity is impossible to evaluate in a local regression and as such is effectively ignored. However, this is important in the OLS.
Please note that GWR is a very suspect method and unless you have very strong nonstationarity in your data I would highly recommend abandoning its application. Besides, in the absence of nonstationarity, there is really no justification for the specification of a local regression. In the absence of second-order variation GWR will likely just overfit the data.
An OLS can often be robust to weak first-order spatial autocorrelation and should provide a reasonable model. If not your next step should not be GWR but a model, such as mixed effects models or spatial autoregressive model, where a spatial term can be explicitly defined.


text:
Q: FSCalendar with Week scope has unintended footer-like view I have issue while using FSCalendar
I created FSCalendar with .week Scope and there's unintended space at bottom of calendar.:

If I try to reduce calendar's height, its font size is also reducing and calendar looks squished.:

class ViewController: UIViewController {

    fileprivate weak var calendar: FSCalendar!

    override func viewDidLoad() {
        super.viewDidLoad()

        let calendar = FSCalendar(frame: CGRect(x: 0, y: 100, width: self.view.frame.width, height: 300))
        self.calendar = calendar
        view.addSubview(calendar)
        calendar.locale = Locale(identifier: "en_US")
        calendar.backgroundColor = .lightGray
        calendar.scope = .week
        calendar.headerHeight = 0
    }
}

I have 3 big questions.

*

*Is there any way to remove that bottom space and fit view to calendar?

*Is FSCalendar's height should be 300?

*Can I use FSCalendar with AutoLayout Constraint?

A: You need to update FSCalendar's frame. It doesn't update its frame by itself when you change the scope of the calendar. You can use the following method to update its frame using a manual layout(Already mentioned on the library's GitHub page):
func calendar(_ calendar: FSCalendar?, boundingRectWillChange bounds: CGRect, animated: Bool) {
    calendar?.frame = CGRect(origin: calendar?.frame.origin ?? CGPoint.zero, size: bounds.size)
    // Do other updates here
}

You can also do it with AutoLayout Constraint.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Launch and autopopulate an email from Excel? I'm looking for a way to click a button in Excel and launch an email, then automatically fill in various fields based on Excel's cell values.
The email looks roughly like this:
"Dear [name],
Job: [description]
Payment: [amount]"
...Etc. The information in square brackets is contained in my Excel spreadsheet, so I essentially want to  automatically have it copy and paste into the fields of the email.
Is there a way to do this?
I'm using Mail for Mac, Excel Mac 2011.


text:
Q: Can we add restart time for a pod in statefulset, when the pod is stuck in pending state? I have pvc template creation enabled in statefulset.The pod is created before the pvc binds with the pv. Pod is stuck in pending state for long time showing that the pvc is not bound. Can we alter the time for this pod to restart?
I am using an EKS fargate cluster


text:
Q: LIST c# to WCF service not working I'm trying to do is just a simple query toList() to return to the WCF service but the service is returning an error.
This is all I have ordered from first use to last use:
[OperationContract]
List<alertas> LeerAlerta();

 public List<alertas> LeerAlerta()
 {
      return _pr.LeerAlerta();
 }

 public List<alertas> LeerAlerta()
 {

     return _db.LeerAlerta();
 }

  internal List<alertas> LeerAlerta()
  {

       using (var db = new alertas2015())
       {
           var alertas = db.alertas.ToList();

           return alertas;
        }

   }

And the object alertas:
public partial class alertas
{
        public int id { get; set; }
        public int modulos_id { get; set; }
        public string proceso { get; set; }
        public string metodo { get; set; }
        public string descripcion { get; set; }
        public int estado { get; set; }
        public string receptor { get; set; }
        public System.DateTime fecha { get; set; }
        public System.DateTime fecha_aceptada { get; set; }

        public virtual modulos modulos { get; set; }
}

The error I'm having is that when reading that wcf service i get ErrorCode 10054 from WcfStorm saying that the host has been closed.
What am I doing wrong?


text:
Q: How to get rid of vertical padding in Flutter DropdownButton? How do I get rid of this extra padding please? I've already enabled isDense.
I don't know if I have to do something with style or if this is a bug: https://github.com/flutter/flutter/issues/60624


text:
Q: Converting Sharepoint 2007 solution to 2010 Has anyone converted a Sharepoint 2007 solution to 2010 ?
I have a highly customized 2007 solution and need to upgrade it, i've seen some info on this, e.g. here but my solution is more complex than a single web part.
I'm concerned about e.g. the following topics and hopefully someone can shed some light on it:

*

*Schema.xml, does it need to be upgraded to match new 2010 syntax ? I've done some testing on this and the top menu bar seems to be missing so I can't create new items

*Mapping the structure of the previous 12 hive. Is there any changes to the structure, can I just rename 12 to 14 and be done with it ?

*onet.xml, does it need to be upgraded similar to Schema.xml ?

*Workflows, will my old workflows be intact or are there any changes to the OM that I need to take into account ?

Finally is there some conversion tool out there that can help me resolve some of these issues ?

A: Have a look at my series of posts about porting a SharePoint 2007 WSPBuilder Project to SharePoint 2010. It doesn't deal with onet.xml, but it does explain how to move from the 12 hive to the 14 hive.


text:
Q: ¿Cómo bloquear el ingreso de otros valores? Necesito bloquear el ingreso de letras y simbolos donde los numeros y de numeros y simbolos donde los caracteres
Ejemplo:

*

*Ingreso Max pero no quiero recibir números o algun símbolo.

*Ingreso 0987563421 como un telefono pero no deseo recibir letras ni símbolos.

Este es mi código:
#include <iostream>
using namespace std;
int main ()
{
    char n[21], a[21], c[13], tel[13], us[21], co[21];
    cout <<"\n\n\n\n\t\t\t\t                   Tricell S.A." << endl;
    cout <<"\t\t\t\t                <---------------->" << endl;
    cout <<"\n\t\t\t\t        > Ingrese sus nombres: ";
    cin.ignore(1,'\n');
    cin.get(n, 21);
    cout <<"\n\t\t\t\t        > Ingrese sus apellidos: ";
    cin.ignore(1,'\n');
    cin.get(a, 21);
    cout <<"\n\t\t\t\t        > Ingrese su cedula: ";
    cin.ignore(1,'\n');
    cin.get(c, 13);
    cout <<"\n\t\t\t\t        > Ingrese su telefono: ";
    cin.ignore(1,'\n');
    cin.get(tel, 13);
    cout <<"\n\t\t\t\t        > Ingrese un usuario: ";
    cin.ignore(1,'\n');
    cin.get(us, 21);
    cout <<"\n\t\t\t\t        > Ingrese una contrase"<<char(164)<<"a: ";
    cin.ignore(1,'\n');
    cin.get(co, 21);
    cout <<"\n\t\t\t\t        < Datos registrados correctamente\n\n";
    cin.get();
    cin.get();
    return 0;
}

¿Conocen alguna funcion o librería para bloquear caracteres?

A: Ten en cuenta que los números de teléfono pueden contener caracteres que no son numéricos, como el símbolo +: +34654321012 es equivalente a 0034654321012. Por otro lado, en los nombres de personas puedes encontrar números u otros caracteres, como la periodista Jennifer 8. Lee o el sueco Brfxxccxxmnpcccclllmmnprxvclmnckssqlbb11116.

Si quieres ignorar ciertos valores de la lectura estándar puedes usar ignore, así pues para ignorar números al ingresar letras Podrías filtrar los valores que te interesan (e ignorar el resto) discriminando entre números y letras:
std::string s{};
std::string::value_type c{};

// Leemos caracter a caracter
while (std::cin.get(c))
    // Si el caracter es alfabetico...
    if (std::isalpha(c))
        // ... agregamos el caracter a nuestro string.
        s.push_back(c);

Con isalpha puedes determinar si un caracter es alfabético o numérico.
Puedes ver el código funcionando [aquí].

A: Para el que tenga el mismo problema o quiera una solucion esta fue la que encontre y probe:
Se crean dos funciones:
1.- void editable (char *p); que sera la funcion que bloqueara los caracteres del teclado
y su codigo es:

void editable (char *p)
{

//TAM es una variable que determina el limite de caracteres a ingresar

    int i, TAM=16;
    char tecla;
    i = 0;
    p[0] = '\0';
    do
    {
        tecla = getch ();
        if ( i > 0 && tecla == 8 )
        {
            cout<<"\b \b";
            p[--i] = '\0';
        }
        else
        {

        //En esta seccion es en la que se edita el bloqueo de caracteres (codigo ASCII)

            if ( (tecla >= 48 && tecla <= 57) || (tecla >= 65 && tecla <= 95)  || (tecla >= 97 && tecla <= 122) )
            {
                cout<<tecla;
                p[i++] = tecla;
            }
        }
    } while ((tecla != 13 || p[0] == '\0') && i < TAM);

    p[i] = '\0';
    return ;
}

2.- char getch (); que sera la funcion que capturara un caracter sin imprimirlo en el estandar de c++ no existe conio.h asi que hay que crear la funcion
char getch ()
{
    char car;
    DWORD leidos, modo;

    GetConsoleMode ( GetStdHandle (STD_INPUT_HANDLE), &modo );
    SetConsoleMode ( GetStdHandle (STD_INPUT_HANDLE), modo &
                     !ENABLE_ECHO_INPUT & !ENABLE_PROCESSED_INPUT );
    ReadConsole ( GetStdHandle (STD_INPUT_HANDLE), &car, 1, &leidos, NULL );
    SetConsoleMode ( GetStdHandle (STD_INPUT_HANDLE), modo );
    return car;
}


text:
Q: Is there a way to test android applications directly on phone, without the emulator? How can I test applications in eclipse without the emulator ? I have a phone with android, and I want to test the apps directly on phone.
Update: I want to develop the entire application using the phone. I hate the emulator because it's very slow on my computer. Also, my application needs GPS and I can better handle this using the phone.

A: Connect your phone by USB cable to your computer.  Remember to set android:debuggable="true" in your application in the AndroidManifest file.
ETA: alternatively, you can email the .apk files to an email account the phone can access and install from there.  You'll also need "unknown sources" ticked under Settings -> Application. (Although that will only let you run them, not debug them.)

A: Yes, Android explicitly supports this. Try this link: https://developer.android.com/studio/run/device.html

A: Yea you need to add the "charge" usb drivers then in the settings turn on USB debugging. I would check with "adb logcat" if you see the logs start to roll your set. In eclipse just build and if everything is setup correct it will install and start on your device. If you have more than one device attached it will ask you to pick.

A: Yes, but in addition to what others mentioned, you need to install a device driver for the particular Android device that you are connecting through USB. Each Android phone may require a different driver (at least on Windows).

A: there are a few thinks you need to do:

*

*setup as others have said, with SDK / eclipse / etc

*on your phone configure it to be debugging.  Settings -> Applications -> Developement

*make sure you have the USB driver for your phone

During setup of the SDK there is a weird Java setup gotcha.  I found great walk through at http://www.mobiusbay.com/home/android%E2%80%93day0gettingstarted
Short story, if you have the Java SDK installed and the Android SDK claims you do not.  Hit the back button and then the Next button.
At the walk through they show a simple application to verify it is running.

A: Yes, you can without the emulator, but not without the Android SDK/Eclipse (at least, not that I know of).  You do it by attaching your Android device and then going into "Debug Configurations" (Debug drop-down menu).  In there you should be able to add your device as a target.

A: Yes, its very simple actually. In case of Samsung devices all you need is "Kies". Follow the link to download for either Windows or Mac OS.
Once the download is complete, install the application.
Next make sure that the following are enable/checked on the device and the emulator:
Device:

*

*Enable USB Debugging

*Enable Stay Awake
Emulator:

*

*Within the AndroidManifest.xml, set Debugging to True
Once the above mentioned steps are completed, connect the device to your PC and click Run as Android Application
Now you should see the application running on your device.


text:
Q: error in long number addition using character array The code written below is working out quite fine but gives out only one error which I cannot find out why. When we add numbers like 99+1 or 999+1 it prints only the zeroes but not one. If you point out the error in the code and correct it i would rather be thankful for your help.
#include<stdio.h>
int main()
{
    int num1[255], num2[255], sum[255];
    char s1[255], s2[255];
    int l1, l2,h;

    printf("Enter Number1:");
    scanf("%s", &s1);
    printf("Enter Number2:");
    scanf("%s", &s2);

    for (l1 = 0; s1[l1] != '\0'; l1++)
        num1[l1] = s1[l1] - 48;

    for (l2 = 0; s2[l2] != '\0'; l2++)
        num2[l2] = s2[l2] - 48;

    int carry = 0;
    int k = 0;
    int i = l1 - 1;
    int j = l2 - 1;

    for (; i >= 0 && j >= 0; i--, j--, k++)
    {
        sum[k] = (num1[i] + num2[j] + carry) % 10;
        carry = (num1[i] + num2[j] + carry) / 10;
    }

    if(l1==0 && carry==1)
    {
        sum[k++]=1;
    }
    else if (l1 > l2)
    {
        while (i >= 0)
        {
            sum[k++] = (num1[i--] + carry)%10 ;
            carry = (num1[i]+carry)/10;
        }
        if(i==0&&carry==1)
        {
            sum[k++]=carry;
        }
    }
    else if(l1<l2)
    {
        while (j >= 0)
        {
            sum[k++] = (num2[j--] + carry)%10 ;
            carry = (num2[j]+carry)/10;
        }
        if(j==0&&carry==1)
        {
            sum[k++]=carry;
        }
    }

    printf("Result:");

    for (k--; k>= 0; k--)
        printf("%d", sum[k]);

    return 0;
}

A: You need to write the carry counter, and then read it. You code only needed a minor adjustment for the carry, then it works.
#include <stdio.h>

int main() {
    int num1[255], num2[255], sum[255];
    char s1[255], s2[255];
    int l1, l2;

    printf("Enter Number1:");
    scanf("%s", s1);
    printf("Enter Number2:");
    scanf("%s", s2);

    for (l1 = 0; s1[l1] != '\0'; l1++)
        num1[l1] = s1[l1] - '0';

    for (l2 = 0; s2[l2] != '\0'; l2++)
        num2[l2] = s2[l2] - '0';

    int carry = 0;
    int k = 0;
    int i = l1 - 1;
    int j = l2 - 1;
    for (; i >= 0 && j >= 0; i--, j--, k++) {
        sum[k] = (num1[i] + num2[j] + carry) % 10;
        carry = (num1[i] + num2[j] + carry) / 10;
    }
    if (l1 > l2) {

        while (i >= 0) {
            sum[k++] = (num1[i] + carry) % 10;
            carry = (num1[i--] + carry) / 10;
        }

        if (sum[k - 1] != carry)
            sum[k++] = carry;

    } else if (l1 < l2) {
        while (j >= 0) {
            sum[k++] = (num2[j] + carry) % 10;
            carry = (num2[j--] + carry) / 10;
        }
        if (sum[k - 1] != carry)
            sum[k++] = carry;
    } else {
        if (carry > 0)
            sum[k++] = carry;
    }

    printf("Result:");
    for (k--; k >= 0; k--)
        printf("%d", sum[k]);

    return 0;
}

Test
Enter Number1:99
Enter Number2:1
Result:100

Test 2
Enter Number1:9999999999999999999999999999999999
Enter Number2:1
Result:10000000000000000000000000000000000

A: *

*In the while loop (i>=0), you are decrementing the index i in the sum step. You are using this index again in the carry step below. You should decerement it at the next carry step.

*The if condition after that, is if(i==0&&carry==1) i will be always -1 at the end of the loop. So the conditionfor i==0 can be removed.
The fixed code is below.
#include<stdio.h>
int main() {
  int num1[255], num2[255], sum[255];
  char s1[255], s2[255];
  int l1, l2,h;

  printf("Enter Number1:");
  scanf("%s", s1);
  printf("Enter Number2:");
  scanf("%s", s2);

  for (l1 = 0; s1[l1] != '\0'; l1++)
    num1[l1] = s1[l1] - 48;

  for (l2 = 0; s2[l2] != '\0'; l2++)
    num2[l2] = s2[l2] - 48;

  int carry = 0;
  int k = 0;
  int i = l1 - 1;
  int j = l2 - 1;
  for (; i >= 0 && j >= 0; i--, j--, k++) {
    sum[k] = (num1[i] + num2[j] + carry) % 10;
    carry = (num1[i] + num2[j] + carry) / 10;
  }
  if(l1==0&&carry==1)
  {
    sum[k++]=1;
  }
  else if (l1 > l2) {

    while (i >= 0) {
      sum[k++] = (num1[i] + carry)%10 ;
      carry = (num1[i--]+carry)/10;
    }
    if(carry==1)
    {
      sum[k++]=carry;
    }
  } else if(l1<l2) {
    while (j >= 0) {
      sum[k++] = (num2[j] + carry)%10 ;
      carry = (num2[j--]+carry)/10;
    }
    if(carry==1)
    {
      sum[k++]=carry;

    }
  }

  printf("Result:");
  for (k--; k>= 0; k--)
    printf("%d", sum[k]);

  return 0;
}

Test1
Enter Number1:99
Enter Number2:2
Result:101

Test2
Enter Number1:22
Enter Number2:99998
Result:100020

A: Try this code. I think this should help you.
#include<stdio.h>
int main()
{
int num1[255], num2[255], sum[255];
char s1[255], s2[255];
int l1, l2,h;

printf("Enter Number1:");
scanf("%s", &s1);
printf("Enter Number2:");
scanf("%s", &s2);

for (l1 = 0; s1[l1] != '\0'; l1++)
    num1[l1] = s1[l1] - '0';

for (l2 = 0; s2[l2] != '\0'; l2++)
    num2[l2] = s2[l2] - '0';

int carry = 0;
int k = 0;
int i = l1 - 1;
int j = l2 - 1;

for (; i >= 0 && j >= 0; i--, j--, k++)
{
    sum[k] = (num1[i] + num2[j] + carry) % 10;
    carry = (num1[i] + num2[j] + carry) / 10;
}

//if num2 has more digits than num1

if(i==-1 && j>=0)
{
      while(j>=0)
      {
          sum[k++]=(num2[j]+carry)%10;
          carry=(num2[j]+carry)/10;
          j--;
      }
}

//if num1 has more digits than num2

if(i>=0 && j==-1)
{
      while(i>=0)
      {
          sum[k++]=(num1[i]+carry)%10;
          carry=(num1[i]+carry)/10;
          i--;
      }
}
 // both has reached to their last digits position and suppose the carry is still left
 if(i==-1 && j==-1)
 {
    if(carry>0)
      sum[k++]=carry;
 }

printf("Result:");

for (k=k-1; k>= 0; k--)
    printf("%d", sum[k]);

return 0;
}


text:
Q: can App Engine SDK run on GAE? The question may sound a bit stupid but I think it's interesting.  Is it possible to upload a GAE application (java or python) from another GAE application ? I mean to use the first GAE app purely as a build server (e.g. http://www.atlassian.com/software/bamboo/overview ) to build / deploy an application.

A: It would be technically possible to do this with some tweaking, but the Terms of Service prohibit apps that upload other apps.

A: It sounds interesting to me, but ultimately I'm not sure of the practicality of it.  You'd have to spend quite a bit of effort to modify the SDK to replace all file operations, and emulate the development filesystem on either the filestore or blobstore.
I say I don't think it's practical, because unless you're running strictly as backends (which ends up being expensive), none of the frontends really last long enough to emulate a debugger.  It would be very difficult to develop software if you can't debug.
That and what Nick said.


text:
Q: thinking_sphinx connection via MySQL Ubuntu 14.04 installation, with nginx, passenger and postgresql.  The following steps are run:
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install mysql-server
sudo mysql_secure_installation  _for allowing only localhost connection_
sudo apt-get install sphinxsearch

gem file has
gem 'mysql2', '0.3.18', :platform => :ruby
gem 'thinking-sphinx', '3.1.4'

thinking_sphinx.yml  specifies
  mysql41: 9312

Running:
RAILS_ENV=development bundle exec rake ts:rebuild

proceeds correctly: total 112 writes, 0.079 sec, 485.0 kb/call avg, 0.7 msec/call avg  Started searchd successfully (pid: 21644).
netstat -ltnp shows only one searchd process
tcp        0      0 127.0.0.1:9312          0.0.0.0:*               LISTEN      21644/searchd

So one concludes that everything is a go... right? [nasty buzzer]
ThinkingSphinx::ConnectionError
Error connecting to Sphinx via the MySQL protocol.
Error connecting to Sphinx via the MySQL protocol. _nice... stated twice!_
Can't connect to MySQL server on '127.0.0.1' (111)

Possible avenues for non-connection:

*

*mySql-server root password not digested

*nginx somehow impeding the connection

others?  how to verify/assert?

A: While Sphinx implements the MySQL protocol for querying, it does not pay any attention to authentication, so Thinking Sphinx doesn't use those fields either. So I'm not sure if mysql_secure_installation is the right tool for the job - certainly, not if it's trying to use authentication to control access. If you don't want to allow external communication to Sphinx, can you just block the port?

A: Building on Pat's observation the following got me running on Ubuntu 14.04 installation, with nginx, passenger and postgresql.
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install mysql-server
sudo apt-get install sphinx search

Ensure gem file has
gem 'mysql2', '0.3.18', :platform => :ruby
gem 'thinking-sphinx', '3.1.4'
# alternately with JRuby
gem 'jdbc-mysql',      '~> 5.1.28', :platform => :jruby

thinking_sphinx.yml  must specify
  mysql41: [port_number]

multiple search processes need distinct ports.
Configure, index and start via:
RAILS_ENV=[your_environment] bundle exec rake ts:rebuild

sudo netstat -ltnp should show the listen port as defined in thinking_sphinx.yml and rendered in config/[your_environment].sphinx.conf
tcp        0      0 127.0.0.1:[port_number]          0.0.0.0:*               LISTEN      21644/searchd

Finally,
sudo reboot


text:
Q: Write to the depth buffer in a Unity 3D unlit shader? I admit I'm a bit lost when it comes to shaders. Below is my unlit shader. What can I add to this to write to the depth buffer and depth texture? Also, am I doing anything wrong or unnecessary in this shader?
Shader "Unlit/Environment Texture" {
Properties {
    _MainTex ("Base (RGB)", 2D) = "white" {}
    _MainTexBias ("Mip Bias (-1 to 1)", float) = -1
}

SubShader {
    Tags { "RenderType"="Opaque" }

    Lighting Off
    Fog { Mode off }

        Pass {
            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                #include "UnityCG.cginc"

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord : TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : SV_POSITION;
                    half2 texcoord : TEXCOORD0;
                };

                sampler2D _MainTex;
                float4 _MainTex_ST;
                half _MainTexBias;

                v2f vert (appdata_t v)
                {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                    return o;
                }

                fixed4 frag (v2f i) : SV_Target
                {
                    fixed4 col = tex2Dbias(_MainTex, half4(i.texcoord.x,i.texcoord.y,0.0,_MainTexBias));
                    return col;
                }
            ENDCG
        }
    }
}

A: the frag should has the SV_Depth semantic
struct fragOutput {
    fixed4 color : SV_Target;
    float depth:SV_Depth;
};

fragOutput frag (v2f i)
{
    fragOutput o;
    o.color = tex2D(_MainTex, i.uv);
    o.depth = i.depth;
    return o;
}

A: Uhm... this should already write to the depth buffer? You can add "Queue"="Opaque" to the tags to enable front-to-back sorting, though i think it should default to this anyways. Ztest On is also implicit. How does it look for you in Unity?


text:
Q: Help me find a tutorial to dual boot windows 7 and ubuntu 13.04 What I've got is a compatible PC with both systems ,Windows 7 and Ubuntu 13.04 ,I've Windows 7 already installed ,now I want to install Ubuntu, and be able to choose which one I want to boot when I power my computer on.
First time I tried it ,I didn't watch any tutorial ,installed Ubuntu on another partition from Windows 7 (D) ,and got that partition deleted ,lost many files but I just want to have Ubuntu and have some experience with it !
Any help is much appreciated !

A: Here's a How to  from Ubuntu --> Ubuntu Installation
Helpful links:
How to burn a DVD
How to create a bootable USB-Stick
Install Ubuntu with with the Windows installer

A: I had such wish before so I selected an easier way. It's installing a virtual machine (e.g., WMware workstation) and then install any other OSs (like, ubuntu) on it.
hope it helps.
This link also will be helpful https://help.ubuntu.com/community/WindowsDualBoot

A: Before you start the installation, create a separate disk partition in Windows. Insert your bootable disc/USB device. Follow the instructions. When you see the disk chooser, select your newly created disk. Select the Change option from below. Format it to ext4 and select mount point /. Press okay. Below, you'll see option for bootloader device. Click on it and choose the topmost option (It'll have some information about your HDD i.e. its size, manufacturer etc). Click continue when you are asked for swap partition option. If you do want to create a swap partition you'll have to create another partition. You won't need it in normal use anyway.

A: Dual Boot Ubuntu 13.04 and Windows 7 - on YouTube
http://youtu.be/xK8X7_tYWmA
I found the video above to be very helpful.
You may also want to consider partitioning your hard drive as described below, which will allow you to access data files from both Windows and Ubuntu. I suggest using Windows Disk Manager to do this if you are more familiar with Windows. GParted, the disk management tool in Ubuntu, can also accomplish it -- but make sure the partition you create is NTFS format. (Windows can only use NTFS; Linux can "see" both Linux partitions and NTFS, but Windows can't)
One partition for Windows recovery and system files
One partition for Windows OS and related files
(These are probably already in place since you have Windows installed)
From the remaining space, create a partition you can use for storage of docs, pictures, videos, etc. If you format this in NTFS, both Win7 and Ubuntu will be able to access the files.
Then go ahead and install Ubuntu. It will ask you whether you want to create a new partition in order to place Ubuntu into it. And it will create its own swap file if you choose the regular installation as opposed to the advanced. The video I linked above shows how to do the advanced installation, which is really pretty simple if you follow along carefully.
Good luck and enjoy Ubuntu - my installation has been working very well so far.


text:
Q: Matlab: compute the sum of elements in the lower portion of a matrix I have to develop a Matlab function that computes the sum of the elements in the reverse diagonal, and the elements to the right of the reverse diagonal.  Sum (A) = 38 ;  Sum (B) = 40;   Sum (C) = 25;
enter image description here
Can somebody provide me a solution on how to go about using looping to solve this problem ?

A: For a n×m Matrix:

*

*Set the sum to 0, column to 1 and top to n (assuming (n,1) is the bottom-left corner of the matrix)

*Add to the sum all elements in current column which row number is more or equal to the top.

*Add 1 to column. If column is greater than m we are done.

*Subtract 1 from top. If top is 0, set top to 1.

*Go to 1.

A: For matrix M
Mysum = sum(sum(tril(rot90(M,-1))))


text:
Q: Image as Signature in CRM Email I came to a scenario where I need to send emails on create of lead but the signature of the user contains Image and that image should reflect in MSCRM email. That image should located after 'Thanks' and above 'User's job title' in email body for CRM 11.
Although I tried it in MSCRM16 as well but no luck.
Is there any way to attach image in email body while sending it using system Workflow or custom workflow ?
Please help if there is any idea.
Thanks in advance.

A: Best way to to do this is to host the images/signatures on public facing website and copy them in to your email templates , use those templates in your lead mails
In case you have users with different signatures then you need to have multiple templates, and based on the logged in user switch your templates
Please follow the links
Email signatures
CRM 2011 E-Mails–How to Insert / Add Graphics


text:
Q: How can I select nth child of an nth child using jquery? How could I do either of these in jquery?

*

*nth Child of nth child

*first child of nth child

*descendants (children OR grandchildren) of nth child which are images

Edit: I am using a variable to access the 'child' like this
var number = ( ... code ...) ;
.... eq(number)

so I cant do anything like
$('li:nth-child(2) li:nth-child(2)')

A: combine the two?
//1
$(":nth-child(2) :nth-child(3)")
//2
$(":nth-child(2) :first-child")
//3
$(":nth-child(2) img")

Do it the same way you would in a css stylesheet.
var number = 2;
//1
$(":nth-child(" + number + ") :nth-child(" + number + ")")
//2
$(":nth-child(" + number + ") :first-child")
//3
$(":nth-child(" + number + ") img")


text:
Q: Solving an Integral With Square Root in the Denominator Solve for k:
$$\int_6^{16}\frac{1}{\sqrt{(x^3 + 7x^2 + 8x  -16)}}dx = \frac{\pi}{k}$$
I have factored the denominator to obtain $x^3 + 7x^2 + 8x - 16  =  (x-1)(x+4)^2$
I think that since the answer involves $\pi$, I have to somehow make it look like the derivative of arcsine or something.
Or should I do a trigonometric substitution?
Please help!

A: HINT:
As $x$ lies $\displaystyle\in[6,16] \sqrt{(x+4)^2}=+(x+4)$
Set $\displaystyle\sqrt{x-1}=u\implies x=u^2+1$

Alternatively,
Using Trigonometric substitution start with $\displaystyle\sqrt{x-1}=\tan\theta$
$\displaystyle\implies x=\sec^2\theta$
$$\int\frac1{\sqrt{x-1}(x+4)}dx=\int\frac{2\sec^2\theta\tan\theta}{\tan\theta(\sec^2\theta+4)}\ d\theta$$
$$=\int\frac{2\sec^2\theta}{(\tan^2\theta+5)}\ d\theta$$
Set $\tan\theta=u$

A: Your approach is fine. We get the integral as
$$I = \int \dfrac{dx}{\sqrt{x-1}(x+4)}$$
Now let $x-1 = t^2$. We then get
$$I = \int \dfrac{2tdt}{t(t^2+5)} = \int\dfrac{2dt}{t^2+5} =  \dfrac2{\sqrt5}\arctan(t/\sqrt5) + \text{constant} =  \dfrac2{\sqrt5}\arctan\left(\dfrac{\sqrt{x-1}}{\sqrt5} \right) + \text{constant}$$
Now I trust you can finish it off.

A: You can also use the substitution $x-1=t^{2}$ which then you will have the derivative of arctan in the integral.


text:
Q: Unicode text in minted source-code listing fails on certain characters I'm currently writing a small mathematical paper and have lots of unicode in my source-code - e.g.:
function y(
    ::Vector{<:Number},
    Φ::(T where T <: Function),
    ::Vector{<:Number})::(T where T <: Number)
    Σ(1, size()[1], j->[j] * Φ(j, ))
end

The problem I'm now having is that I (for example) can't get it to render the (U+1D430) and . I get the following in my build-log:
Missing character: There is no  in font Droid Sans Mono/OT:mapping=tex-text;!
Missing character: There is no  in font Droid Sans Mono/OT:mapping=tex-text;!
Missing character: There is no  in font Droid Sans Mono/OT:mapping=tex-text;!

and no matter what font I use it's this way. I'm 100% certain that my font (usually Fira Code) does support the character because it's also what I run in my source-code editor and there the characters show up just fine. I also made sure to test all the fallback fonts(hence the error message shows Droid Sans Mono) - but to no avail.
Does anyone have an idea on what else I could try to fix this?
EDIT: minimal working example
\documentclass{article}

\usepackage{minted}
\usepackage{fontspec}

\setmonofont[Mapping=tex-text, Scale=0.90,]{Fira Code}
%\setmonofont[Mapping=tex-text, Scale=0.90,]{Droid Sans Mono}

\begin{document}
  \begin{minted}{Julia}
      """Linear Regression
      # Args:
          : Parameters
          Φ(j, ): Basis function of type (Int, Vector{T}) -> T
          : Input vector
      """
      function y(
        ::Vector{<:Number},
        Φ::(T where T <: Function),
        ::Vector{<:Number})::(T where T <: Number)
          Σ(1, size()[1], j->[j] * Φ(j, ))
      end
  \end{minted}
\end{document}

A: I guess your aim is to print boldface w and x.
\documentclass{article}

\usepackage{minted}
\usepackage{fontspec}
\usepackage{newunicodechar}

\setmonofont{FiraMono}[
  Extension=.otf,
  UprightFont=*-Regular,
  BoldFont=*-Bold,
  Scale=0.9,
]

\newunicodechar{}{\textbf{w}}
\newunicodechar{}{\textbf{x}}

\begin{document}

\begin{minted}{Julia}
"""Linear Regression
# Args:
    : Parameters
    Φ(j, ): Basis function of type (Int, Vector{T}) -> T
    : Input vector
"""
function y(
  ::Vector{<:Number},
  Φ::(T where T <: Function),
  ::Vector{<:Number})::(T where T <: Number)
    Σ(1, size()[1], j->[j] * Φ(j, ))
end
\end{minted}

\end{document}

A: As per the comments.
A general text font is unlikely to be going to cover the 996 symbols of the Mathematical Alphanumeric Symbols code block in Unicode, let alone all the operators etc. A math font with Basic Latin glyphs, with everything in text mode (i.e., direct Unicode input) looks like it could work, if you make it the main font. All glyphs will print 'as-is', i.e., like ordinary glyphs, even though some are bold or not, some are italic or upright, some are sans or serif, etc. Asana Math and Latin Modern Math are two fonts like that. There are probably more. The reason is that the MAS defines 13 Latin alphabets, 5 and a bit Greek ones, and 5 types of Digits. The MAS is independent of the Basic Latin block, where the 'text' A-Z, a-z letters are.

I don't have shell-escape, so minted is inactive and I made manual line feeds.
MWE
\documentclass{article}

%\usepackage{minted}
\usepackage{fontspec}

\setmainfont[Mapping=tex-text, Scale=0.90,]{Latin Modern Math}
\begin{document}
%  \begin{minted}{Julia}
      """Linear Regression \\
      \# Args:\\
: Parameters\\
Φ(j, ): Basis function of type (Int, Vector{T}) $\to$ T\\
: Input vector\\
      """\\
      function y(\\
        ::Vector{<:Number},\\
        Φ::(T where T <: Function),\\
        ::Vector{<:Number})::(T where T <: Number)\\
          Σ(1, size()[1], j->[j] * Φ(j, ))\\
      end\\
%  \end{minted}
\end{document}

If minted is the driver of the question, we will need to find a mono math font with basic Latin (alternatively, can minted accept $...$ math mode?).
=====
Edited to add:
egreg's \newunicodechar is quite powerful. In effect, it maps A to B: ↦, where  is a glyph/character and  is arbitrary code.
This in turn allows math mode material (like $\to$, attached to an arbitrary glyph) to be inserted into the minted output. $..$ material directly inside minted prints verbatim, otherwise.
As well as non-ASCII mathematical symbols and operators.

MWE
\documentclass[12pt]{article}

\usepackage{minted}
\usepackage{xcolor}
\usepackage{fontspec}
\usepackage{newunicodechar}

\setmonofont{Fira Mono}[
  Scale=0.9,
]

\newfontface\fmxm{XITS Math}[Colour=blue]

\newunicodechar{}{{\fmxm }}
\newunicodechar{}{{\fmxm }}
\newunicodechar{}{{\fmxm }}
\newunicodechar{}{{\fmxm }}
\newunicodechar{}{{\fmxm }}
\newunicodechar{∗}{{\fmxm ∗}}

\newunicodechar{}{{\fmxm $\to$}}

\begin{document}

\begin{minted}{Julia}
"""Linear Regression
# Args:
     : Parameters
    (, ): Basis function of type (Int, Vector{T})  T
    : Input vector
"""
function y(
  ::Vector{<:Number},
  ::(T where T <: Function),
  ::Vector{<:Number})::(T where T <: Number)
    (1, size()[1], [] ∗ (, ))
end
\end{minted}

\end{document}

A random Anatolian hieroglyph, , is being used to carry the $\to$ into the output.
=====
Edit 2
Using code from here (How to change math font to monospace, only inside \texttt), and using newunicodechar as a key-value mechanism, gives:

MWE
\documentclass{article}
\usepackage{newunicodechar}
\usepackage{minted}
\usepackage{amsmath}
\newcommand{\ttmath}{%
  \everymath{%
    {\scriptstyle\mathtt{}}%
    {\scriptscriptstyle\mathtt{}}%
    \mathtt{\xdef\tmp{\fam\the\fam\relax}\aftergroup\tmp}}}
\newcommand{\val}[1]{\bgroup\ttmath\texttt{#1}\egroup}

\newunicodechar{}{\ensuremath{x^2 + y^2 = z^2}; \val{1\ensuremath{\ensuremath{\cdot}10\ensuremath{^{-6}}}} (\ensuremath{a_0}, \ensuremath{m_{\text{e}}})}
\newunicodechar{}{$\alpha \to \beta$}
\newunicodechar{}{\ensuremath{abc + d\cdot f(x) = g_i}}
\newunicodechar{}{$\Phi = \phi(x,n)$;}

\begin{document}

\begin{minted}{Julia}
 : number
# xyz
function

\end{minted}
\end{document}

Almost there.


text:
Q: Cross-site POST form submissions are forbidden My sveltekit app has a form which sends a POST request to server. The app is working fine on dev server but when I build and run the app it fails to send the form data via POST request. It shows the following error in the browser:

Cross-site POST form submissions are forbidden

A: This is a built-in protection against cross-site request forgery attacks in Sveltekit. Set csrf to false in svelte.config.js to allow cross-site post requests.
See csrf in the Sveltekit configuration docs
import adapter from '@sveltejs/adapter-node'

const config = {
  kit: {
    adapter: adapter(),
    csrf: {
      checkOrigin: false,
    }
  },
}

export default config

A: You have to set the the ORIGIN env var like this
ORIGIN=http://localhost:3000 node build/index.js
https://github.com/sveltejs/kit/tree/master/packages/adapter-node#origin-protocol_header-and-host_header

A: This works: node -r dotenv/config build after including your new variable in .env ORIGIN=https://yourwebsite.com (please install it with npm install dotenv command as pointed out here)


text:
Q: Android : Notification not sent & shown when Icon is changed I am working on an Android project in which I am sending out notifications whenever there is an event happening. Unfortunately, when I change the icon of Notification to our project icon, which is a 8.4kb image, I don't get any notification. This is especially problematic as there is no error thrown, just no notificiations are received.
When I change the image to a simple red-square, I can see the notification, but the notification is not even red colored. How can I properly set the Notification image to desired image. Thank you.
As you can see the first notification, the icon is not proper.
Screenshot :

Code :
  NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder.setAutoCancel(true);

mBuilder.setSmallIcon(R.drawable.defaultimage);
mBuilder.setContentTitle(subject);
mBuilder.setContentText(Html.fromHtml(text));

 if (type.equals("note")) {
                    Log.d("type","note");
                    Intent resultIntent = new Intent(getApplication(), EditNoteActivity.class);
                    resultIntent.putExtra("groupid", Long.valueOf(channelName));
                    resultIntent.putExtra("canvasid", Integer.valueOf(canvasId));
                    resultIntent.putExtra("sectionid", Integer.valueOf(sectionId));
                    resultIntent.putExtra("noteid", Integer.valueOf(noteId));

                    TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
                    stackBuilder.addParentStack(EditNoteActivity.class);

                    stackBuilder.addNextIntent(resultIntent);
                    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                    mBuilder.setContentIntent(resultPendingIntent);

                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                    mNotificationManager.notify(notificationCounter, mBuilder.build());
                    notificationCounter++;
}

The image which I am trying to set is a PNG image, of 8kb, doesn't help setting it any way. Any help would be nice. Thank you.
Update
When I select the image, The ide shows the image properly as seen from the screenshot :

Even if the IDE shows it correctly, the image received in notification is not correct.
Now, when I try to add it as an asset, it shows preview very wrong. And the images generated are also wrong.
Screenshot :

As you can see, it just says the image is some gray color, but its a blue colored image.
Aloks suggestion
  NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
                mBuilder.setAutoCancel(true);
                mBuilder.setSmallIcon(R.mipmap.twentynotelogo);
                Bitmap icon = BitmapFactory.decodeResource(getResources(),
                        R.mipmap.twentynotelogo);
                mBuilder.setLargeIcon(icon);
                mBuilder.setContentTitle(subject);
                mBuilder.setContentText(Html.fromHtml(text));

A: You need to implement new specification for notification,
Need to use setLargeIcon(),together with transparent small icon.
in your case you are using setSmallIcon() only that is causing issue.
Just set both small and large icon it will work.( it is an update in lollipop)
update: if you only need to set small icon than you need to use bitmap and apply some background color

A: Try to get the image as a drawable from the Android Studio as a Notifications Icon.
Also use setLarge() Icon as well.
While selecting the resource select it is a Image asset as shown below.

The notification icon shows in preview what it will look like based on the API levels.
For your icon you need to use it as a Transparent Icon and then import in the above method itself. Remove the blue layer from the icon then load it in the Android Studio. You will get this as shown below.

Then if you still want blue color in your icon you need to add background color programmatically to your NotificationCompat.Builder as
int notificationcolor = getResources().getColor(R.color.my_notif_color);

mBuilder.setColor(notificationcolor);


text:
Q: How to shrink divs vertically while keeping aspect ratio and location relative to other divs? In HTML images tend to keep their aspect ratio by default, which makes it easy to shrink images horizontally and keep proportions when the window is resized like this:

In the gif notice how the images not only keep aspect ratio but they stay together. They don't just get smaller in their own containers. This is what I want to accomplish, but vertically. ( When the window is dragged from bottom to top ).
All of the code to this simple demo is below. Currently if you make the snippet full screen and shrink the window vertically everything just gets clipped like this:

I want to keep everything on screen just like when it scales horizontally. I want it to behave in exactly the same way, but when the window is scaled vertically.
I've tried giving every element a width of auto or giving it a value of display: inline-block. Any ideas?

/* //////////////////////////// IMPORTS ////////////////////////// */
@import url( "https://necolas.github.io/normalize.css/latest/normalize.css" );

/* //////////////////////////// INITIAL ////////////////////////// */
body {
  max-width: 1024px;
  margin: auto;
  text-align: center;
}
img, footer {
  width: 100%;
}
html {
  height: 100%;
}
p {
  margin: 0;
}
.img-contr {
  width: 33.333%;
  float: left;
}

/* /////////////////////////// CORE CLASSES ////////////////////// */
.clr-fix::after {
  content: "";
  display: block;
  clear: both;
}
.v-cntr {
  position: relative;
  top: 50%;
  transform: translateY( -50% );
}

footer

EDIT So I a made gif showing exactly what I want to accomplish. But I made it by screenshotting my website and making the whole thing an image. The goal is to do this with multiple images inside divs like inside my code. Here is what I want to accomplish:

This question: Vertically center image on page and maintain aspect ratio on resize
is a solution for one image. When I try it in my code the images scale but they separate. Setting every image to max-height: 100% doesn't solve at all.

A: Ok. So with the help of vmin units and aspect ratio media queries I was able to put together something that reflects what works best for me as a solution to this question:

/* ///////////////////////////////// IMPORTS /////////////////////////////// */
@import url( "https://necolas.github.io/normalize.css/latest/normalize.css" );

/* ///////////////////////////////// INITIAL /////////////////////////////// */
* {
  box-sizing: border-box;
  overflow: hidden;
}
html {
  height: 100%;
  background-color: #fff;
}
html, body {
  padding: 0.5%;
}
body {
  max-width: 1000px;
  background-color: #eee;
}
body, .top-contr {
  margin: auto;
}
p {
  margin: 0;
  padding: 0;
  text-align: center;
  color: #aaa;
}

/* ///////////////////////////////// STRUCTURE ///////////////////////////// */

/* / / / / / / / / / / / / / / / / / / HEADER / / / / / / / / / / / / / / / /*/
header, footer, main .top-contr {
  padding: 1%;
}
header .top-contr {
  background-color: #ddd;
  padding: 15%;
}
.top-contr, .v-cntr, .v-cntr-a {
  position: relative;
}
.cnt {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

/* / / / / / / / / / / / / / / / / / / MAIN / / / / / / / / / / / / / / / / /*/
main .top-contr {
  width: 33.333%;
  float: left;
}
main .mid-contr {
  background-color: #ccc;
  padding: 45%;
}
main .cnt {
  padding: 4%;
}

/* / / / / / / / / / / / / / / / / / / FOOTER / / / / / / / / / / / / / / / /*/
footer .top-contr {
  background-color: #bbb;
  padding: 5%;
}

/* //////////////////////////////// CORE CLASSES /////////////////////////// */
.clr-fix::after {
  content: "";
  display: block;
  clear: both;
}
.v-cntr {
  top: 50%;
  transform: translateY( -50% );
}

/* /////////////////////////////// MEDIA QUERIES /////////////////////////// */
@media ( min-aspect-ratio: 3/2 ) {
  body {
    width: 135vmin;
    height: 100vmin;
  }
}
@media ( min-aspect-ratio: 3/2 ) and ( min-width: 1000px ) {
  .v-cntr-a {
    top: 50%;
    transform: translateY( -50% );
  }
}

header

rectangle 1

rectangle 2

rectangle 3

footer

Aslo see accepted answer here: https://stackoverflow.com/questions/42757168/how-to-keep-aspect-ratio-on-a-vertically-scaling-div-not-image?noredirect=1&lq=1


text:
Q: run synchronouse function in a promise I am new to JS and async operations. In a router of nodeJS using express, I have aggregated some data from mongo using mongoose. The data is weather data collected from different sites every 15 minutes interval. I processed the data with mongoose aggregate pipeline to get hourly data and group by each site. But the data needs a further process to get periods where for example relative humidity over 90% and assign scores to each period so I wrote some synchronous functions that target each site (each geojson object).
Mongoose looks something like that:
module.exports.filteredData = function (collection, dateInput) {
return collection.aggregate([

    {
        $addFields :{
            DateObj: {
                $dateFromString: {
                    dateString: "$DateTime",
                    format: '%Y-%m-%d'
                }
            },
        }
    },

    {
        $addFields :{
            NewDateTimes: {
                $dateFromParts:{
                    'year': {$year: '$DateObj'},
                    'month':{$month: '$DateObj'},
                    'day':{$dayOfMonth: '$DateObj'},
                    'hour': {$toInt: "$Time"}
                }
            }
        }
    }

...

synchronouse functions:
const calcDSV = function(featuresJSON){

    // featuresJSON
    const SVscore = [];
    const tuEval = featuresJSON.features.properties.TU90; // array
    const obArr = featuresJSON.features.properties.OB; // array
    const periodObj =  getPeriods(tuEval);// get period position
    const paramObj =  getParams(periodObj, obArr); // get parameters
    const periodDate =   getPeriodDate(featuresJSON, periodObj);
    const removeTime =  periodDate.beginDate.map(x=>x.split('T')[0]);

    let hourly = paramObj.hourCounts;
    let avgTemps = paramObj.avgTemps;

    for(let i = 0;i<hourly.length; i++){

        let score =  assignScore(avgTemps[i], hourly[i]);
        SVscore.push(score);

    }

    // output sv score for date

    const aggreScore =  accumScore(removeTime, SVscore);

    aggreScore.DSVdate = aggreScore.Date.map(x=>new Date(x));

    featuresJSON.features.properties.periodSV = SVscore;
    featuresJSON.features.properties.Periods = periodDate;
    featuresJSON.features.properties.DSVscore = aggreScore;

    return  featuresJSON;

}

Now I am stuck on how to apply those function on each site return by the mongoose aggregate pipeline on a post request:
router.post('/form1', (req, res, next)=>{

const emdate = new Date(req.body.emdate);
const address = req.body.address;
const stationDataCursor = stationData.filteredData(instantData, emdate);

stationDataCursor.toArray((err, result)=>{
    if(err){
        res.status(400).send("An error occurred in Data aggregation")
    };

    res.json(result.map(x=>calcDSV.calcDSV(x)));

})

});

I tried in the callback:
stationDataCursor.toArray((err, result)=>{
    if(err){
        res.status(400).send("An error occurred in Data aggregation")
    };

    res.json(result.map(async (x)=>await calcDSV.calcDSV(x))));

})

and using then():
stationDataCursor.toArray().then((docArr)=>{

    let newfeature = await docArr.map(async (x)=> await calcDSV.calcDSV(x))));

    res.json(newfeature);

})

or make calcDSV() returns new promise
    return  new Promise((rej, res)=>{
            resolve(featuresJSON);
     })

I would expect to see all sites with a new feature added in the HTTP response output. But most of the time, I got ReferenceError: error is not defined.

A: I think I have figured it out:

*

*after all, have to make all synchronous functions asynchronous by prepending async to those functions;

*rewrite this part in the post router function, especially the array map part. I read from this. and in the map() gonna have try...catch... in it, otherwise it won't work.
await stationDataCursor.toArray().then(async (docArr)=>{

        const newfeature = await Promise.all(docArr.map(async function(x){
            try{
                const feature = await calcDSV.calcDSV(x);

                return feature
            } catch(err){
                console.log("Error happened!!! ", err);

            }

        }));

        res.json(newfeature)

})

Hope it helps.


text:
Q: How to add whitelisted domains when using Safari Content blocker in the iPhone What's the proper way to create whitelists when using Safari content blocker API?
https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ContentBlocker.html
Imagine I have an adult content blocker like this one, but instead of 3 domains, 50000. (I already did it and it works)
[
    {
        "action": {
            "type": "block"
        },
        "trigger": {
            "url-filter": ".*",
            "if-domain": ["*xvideos.com", "*pornhub.com", "*xxx.com"]
        }
    }
]

How should I add a whitelist?
Do I have to create a second blocker with other rules or do I have to modify my adult content blocker to remove the whitelisted domains programmatically in real time, generate another JSON and reloading it?

A: You start by blocking everything:
{
    "action": {
        "type": "block"
    },
        "trigger": {
        "url-filter": ".*"
    }
}

than you whitelist (for example) the website "Google.com":
{
    "action": {
        "type": "ignore-previous-rules"
    },
    "trigger": {
        "url-filter": "Google.com/.*"
    }
}

Here I approve "Google.com" and everything down his hierarchy, for example "Google.com/shop" or "Google.com/account".
Edit:
it seems I was wrong, and not the first one to fall into it, to white list a website, This is how it's done:
{
    "trigger": {
        "url-filter": ".*",
        "if-domain": ["Google.com"]
    },
    "action": {
        "type": "ignore-previous-rules"
    }
}

You can see full list of commands here:
https://developer.apple.com/documentation/safariservices/creating_a_content_blocker
Also check this question:
iOS Content Blocker Whitelist Website


text:
Q: Mann-Kendall trend test minimum lenght of the time-series What is the minimum length of a time-series for considering the results of the Mann-Kendall trend test "coherent"?

A: The Mann-Kendall function in R requires at least 3 data points. Look here: Mann-Kendall test in R using 'Kendall' package: exact test or approximation?


text:
Q: My laptop shuts down on hdmi during video games and 60fps videos First of all, sorry for my English here is my problem:
I have an old Asus laptop and i don't have a battery. My laptop is 8 years old, i'm using this computer with a monitor with HDMI connection, whenever i try to play a game or do anything that will force the ram my computer shuts down, this problem does not occur without the HDMI connection, is this happening because i don't have a battery? I googled this issue and tried few solutions but they don't work.
Please help me.


text:
Q: Is there a way to `apply` a function to one column of a dataframe while leaving the other columns fixed? Basically I'm wondering if there's a more "Pandathonic" way of expressing this:
df.apply(lambda col: myfunc(col) if col == "mycol" else col)

Something like
df.apply(myfunc, subset = ["mycol"])

is the kind of thing I have in mind.
The reason is that I'm trying avoid doing this:
df['mycol']=myfunc(df['mycol'])

as I'm on a functional programming kick at the moment and I want my code to eschew side-effects.

A: In pandas 0.16 or later, you can use DataFrame.assign, which returns a new DataFrame with whatever assignments you tell it to do, but doesn't modify the original:
>>> d = pandas.DataFrame({"A": [1, 2, 3], "B": [8, 88, 888]})
>>> d
   A    B
0  1    8
1  2   88
2  3  888
>>> d.assign(A=d.A**2)
   A    B
0  1    8
1  4   88
2  9  888
>>> d
   A    B
0  1    8
1  2   88
2  3  888


text:
Q: Err.Number not populating for 'Excel Ran Out of Resources' error I've developed a program using Excel VBA which occasionally causes an 'Excel Ran Out of Resources' error.
Closing the file, reopening, and rerunning the macro always fixes whatever issue created the error.  I know that preventing the error in the first place is best practice, but am resigned to believe that it's unavoidable.
So, I would like to alert the user of the error, instead of Excel doing it, and perform some actions once the error has been detected.  The problem is that I can't get VBA to recognize the error using the On Error GoTo ErrorHandler routine or the Err.Number property.  I never get to the msgbox below:
My code is as follows:
Sub test()

On Error GoTo ErrorHandler

    Calculate

ProcedureDone:
    Exit Sub

ErrorHandler:
    MsgBox "Error", vbOKOnly, "Oops"
    Resume ProcedureDone

End Sub

Any insight would be fantastic since I've been searching for several days and haven't been able to find a work around.

A: I just happened to run across another issue that sounds like yours.
The point from the other thread is that Excel does not treat these application method results as VBA errors. Rather, they are Excel alerts, and they can be suppressed but not trapped in VBA as errors.
The way I interpret this is that when you execute certain application methods from VBA, it does not raise errors that VBA can trap. Rather, Excel interacts with the user as if the user had issued a GUI command. On the other hand, if an application method is designed to interact with VBA (e.g., if it returns a value), then VBA might be able to handle its errors.
This is distinct from the way VBA handles worksheet functions rather than application methods. VBA can intercept errors raised by worksheet functions, as noted in "Error Handling With Worksheet Functions" here.
I realize this does not solve your problem, but it gives you an idea of why.


text:
Q: The Maximum Principle and Some Notation I am working on this question:

Suppose that $\Delta u\leqslant0$ in $\Omega$ and $u=f$ on $\partial\Omega$, and $\Delta v\leqslant0$ in $\Omega$ and $v=f$ on $\partial\Omega$. Prove that $v(x)\leqslant u(x)$ for $x\in\Omega$ using the maximum principle.

I do not want an answer to it. The context of it is partial differential equations, and I do not know what the symbols mean.
I assume that
$$\Delta=\nabla^2=\frac{\partial}{\partial x}+\frac{\partial}{\partial y}+\frac{\partial}{\partial z}$$
is the Laplace operator, $\Omega$ is some subset of $\mathbb{R}^3$, and I have no clue what $\partial\Omega$ is; maybe it is the surface of $\Omega$? Also, how could I go about answering this question? I mean, I am thinking in terms of three dimensions, but both $u$ and $v$ are functions of one variable.
I am so confused!


text:
Q: Re-Direct To Webpage After Facebook Comment Is Placed I am planning on installing the Facebook Comments module/plugin on a web page, let's say:
http://www.example.com/
Is it possible to re-direct users to another landing page within the site?  Let's say I want to send them here after clicking to post the comment:
http://www.example.com/landing-page/
Is this possible with either Facebook API or another script?

A: You can subscribe to the comment.create event which fires when a user adds a comment like this:
Init

And in your fb comment you must set notify="true" like so
<fb:comments numposts="10" notify="true"></fb:comments>


text:
Q: PowerShell to find all empty AD Security Groups with no Members OR Computer Objects I am currently running this script:
Get-ADGroup -Filter {GroupCategory -eq 'Security'} | ?{@(Get-ADGroupMember $_).Length -eq 0} | Export-Csv -Path "C:\Users\177626\EmptySG.csv"
It technically is working by pulling all of the Security Groups without members but it is still pulling groups that have Computer Objects in the Members list. Is there anyway to modify this to filter out those groups that have those Computer Objects in them?
Thanks!

A: You can tell Get-ADGroup to provide more than just the default attributes. One of them is "Members". You can use the property .count to determine if the group is empty or not.
Get-ADGroup -Filter "GroupCategory -eq 'Security'" -Properties Members |
    Where-Object {$_.Members.count -eq 0}


text:
Q: R- How to get locations/positions of elements of a vector that satisfies given conditions? I am using R studio with R 3.1.2 on Mac ox X 10.10.3, i need to get positon of elments in a vector when it is given some conditions.
Let x be a sample of 100 elements and y is equals to 100.
How to get a vector stating positions of elements of x, for which  x >y
I have tried functions like match, replace and %in%, but not much success. Either i am missing something oe doing it all wrong.
Thanks and Regards.

A: If you need the first position where x >y, try which.max
which.max(x>y)
#[1] 6

It could be also done with which
 which(x >y)[1]
 #[1] 6

data
set.seed(24)
x <- sample(1:140, 100, replace=TRUE)
y <- 100


text:
Q: CMake: Compiler could not be found on Windows When I run this : cmake -G "Visual Studio 15 2017 Win64"
I have this output :
-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
CMake Error at CMakeLists.txt:2 (project):
  No CMAKE_C_COMPILER could be found.

CMake Error at CMakeLists.txt:2 (project):
  No CMAKE_CXX_COMPILER could be found.

-- Configuring incomplete, errors occurred!
See also "C:/Users/ce/type/CMakeFiles/CMakeOutput.log".
See also "C:/Users/ce/type/CMakeFiles/CMakeError.log".

This is my CMakeLists (I have deleted the useless stuff for the exemple)
cmake_minimum_required(VERSION 3.4)
project(type)

option(BUILD_CLIENT "Build Client" ON)
option(BUILD_SERVER "Build Server" ON)

set(CLIENT_NAME "type_client")
set(SERVER_NAME "type_server")

set(CLIENT_SRCDIR "client/src/")
set(SERVER_SRCDIR "server/src/")

set(INC_DIR_CLIENT "client/includes")
set(INC_DIR_SERVER "server/includes")
set(INC_DIR_DLLOADER "DLLoader/")
set(INC_DIR_ECS "ecs/")
set(INC_DIR_PROTOCOL "protocol/")

set(LIB_LINKS "-ldl -lpthread")

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")

set(CLIENT_SOURCE_FILES
        ${CLIENT_SRCDIR}main.cpp)

set(SERVER_SOURCE_FILES
        ${SERVER_SRCDIR}main.cpp)

set(SERVER_SOURCE_FILES_SYSTEMS)

set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH})
if(WIN32)
    set(SFML_ROOT "dependancies/windows/SFML-2.4.1")
elseif(UNIX)
    set(SFML_ROOT "dependancies/linux/SFML-2.4.1")
endif()
find_package(SFML 2 REQUIRED system window graphics network audio)

install(TARGETS ${EXECUTABLE_NAME} DESTINATION bin)

if(WIN32)
    include_directories(${INC_DIR_DLLOADER}/win)
elseif(UNIX)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
    include_directories(${INC_DIR_DLLOADER}/linux)

    set(SFML_ROOT "dependancies/SFML-2.4.1")
endif()

include_directories(${SFML_INCLUDE_DIR})

if(BUILD_CLIENT)
  add_executable(${CLIENT_NAME} ${CLIENT_SOURCE_FILES})
  target_link_libraries(${CLIENT_NAME} ${SFML_LIBRARIES} ${LIB_LINKS})
endif()

if(BUILD_SERVER)
    if(WIN32)
        add_executable(${SERVER_NAME} ${SERVER_SOURCE_FILES}
                ${SERVER_SOURCE_FILES_SYSTEMS} ${SERVER_SOURCE_FILES_WIN})
        target_link_libraries(${SERVER_NAME} -lws2_32)

    elseif(UNIX)
        add_executable(${SERVER_NAME} ${SERVER_SOURCE_FILES}
                ${SERVER_SOURCE_FILES_SYSTEMS} ${SERVER_SOURCE_FILES_LINUX})
        target_link_libraries(${SERVER_NAME} ${LIB_LINKS})
    endif()
endif()

I installed the C++ compiler with Visual Studio, so I don't understand why the compiler is not detected.

A: Try to compile with cmake -G "Visual Studio 14 2015"


text:
Q: Why is swift's JSONDecoder.decode(_:from:) taking 10-15 seconds for just 1mb data? I'm using swift's JSONDecoder to decode a JSON data of about 1mb. My JSON has a bunch of nested objects.
I'm decoding using init(from decoder:) to decode my JSON data. The issue is that it takes about 10-15 seconds to decode the JSON only after the API call returns with a success response. Why is this happening(the size of my data is not that large)?
Also, how can I reduce this time?
I'm testing on an iPhone 6 and on the Xcode simulator.
The API call takes about 1-2 seconds to get the JSON.
I'm using Moya here's a sample of my api call:
API.provider.request(API.getDetails(id: courseID), completion:  { [weak self] result in
        switch result {
        case .success(let response):
            do {
                var results = try JSONDecoder().decode(MiniDetailApiResponse.self, from: response.data)
                delegate?.success(results)
              }catch{
                 delegate?.failure()
              }
}

A: Decoding from JSON probably isn't taking that long, unless you're doing something very interesting in custom init(from: Decoder), but you haven't included anything from MinDetailApiResponse in your question so it's hard to tell.
If your 10-15 seconds figure is derived from you waiting for something to change on the screen, then the most likely cause is that the API request call above isn't being called on the main thread, which often reveals itself as a long delay to UI updates.
Put a breakpoint on var results = try... above, and when it gets hit, look in the debug navigator - are you on the main thread?

If not, you should call your delegate method on the main thread:
DispatchQueue.main.async { delegate?.success(results) }


text:
Q: How to know the image dimensions in pixels to fit all screens I'm working on a react native application in a company and my manager asked me what is the best image size in pexels to upload from API (dashboard) to fit the View in the application ?
And I'm using percentage units not numbers: (width: '80%', height: '50%') I don't know what is the best sized of images to fit or the aspect ratio of the image and react native is unitless!
What should we add 'Hint' for the client in the dashboard when he upload any image ?
Or how could I know the best image dimensions to fit all screens ?

A: In case the app target both iOS and Android, there is a multitude of devices with various resolutions and pixel densities from high-end iPads to low-end androids devices with smaller resolutions.
The General rule of thumb is to find the average image size which will not pixelated (look blurry) on the high-end devices but does not have a large download size in case some users will have slow internet.
You should start with 1024 x 768 pixels which is a standard dimension for iPad

A: Consider using resizeMode prop of react native image. With resizeMode you can manage to render image based on available space in screen.
Check it here : https://reactnative.dev/docs/image#resizemode

A: In our organisation, we usually follow the following convensions to make an image fully responsive.

*

*Get the dimentions of the image using: const {width, height} = Image.resolveAssetSource('path-to-your-image');

*Get the ratio factor of width and height by using: const ratioFactor = height/width;

*Whenever you set the width of your screen by 'n' digit, set the height to 'n*ratioFactor'

*In this ways the image can never be stretched or compressed. It will be fully responsive according to it's dimensions.

*Preferably use image with standard dimentions as 1024 x 768 pixels.


text:
Q: CodeIgniter4 - Redirect with data I try to do this redirect in controller:
$this->getSession()->setFlashdata("error_controller", "Incorrect email or password");
return redirect()->route("login");

and this is in view:
<?php
    if($error_controller){
        echo "
" . $error_controller . "
";
    }else{
        echo "no-no";
    }
?>

In browser is printed no-no, which that means error_controller from flashdata not arrives to view.
How to redirect to login route with data?

A: Add this code in the Controller
session()->setFlashData("error_controller","Incorrect email or password");

return redirect()->to(base_url('/login'));

Add this code inside the view file
 <?php

if(session()->has('error_controller'))
  echo "
" . session()->getFlashdata('error_controller') . "
";
    }else{
        echo "no-no";
    }
?>

A: I tried this way and it worked:
In Controller:
$validate = $this->validate([
   'firstname' => 'required',
   'lastname'  => 'required',
   'email'     => 'required|valid_email|is_unique[users.email]',
]);

Then I passed errors as array in view (in controller)
$data['validation'] = $this->validator;
return view( 'view_file', $data );

Then in View File:
<?= form_open(....) ?>
  <input type="text" name="firstname" class="form-control" placeholder="Firstname">
  <?= ( isset($validation) && $validation->hasError('firstname')) ? $validation->getError('firstname'): ''; ?>
<?= form_close() ?>


text:
Q: Почему нельзя использовать инкрементный подход к созданию методов при множественном наследовании?
SingingWaiter порожден от классов Waiter и Singer, которые порождены от класса Worker(вот такой ромбик получается).

Написанное в книге на этих фото мне кажется чем-то очень нелогичным(бредом короче), поэтому я решил написать тестовый код и проверить все сам:
#include <iostream>
#include <cstring>
#include <new>
int main(int argc, char const *argv[])
{
    using namespace std;
    class a
    {
    public:
        void show() {std::cout<<"i am an A!\n";}
    };

    class b : virtual public a
    {
    public:
        void show() {a::show(); std::cout<<"i am an B!\n";}
    };

    class c : virtual public a
    {
    public:
        void show() {a::show(); std::cout<<"i am an C!\n";}
    };

    class d : public b, public c
    {
     public:
        void show() {b::show(); std::cout<<"i am an C!\n";}
    };

    return 0;
}

Если утверждения в книге верны, то класс d не должен давать возможности скомпилироваться программе, ведь в нем вызывается только метод b::show(), а должно вызываться два метода - b::show() и c::show().  НО, программа компилируется на разных компиляторах(clang, g++). Можете сами проверить. Что я неправильно понял?

A: Вы неправильно поняли слово "сбой".
Речь не о проблеме компиляции, а том что логика программы будет неправильная. Два раза вызывается метод из базового класса.
В этом примере это печать на экран два раза, но представьте, что это снятие денег со счета, а не печать.


text:
Q: Configure AWS cognito for federated sign-in to get authenticated through microsoft account (live.com) I'm trying to configure my AWS cognito User pool for federated sign-in for microsoft users. I've followed this article.
https://aws.amazon.com/blogs/security/how-to-set-up-amazon-cognito-for-federated-authentication-using-azure-ad/
This authentication flow is working only for the users who are associated with specific enterprise application created inside Azure AD. I have multiple clients who are having their own Azure AD instances for maintaining their users and handling authentication. I need to onboard those users in my application using federated sign-in. Hence I'm trying to give a generic button to end users to Login with Microsoft. Can someone please suggest the direction?


text:
Q: BASH loop to change data from 1 csv from other csv trying to change the value of a column based on other column in other csv
so let's say we have a CSV_1 that states with over 1000 lines with 3 columns
shape   Color    size
round      2      big
triangle   1      small
square     3      medium

then we have a CSV2 that has only 10 with the following information
color
1 REd
2 Blue
3 Yellow
etc

now i want to change the value in column color in CSV_1 with the name of the color of CSV2
so in other words .. something like
for (i=0; i<column.color(csv1); i++) {
if color.csv1=1; then
subustite with color.csv2=1  }

so that loop iterates in all CSV1 Color column and changes the value with the values from CSV2

A: An explicit loop for this would be very slow in bash. Use a command that does the line-wise processing for you.
sed 's/abc/xyz/' searches abc in each line and replaces it by xyz. Use this to search and replace the numbers in your 2nd column by the names from your 2nd file. The sed command can be automatically generated from the 2nd file using another sed command:
The following script assumes a CSV file without spaces around the delimiting ,.
sed -E "$(sed -E '1d;s#^([^,]*),(.*)#s/^([^,]*,)\1,/\\1\2,/#' 2.csv)" 1.csv

Interactive Example
$ cat 1.csv
shape,Color,size
round,2,big
triangle,1,small
square,3,medium
$ cat 2.csv
color
1,REd
2,Blue
3,Yellow
$ sed -E "$(sed -E '1d;s#^([^,]*),(.*)#s/^([^,]*,)\1,/\\1\2,/#' 2.csv)" 1.csv
shape,Color,size
round,Blue,big
triangle,REd,small
square,Yellow,medium

A: Here is one approach, with mapfile which is a bash4+ feature and some common utilities in linux/unix.
Assuming both files are delimited with a comma ,
#!/usr/bin/env bash

mapfile -t colors_csv2 < csv2.csv

head -n1 csv1.csv

while IFS=, read -r shape_csv1 color_csv1 size_csv1; do
  for color_csv2 in "${colors_csv2[@]:1}"; do
    if [[ $color_csv1 == ${color_csv2%,*} ]]; then
      printf '%s,%s,%s\n' "$shape_csv1" "${color_csv2#*,}" "$size_csv1"
    fi
  done
done < <(tail -n +2 csv1.csv)

Would be very slow on large set of data/files.

If ed is available acceptable, with the bash shell.
#!/usr/bin/env bash

ed -s csv1.csv < <(
  printf '%s\n' '1d' $'g|.|s|,|/|\\\ns|^|,s/|\\\ns|$|/|' '$a' ',p' 'Q' . ,p |
  ed -s csv2.csv
)

A: To add to @Jetchisel interesting answer, here is an old bash way to achieve that. It should work with bash release 2 as it supports escape literals, indexed array, string expansion,  indirect variable references. It implies that color keys in csv2.csv will always be a numeric value. Add shopt -s compat31 at the beginning to test it in the 'old way' with a recent bash. You can also replace declare -a csv2 with a Bash 4+ declare -A csv2 for an associative array, in which case the key can be anything.
#!/bin/bash
declare -a csv2
esc=$'\x1B'
while read -r colors; do
   if [ "${colors}" ] ; then
     colors="${colors// /${esc}}"
     set ${colors//,/ }
     if [ "$1" ] ; then
       csv2["$1"]="$2"
     fi
   fi
done < csv2.csv
while read -r output; do
   if [ "${output}" ] ; then
     outputfilter="${output// /${esc}}"
     set ${outputfilter//,/ }
     if [ "$2" ] ; then
       color="${csv2["$2"]}"
       [ "${color}" ] && { tmp="$1,${color},$3";output="${tmp//${esc}/ }"; };
     fi
     echo "${output}"
   fi
done < csv1.csv


text:
Q: Complex notification system We're building a web application to monitor industrial facilities, and we need to add a module to notify the users when certain things happen in the system.
We get data (lots of data) from the facility machines as 10 minutes data series (a value each 10 minutes, like machine's components temperatures, output performance, power consumption, etc), and we store the data in a cassandra DB. The framework used is Django.
These are the kind of things that we need to notify (and we need to emit the notification when the event happens, so no batch processing):

*

*When a machine has been under 90% of its theoretical performance for 60 minutes in a row (i.e. 6 rows of 10-min data), but not if the machine has been manually stopped.

*When the whole facility has been under 95% of it theoretical performance for two hours in a row.

*When a machine is manually stopped.

*When the monthly production reaches 50% of the expected.

*Etc, etc.
The details of the notification (percentages, time spans, etc) should be configurable per user.
We are looking for a design as generic as posible, because the list of available notifications will grow in the future. Has somebody dealed with a similar problem? How did you deal with it?
I'm just looking for general tips on how to design this, that's why I'm not giving too much specifics.
UPDATE
I'm asking for help on how to design the general system. The problem is how to define the rules for each notification, given that I must keep an eye on the evolution on the data (the notification isn't defined as "something happened", but as "something happened and kept happening for X time in a row".
The main questions are:

*

*How should I store the rules of the notifications?

*How should I check if a new notification must be sent to the user? Querying the database each time I insert data, or is there a more elegant way? Should I keep the state of each possible positive until it becomes an actual notification, or that's an overkill?
Please don't focus on the user settings or if the events should be notified by email or pushed to a mobile app, that's not important :-)

A: So, I'll say up front it seems like you may have gone down the "Let's build it from scratch" path without doing sufficient research.  The kind of system you want exists in a lot of places, many of which aren't even requiring you to pay.
My favorite tool for this kind of problem is the Elastic Stack.  It's highly flexible and highly scalable for taking in a ton of events with low latency, parsing them and indexing them.  There are all kinds of outputs that you can configure to include notifications.
There's even a specific article they publish on doing alerts and notifications based on complex events..

A: I would do the following:

*

*Create a language for the rules. This does not mean you must create a text based language, with a parser. It means you think about the operators needed to compose rules (they are composite objects), as well as the terminals (leaf nodes of expressions), and create a library that contains an object for each component of the language. Now you can compose rules.

*Rules need an evaluate or execute method that traverses the object tree and determines if a notification is in order. The simplest is a method that returns a boolean.

*Rules need to be persisted using your favorite technique. I would use binary persistence, but you can use whatever you fancy.

*I would keep the rules in memory in a server process. I would keep the smaller bits of input data (data supplied to rule evaluator via a context object) in memory as possible as well.

*If you have much real-time data, I assume you have thought about performance already. If not, consider simple binary streams in a file system; whatever you do, don't do the equivalent of a row in a database per incremental bit of data coming in.

*The incoming data is probably read-only so you can get away with creating new files per chunk of data, and cleaning them periodically with a garbage collector.

*If you are concerned about the overhead of evaluating all rules each time you get new data, you could keep a list of input data used by each rule at the root node of the rule, computed once after rule creation. Use that to determine which rules are affected.

Of course there are lots of optimization strategies; measure before optimizing anything.


text:
Q: Is there any way to create 3D environment with navtive mobile development like Zepeto? I am looking for a way to insert a mini game feature in my app.
And I found this.
https://developer.android.com/games/guides
But It says about implementing games with the engines like defold, godot, unity, unreal.
I am an Android Developer who uses Kotlin. Someone needs to make a game and export it and import it to Android Studio project. So, I can't make the games and maintain the source code. So, This document isn't helpful.
And I found rive app. It's like lottie but can add some events and listeners with number or boolean conditions. It has State Machine that can connect the native app and interact between the rive animation and the native app. That's it. And It doesn't support everything like normal game engines do. I need to make timelines to create animations and no sound, etc.
I tried to find better way to implement an app like miniapp. And I've found Zepeto. it uses a lot of 3D animations. It uses Jetpack compose. That's very interesting point. How can I implement 3D modelings with native app? Is there any way to create 3D animation and the virtual environment like Zepeto?


text:
Q: onClickListener parameter casted to a textview I am trying to make the onClickListener parameter, for example:
public void onClick(View v){}

v, to be casted to a TextView and set the text to this x textView, but I cannot specify the textView because I want it to be a different one each time the onClick is triggered. Basically I want to setText for the parameter:
(TextView) v.setText("");

And the problem is that the setText() method cannot be used this way, so is there any way I can do this? Sorry if I did not explain well and thanks in forward.

A: Try
((TextView) v).setText("");

A: Your casting is wrong, If that view is TextView, you should cast TextView like ((TextView) v) and then you can do any operation.
Ex:  ((TextView) v).setText("");


text:
Q: C# memory usage How I can get the actual memory used in my C# application?

*

*Task Manager shows different metrics.

*Process Explorer shows increased usage of private bytes.

*Performance counter (perfmon.msc) showed different metrics

*when I used .NET memory profiler, it showed most of the memory is garbage collected and only few Live bytes.

I do not know which to believe.

A: If you are using VS 2010 you can use Visual Studio 2010 Profiler.
This tool can create very informative reports for you.

A: If you want to know approximately how many bytes are allocated on the GC heap (ignoring memory used by the runtime, the JIT compiler, etc.), you can call GC.GetTotalMemory. We've used this when tracking down memory leaks.

A: Memory usage is somewhat more complicated than displaying a single number or two. I suggest you take a look at Mark Russinovich's excellent post on the different kinds of counters in Windows.
.NET only complicates matters further. A .NET process is just another Windows process, so obviously it will have all the regular metrics, but in addition to that the CLR acts as a memory manager for the managed application. So depending on the point of view these numbers will vary.
The CLR effectively allocates and frees virtual memory in big chunks on behalf of the .NET application and then hands out bits of memory to the application as needed. So while your application may use very little memory at a given point in time this memory may or may not have been released to the OS.
On top of that the CLR itself uses memory to load IL, compile IL to native code, store all the type information and so forth. All of this adds to the memory footprint of the process.
If you want to know how much memory your managed application uses for data, the Bytes in all heaps counter is useful. Private bytes may be used as a somewhat rough estimate for the application's memory usage on the process level.
You may also want to check out these related questions:
Reducing memory usage of .NET applications?
How to detect where a Memory Leak is?

A: Download VADump (If you do not have it yet)
Usage: VADUMP.EXE -sop [PID]

A: Well, what is "actual memory used in my C# application" ?
Thanks to Virtual memory and (several) Memory management layers in Windows and the CLR, this is a rather complicated question.
From the sources you mention the CLR profiler will give you the most detailed breakdown, I would call that the most accurate.
But there is no 'single number' answer, the question whether Application A use more or less memory than B can be impossible to answer.
So what do you actually want to know?  Do you have a concrete performance problem to solve?


text:
Q: Wein's Displacement Law for Light Bulbs? I know Wein's Law $\lambda_{max}=\frac{b}{T}$ works for ideal black bodies. I have some clear glass incandescent light bulbs which have Tungsten as a filament. Would Wein's Law of displacement be a close enough approximation for these light bulbs in order for me to figure out the temperature of the filament?
If there are any definitive resources, I would love to read them!
Edit: I have access to a spectrometer, so I can find out their peak wavelength.

A: This is obviously a well researched subject. The short answer is that using Wein's law as is will result in a significant error, i.e., for, a tungsten filament, the black body approximation does not work very well.
This is mostly due to the uncertainty of the tungsten filament emissivity, which directly affects the relationship between the surface temperature of a filament and its thermal radiation spectrum.
The emissivity of a black body is defined as unity. The radiation spectrum of a surface with the emissivity lower than unity will be generally red shifted relative to the spectrum of a black body at the same temperature, so, if we apply Wein's law to calculate the temperature of the surface based on the peak of the specral curve, the surface will appear to be cooler than it actually is.
According to this article by FAR Associates, the emissivity of tungsten filaments, among other factors, may depend on the temperature and the wavelength and, in addition, it changes with time. For example, here is a chart from the article showing wavelength dependency of tungsten emissivity measured in multiple experiments under various conditions:

As can be seen from the chart, the emissivity of tungsten is all over the place.
Incidentally, the article talks about a multiwavelength pyrometer, FARS SpectroPyrometer, which presumably can measure the temperature of tungsten filaments pretty accurately, by analyzing the spectrum at many different wavelengths and inferring the temperature by comparing the results.


text:
Q: Merging two sorted arrays in python I am trying to merge two sorted arrays recursively, and I can merge the first few numbers until one pointer exits the array. There seems to be some problem with the base case not getting executed. I  have tried to print the new_arr with the pointers for each recursive call to debug but cannot seem to find a solution. Here is my code:
new_arr= []
i= 0
j=0
def merge(arr1, arr2, i, j):
    #base case
    ##when arr1 pointer exits
    print(i,j, new_arr)
    if(i>len(arr1)-1):
        new_arr.append(arr2[j:])
        return new_arr
    ##when arr2 pointer exits
    if (j > len(arr2)-1):
        new_arr.append(arr1[i:])
        return new_arr

    if(arr1[i]<arr2[j]):
        new_arr.append(arr1[i])
        i+=1
        merge(arr1, arr2, i, j)
    elif(arr1[i]>=arr2[j]):
        new_arr.append(arr2[j])
        j+=1
        merge(arr1, arr2, i, j)
sortedarr = merge([1,9], [3,7,11,14,18,99], i, j)
print(sortedarr)

and here goes my output:
0 0 []
1 0 [1]
1 1 [1, 3]
1 2 [1, 3, 7]
2 2 [1, 3, 7, 9]
None

A: These are the issues:

*

*new_arr.append(arr2[j:]) should be new_arr.extend(arr2[j:]). append is for appending one item to the list, while extend concatenates a second list to the first. The same change needs to happen in the second case.

*As you count on getting the mutated list as a returned value, you should not discard the list that is returned by the recursive call. You should return it back to the caller, until the first caller gets it.

*It is a bad idea to have new_arr a global value. If the main program would call the function a second time for some other input, new_arr will still have its previous values, polluting the result of the next call.
Although the first two fixes will make your function work (for a single test), the last issue would best be fixed by using a different pattern:
Let the recursive call return the list that merges the values that still needed to be analysed, i.e. from i and j onwards. The caller is then responsible of prepending its own value to that returned (partial) list. This way there is no more need of a global variable:
def merge(arr1, arr2, i, j):
    if i >= len(arr1):
        return arr2[j:]
    if j >= len(arr2):
        return arr1[i:]

    if arr1[i] < arr2[j]:
        return [arr1[i]] + merge(arr1, arr2, i + 1, j)
    else:
        return [arr2[j]] + merge(arr1, arr2, i, j + 1)

sortedarr = merge([1,9], [3,7,11,14,18,99], i, j)
print(sortedarr)

A: Note that Python already has a built-in function that knows how to merge sorted arrays, heapq.merge.
list(heapq.merge((1, 3, 5,  7), (2, 4, 6, 8)))
[1, 2, 3, 4, 5, 6, 7, 8]


text:
Q: Removing from vowels from a string Here is the code I have:
import string # to import the alphabet <-'abcdefghijklmnopqrstuvwxyz'
alpha = string.lowercase
vowels = "aeiou"
alpha = alpha.strip(vowels)
sentence = "methinks it is like a weasel"
words = sentence.split(" ")
characters = list(sentence)

words
characters
alpha
vowels

when I print I get this:
['methinks', 'it', 'is', 'like', 'a', 'weasel']

['m', 'e', 't', 'h', 'i', 'n', 'k', 's', ' ', 'i', 't', ' ', 'i', 's', ' ', 'l', 'i', 'k', 'e', ' ', 'a', ' ', 'w', 'e', 'a', 's', 'e', 'l']

'bcdefghijklmnopqrstuvwxyz'
'aeiou'

I would like it to remove all vowels from the alphabet, but thus far it is only removing the a (the leading coefficient).

A: [character for character in sentence if character not in vowels] # returns list

This list comprehension should do the trick for you.
The way it works is that it takes advantage of the fact that vowels and sentences are iterables: you can define a for-loop over them, so to speak. Specifically, it pulls every character in sentence, checks if that same character does not appear in vowels, and only then does it insert it into a list.
If you want a string at the end, simply use join:
''.join([character for character in sentence if character not in vowels]) # returns string without vowels

A: I wrote a sample code, hope it helps.
words = ['Ahmad Siavashi', 'Mohammad Siavashi']
print [''.join([c for c in w if c not in 'aeoui']) for w in words]

Output:
['Ahmd Svsh', 'Mhmmd Svsh']

and if you only want for one string, use:
print ''.join([c for c in "methinks it is like a weasel" if c not in 'aeoui'])


text:
Q: Quantum uncertainty affecting classical object? As far as I know, the probability of a quantum object being in a certain position depends on the wave function value for each position. That raises a question:
Is this probability strictly greater than 0 for all points? If I place an electron in a box, it can be anywhere on the box, or anywhere on the universe?
For example, there is always a small possibility of finding a value however far from the mean, while that is not the case for a triangular distribution.
Also, slightly related: Is this property maintained when studying classical objects? Is there any possibility, even if unimaginably small, that all of the particles of a cat will simply move somewhere else at the same time, "teleporting" it?

A: You answer your own question in your first paragraph:

the probability of a quantum object being in a certain position depends on the wave function value for each position

If the value of $|\psi|^2$ is greater than zero there is a probability of detecting the particle. Whether this is the case depends on the potential. For example if the particle is in an infinite potential well then $\psi$ is zero outside the box and there is no probability of detecting the particle outside the box. If the box is not an infinitely deep potential well then there is a probability of detecting the particle outside the box, though this probability rapidly falls to such small values that it is indistinguishable from zero.
To take a real example, for an electron in the ground state of a hydrogen atom the wavefunction is non-zero everywhere so there is in principle a probability of detecting the electron anywhere in the universe.
Re your follow-up question, the issue of to what extent QM applies to macroscopic objects has already been extensively addressed. A quick and far from exhaustive search finds:

*

*Validity of naively computing the de Broglie wavelength of a macroscopic object

*How to prove wave nature of large object?

*Quantum mechanics in macroscopic systems

*Probability, quantum physics, and why (can't it/does it) apply to macroscale events?


text:
Q: Why am I facing PermissionError while installing SpaCy en_core_web_sm on SSH server I am working on a project and have shifted my environment from local windows to a linux server (via SSH). I only have limited access as the host server is from my college, I've installed many packages without issues (both with and without virtualenv). I'm working on Python 3.6.9.
I was able to install spacy and import it but I need to use the en_core_web_sm package which has to be installed additionally using the command python3 -m spacy download en_core_web_sm. However, I consistently face a PermissionError as seen in the logs below.
Why am I facing this error? Is it because I don't have administrator access on the /usr level (refer to last line of logs)? If yes, how come only this package in particular requires a higher level access? If no, are there any workaround for me to install the package, or do I need to contact the server administrator?
jiayi@cdas1:~/adverse_drug_event_extraction/app/preprocessing$ python3 -m spacy download en_core_web_sm
Collecting en-core-web-sm==3.1.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.1.0/en_core_web_sm-3.1.0-py3-none-any.whl#egg=en_core_web_sm==3.1.0
  Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.1.0/en_core_web_sm-3.1.0-py3-none-any.whl (13.6MB)
    100% |████████████████████████████████| 13.6MB 117kB/s
Requirement already satisfied: spacy<3.2.0,>=3.1.0 in /home/jiayi/.local/lib/python3.6/site-packages (from en-core-web-sm==3.1.0)
Requirement already satisfied: pathy>=0.3.5 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: blis<0.8.0,>=0.4.0 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: typer<0.4.0,>=0.3.0 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: jinja2 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: srsly<3.0.0,>=2.4.1 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: spacy-legacy<3.1.0,>=3.0.7 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: requests<3.0.0,>=2.13.0 in /usr/lib/python3/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: pydantic!=1.8,!=1.8.1,<1.9.0,>=1.7.4 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: setuptools in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: catalogue<2.1.0,>=2.0.4 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: packaging>=20.0 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: typing-extensions<4.0.0.0,>=3.7.4; python_version < "3.8" in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: wasabi<1.1.0,>=0.8.1 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: thinc<8.1.0,>=8.0.8 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: numpy>=1.15.0 in /home/jiayi/.local/lib/python3.6/site-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: smart-open<6.0.0,>=5.0.0 in /home/jiayi/.local/lib/python3.6/site-packages (from pathy>=0.3.5->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: dataclasses<1.0,>=0.6; python_version < "3.7" in /home/jiayi/.local/lib/python3.6/site-packages (from pathy>=0.3.5->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: click<7.2.0,>=7.1.1 in /home/jiayi/.local/lib/python3.6/site-packages (from typer<0.4.0,>=0.3.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: MarkupSafe>=2.0 in /home/jiayi/.local/lib/python3.6/site-packages (from jinja2->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: zipp>=0.5; python_version < "3.8" in /home/jiayi/.local/lib/python3.6/site-packages (from catalogue<2.1.0,>=2.0.4->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: pyparsing>=2.0.2 in /home/jiayi/.local/lib/python3.6/site-packages (from packaging>=20.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: contextvars<3,>=2.4; python_version < "3.7" in /home/jiayi/.local/lib/python3.6/site-packages (from thinc<8.1.0,>=8.0.8->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Requirement already satisfied: immutables>=0.9 in /home/jiayi/.local/lib/python3.6/site-packages (from contextvars<3,>=2.4; python_version < "3.7"->thinc<8.1.0,>=8.0.8->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0)
Installing collected packages: en-core-web-sm
Exception:
Traceback (most recent call last):
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "/home/jiayi/.local/lib/python3.6/site-packages/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/usr/lib/python3.6/os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.6/dist-packages/en_core_web_sm-3.1.0.dist-info'

A: As you suspect, this is happening because you don't have permission to install to /usr. Normally pip would install there, but it looks like your pip is basically running with --user, which will install to your user home directory instead.
The spaCy models can't be installed directly via pip because they are large data files, so they can't be hosted on PyPI like ordinary code. An unfortunate side effect of this is that some of the options around pip configuration are ignored.
You can pass extra arguments to the pip install command by appending them to your command, so in your case you can do this:
python3 -m spacy download en_core_web_sm --user

And everything should work.
That said, I would strongly recommend you learn how to use virtual environments with the virtualenv tool, which will make working with Python projects easier and allow to you avoid this problem, as anything you install will just go in the local virtualenv rather than your global pip install.

A: It seems all other packages are installed under your user /home/jiayi/.local/python3.6/lib and this one tries to install itself globally in /usr/local/lib/python3.6/, not sure why. I guess you can give it installation folder or something.
Look here Where does spacy language model download?