text:
Q: how to display all students doing each course I am trying to display the number of students doing each course, but it firstly gives me the right amount when i enter the first course , but when i enter the second course it adds all courses.
the main issue is on case 6: id really appreciate your help. I'm sort of a beginner in programming.
here's the part of code below:
     #include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string>
#include<iomanip>
#include<fstream>
#include<cstring>
#include<vector>
#include<assert.h>

using namespace std;

struct student
{
    char name[80];
    char sname[80];

    int idno;
    char cours[100];
    int age;
    int modules;
};

int main()
{
    ofstream cfile;
    ofstream sfile;
    char dow;
    int arr=0;
    do{

        student stud[100];

        cout<<"Press 1 Enter record \n";
        cout<<"Press 2 Delete record \n";
        cout<<"Press 3 Update record \n";
        cout<<"Press 4 Search record \n";
        cout<<"Press 5 To check number of students doing each course \n";
        cout<<"Press 6 To check student course file \n";
        cout<<"Press 7 Display record \n";
        cout<<"\n\t Select option::";

        int idcheck=0;

        int sw;
        cin>>sw;

        switch(sw)
        {

             case 1:

                cout<<"\n Enter the data of the student no "<<arr+1<<" is :\n";

                cout<<"\t Enter the Roll No = ";
                int id2;
                int id;

                cin>>id;

                for(int j=0; j<=arr; j++)
                {

                    id2=id;
                    if(id2==stud[j].idno)
                    {
                        idcheck=1;
                     }
                 }
                 if(idcheck!=1){
                    stud[arr].idno=id;

                    cout<<"\t Enter the Name = ";
                    cin>>stud[arr].name;

                    cout<<"\t Enter the Surname = ";
                    cin>>stud[arr].sname;

                    cout<<"\t Enter the age = ";
                    cin>>stud[arr].age;

                    cout<<"\t Enter the Course = ";
                    cin>>stud[arr].cours;

                    cout<<"\t Enter the Modules = ";
                    cin>>stud[arr].modules;

                    arr=arr+1;
                 }
                 else
                 {
                    cout<<"This Record is Already Entered \n";
                 }

                 break;

                 case 2:

                    cout<<"\n Enter the Roll no of the student To Delete :: \n";

                    cin>>id;

                    for(int j=0; j<=arr; j++)
                    {
                        id2=id;
                        if(id2==stud[j].idno)
                        {

                            stud[j].idno='d';
                            cout<<"\t Record Deleted";

                         }
                     }

                     break;

                     case 3:
                        cout<<"\n Enter the Roll no of the student To Update ::\n";

                        cin>>id;

                        for(int j=0; j<=arr; j++)
                        {

                            id2=id;
                            if(id2==stud[j].idno)
                            {
                                cout<<"\t ID = ";
                                cout<<stud[j].idno;

                                cout<<"\t Name = ";
                                cout<<stud[j].name;

                                cout<<"\t Surname = ";
                                cout<<stud[j].sname;

                                cout<<"\t Age = ";
                                cout<<stud[j].age;

                                cout<<"\t Course = ";
                                cout<<stud[j].cours;

                                cout<<"\t Modules = ";
                                cout<<stud[j].modules;

                                cout<<"\n\t Re-Enter Data ";

                                cout<<"\n\t Enter the Name = ";
                                cin>>stud[j].name;

                                cout<<"\n\t Enter the Surname = ";
                                cin>>stud[j].sname;

                                cout<<"\n\t Enter the Age = ";
                                cin>>stud[j].age;

                                cout<<"\n\t Enter the Course = ";
                                cin>>stud[j].cours;

                                cout<<"\n\t Enter the Modules = ";
                                cin>>stud[j].modules;

                             }
                         }

            break;

            case 4:

            cout<<"\n Enter the ID number of the student To Search ::";

            cin>>id;

            for(int j=0; j<=arr; j++)
            {
                id2=id;
                if(id2==stud[j].idno)
                {
                    cout<<"\n\t ID = ";
                    cout<<stud[j].idno;

                    cout<<"\n\t Name = ";
                    cout<<stud[j].name;

                    cout<<"\n\t Surname = ";
                    cout<<stud[j].sname;

                    cout<<"\n\t Age = ";
                    cout<<stud[j].age;

                    cout<<"\n\t Course = ";
                    cout<<stud[j].cours;

                    cout<<"\n\t Modules = ";
                    cout<<stud[j].modules;

                }
            }

            break;

            case 5:
                {

                    string  str;
                    int i, count = 0;

                    cout<<"Enter Course: ";
                    cin>>str;

         for( i=0; i<=str.size(); i++)
         {
            if(str == stud[i].cours)

         {
            count++;
         }
    }
                     cout<<"Number of students doing "<<str<<" are "<<count;
                    }

            break;

            case 6:
                {
                    string str;
                    int n, count = 0;

                cout<<"Enter number of courses: ";
                cin>>n;

            for(int i=0; i<=n-1; i++)
                    {
                    cout<<"Enter course: ";

                cin>>str;

         for(int i=0; i<=str.size(); i++)

         {

        if(str == stud[i].cours)

         {
count++;

}

}

    cout<<"Number of students doing "<<str<<" are "<<count<<endl;

}

}
                cout<<"\n__________________________________________________________________________________________________________________________________________________________________"<<endl;
                for(int i=0; i<1; i++)
                {
                    cout<<setw(12)<<"Rollno ||";
                    cout<<setw(12)<<" Name   ||";
                    cout<<setw(12)<<" Surname    || ";
                    cout<<setw(12)<<"Age  ||";
                      cout<<setw(12)<<" Course  ||";
                      cout<<setw(12)<<" Module   ||";

                      for(int k=0; k<arr; k++)
                      {
                        if(stud[k].idno!='d')
                        {
                            cout<<"\n";
                            cout<<" ";
                            cout<<setw(5)<<stud[k].idno;

                            cout<<setw(15)<<stud[k].name;

                        cout<<setw(14)<<stud[k].sname;

                         cout<<setw(14)<<stud[k].age;

                          cout<<setw(12)<<stud[k].cours;

                            cout<<setw(14)<<stud[k].modules;

                            }
                        }
                }
                cout<<"\n______________________________________________________________________________________________________________________________________________________________________________"<<endl;

                    {

                        cfile.open("CourseFile.txt");

                    string  str;
                    int i,count = 0;

            for(i=0; i<2; i++)
    {

         for( i=0; i<=sizeof(str); i++)
         {
            if(str == stud[i].cours)

         {
            count++;
         }
    }

                     cfile<<"Number of students doing "<<str<<" are "<<count;
                    }
            }

            cfile<<"\n__________________________________________________________________________________________________________________________________________________________________"<<endl;
                for(int i=0; i<1; i++)
                {
                    cfile<<setw(12)<<"Rollno ||";
                    cfile<<setw(12)<<" Name   ||";
                    cfile<<setw(12)<<" Surname    || ";
                    cfile<<setw(12)<<"Age  ||";
                      cfile<<setw(12)<<" Course  ||";
                      cfile<<setw(12)<<" Module   ||";

                      for(int k=0; k<arr; k++)
                      {
                        if(stud[k].idno!='d')
                        {
                            cfile<<"\n";
                            cfile<<" ";
                            cfile<<setw(5)<<stud[k].idno;

                            cfile<<setw(15)<<stud[k].name;

                        cfile<<setw(14)<<stud[k].sname;

                         cfile<<setw(14)<<stud[k].age;

                          cfile<<setw(12)<<stud[k].cours;

                            cfile<<setw(14)<<stud[k].modules;

                            }
                        }
                }
            cfile<<"\n______________________________________________________________________________________________________________________________________________________________________________"<<endl;

            cfile.close();

                break;

            case 7:
                {

                sfile.open("StudentFile.txt");
                cout<<"\n__________________________________________________________________________________________________________________________________________________________________";
                for(int i=0; i<1; i++)
                {
                    cout<<setw(12)<<"Rollno ||";
                    cout<<setw(12)<<" Name   ||";
                    cout<<setw(12)<<" Surname    || ";
                    cout<<setw(12)<<"Age  ||";
                      cout<<setw(12)<<" Course  ||";
                      cout<<setw(12)<<" Module   ||";

                      for(int k=0; k<arr; k++)
                      {
                        if(stud[k].idno!='d')
                        {
                            cout<<"\n";
                            cout<<" ";
                            cout<<setw(5)<<stud[k].idno;

                            cout<<setw(15)<<stud[k].name;

                        cout<<setw(14)<<stud[k].sname;

                         cout<<setw(14)<<stud[k].age;

                          cout<<setw(12)<<stud[k].cours;

                            cout<<setw(14)<<stud[k].modules;

                            }
                        }
                }
                cout<<"\n______________________________________________________________________________________________________________________________________________________________________________";

        for(int i=0; i<1; i++)
                {
                    sfile<<setw(12)<<"Rollno ||";
                    sfile<<setw(12)<<" Name   ||";
                    sfile<<setw(12)<<" Surname    || ";
                    sfile<<setw(12)<<"Age  ||";
                      sfile<<setw(12)<<" Course  ||";
                      sfile<<setw(12)<<" Module   ||";

                      for(int k=0; k<arr; k++)
                      {
                        if(stud[k].idno!='d')
                        {
                            sfile<<"\n";
                            sfile<<" ";
                            sfile<<setw(5)<<stud[k].idno;

                            sfile<<setw(15)<<stud[k].name;

                        sfile<<setw(14)<<stud[k].sname;

                         sfile<<setw(14)<<stud[k].age;

                          sfile<<setw(12)<<stud[k].cours;

                            sfile<<setw(14)<<stud[k].modules;

                            sfile.close();

                            }
                        }
                }

            }

                break;

                default:
                    cout<<"\t Wrong option Selected ";
                    break;
        }

    cout<<"\n\n\t Do You Want to Continue Again [Y/N]";
    cin>>dow;

}
while(dow=='y');
return 0;
getch();
}


text:
Q: Nginx response code is 200 even if response is incomplete We have a flask app in python which is serving data (reading from db and sending it over network). Here app is behind ALB(AWS) and which is behind 2 apps serving as proxy and nginx server is at final boundary which has connection with end client.
In short, request routing is as below,
Flask APP <-> ALB <-> proxy1 (rate limiter) <-> proxy2 (auth) <-> Nginx <-> cloudfront <-> End client

Here we have observed strange thing, Sometimes data sent from Flask app is sent partially to end client but response code is sent 200 on its first sent byte of data. As its chunked data transfer, I believe sending 200 as soon as first byte of data is transferred is correct but not sure why end client is sometimes receiving only partial data. Ex. if total data is 100MB then client gets only 10-50MB without any error code. All intermediate apps/proxies transfer data as stream and I can see 200 status in all of them.
Not sure why this is happening? Has anybody faced such issue before, if yes any pointers will be helpful.
protocol version is HTTP 1.1 and flask version are,
Flask==1.1.2
Flask-BasicAuth==0.2.0
Flask-Compress==1.4.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the closest thing to a nested dictionary (python) in Java? I'm following a tutorial for a recommendation engine and the book wants to input user preferences and reviews using a nested dictionary. What is Java's equivalent?

A: A nested dictionary is a dictionary where the values of the entries can be dictionaries. In Java, dictionaries are implemented via the Map interface.
If your dictionary keys are strings (both the top-level keys and the second-level keys), and the values of the inner dictionaries are (say) Widgets, then you'd use a Map<String, Map<String, Widget>>:
//  +---------------------------- Outer dictionary key type
//  v       vvvvvvvvvvvvvvvvvvv-- Outer dictionary value type
Map<String, Map<String, Widget>> nested = new HashMap<String, HashMap<String, Widget>>;
//              ^       ^
//              |       |
//              |       +-------- Inner dictionary value type
//              +---------------- Inner dictionary key type

...where HashMap is just one of the possible Map implementations you might use.

A: Nested HashMap is what you might be looking for.

You can do it like this:
Map<Float, Map<Float, Integer>>map=new HashMap<>();

map.put(.0F,new HashMap(){{put(.0F,0);}});
map.put(.1F,new HashMap(){{put(.1F,1);}});

map.get(.0F).get(.0F);


text:
Q: Convert ID from speech to text without spaces I'm using Google Cloud Speech API with IBM Voice Gateway in order to interact with a VoiceBot through a phone.
If I say an identifier contening letters and numbers through the phone, the Google Cloud Speech converts it into string with spaces. For example, if I say "A1B2C3", it will convert it into the following string "a 1 b 2 c 3".
Do you know if there is way to avoid these useless spaces ?
Thanks for your help!
Lucas

A: I don't see any way in which you can eliminate spaces from the API response. What you could do is experiment with the available features, as this is probably your best chance to get a recognition more similar to what you are looking for.
For example: you can provide some sample hint phrases echoing your use case, indicate that the audio is a phone call, or use an enhanced model (although for the latter to be available you need to first opt in for data logging).
Honestly though, for your case, it might be better if you post process the returned string (e.g. with a simple "a 1 b 2 c 3".replace(' ','') ).


text:
Q: Java ArrayList Interface Type I have many classes that implement a common interface. I use a definition like Array List  mytypes, and add objects of that type to the ArrayList. Now i want to use contains method of the ArrayList class to see if this List contains a class i am adding.
If I implement hashcode and equals on the classes will the contains method know if a certain object already is in the ArrayList or not?

A: from List.contains():

Returns true if this list contains the specified element. More
  formally, returns true if and only if this list contains at least one
  element e such that (o==null ? e==null : o.equals(e)).

So basically hashCode() is not relevant here, only equals()
EDIT: [better explicit then implicit], as mentioned in comments by @aiobee, equals() still needs to be overriden - according to the contract - but it will not have effect on the value returned by contains()

A: Implementing hashCode is not useful for that purpose but it is a goog practice to override both equals and hashCode simultaneously.
Yes, it will work, that is the purpose of the contains method.

A: ArrayList.contains won't use hashCode, but it will use equals, as documented:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

(This won't check whether "this class" is already in the list - it will check whether an equal object is in the list.)


text:
Q: How do I know which one is the physical MAC Address programmatically? I use this code in VB6 to get the MAC Address of the computer:
Sub GetMACAddress()

    'get MAC address using WMI
    Dim oWMIService As Object
    Dim oColAdapters As Object
    Dim oObjAdapter As Object

    Set oWMIService = GetObject("winmgmts:" & "!\\.\root\cimv2")
    Set oColAdapters = oWMIService.ExecQuery _
    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")

    For Each oObjAdapter In oColAdapters
       MsgBox "MAC address formatted: " & oObjAdapter.MacAddress & vbNewLine _
       & "MAC address unformatted: " & Replace(oObjAdapter.MacAddress, ":", "")
    Next

    Set oObjAdapter = Nothing
    Set oColAdapters = Nothing
    Set oWMIService = Nothing
    End Sub

The problem is that I have Windows 7 running on Oracle VirtualBox installed and oColAdapters is having two MAC Addresses.
How to check which one is the phisical one of my PC?


text:
Q: tocar varios botones con un dedo estoy queriendo hacer un piano por partes, como podria hacer el efecto de cuando se toca una tecla y dezlizando hacia izquierda o derecha (sin levantar el dedo) suenen las demas notas?

casi utilice el mismo codigo de la botonera. Leyendo por ahi tendria que poner otro if con el evento de MotionEvent.ACTION_MOVE debajo del MotionEvent.ACTION_DOWN ? y mi otra duda es que si no tendria que utilizar MultiTouch en vez de ontouch ya que seria lo logico o no?
public class MainActivity extends AppCompatActivity {

    ImageButton tecla1,tecla2,tecla3,tecla4;
    private SoundPool soundPool;
    private int son_tecla1, son_tecla2, son_tecla3, son_tecla4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tecla1 = (ImageButton)findViewById(R.id.ib1);
        tecla2 = (ImageButton)findViewById(R.id.ib2);
        tecla3 = (ImageButton)findViewById(R.id.ib3);
        tecla4 = (ImageButton)findViewById(R.id.ib4);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            soundPool = new SoundPool.Builder().setMaxStreams(4).build();
        }else {
            soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
        }

        son_tecla1=soundPool.load(this, R. raw.t1,1);
        son_tecla2=soundPool.load(this, R. raw.t2,1);
        son_tecla3=soundPool.load(this, R. raw.t3,1);
        son_tecla4=soundPool.load(this, R. raw.t4,1);

        tecla1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent ) {

                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    soundPool.play(son_tecla1,1,1,0,0,0);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    soundPool.stop(son_tecla1);
                }
                return false;
            }
        });

        tecla2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent ) {

                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    soundPool.play(son_tecla2,1,1,0,0,0);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    soundPool.stop(son_tecla2);
                }
                return false;
            }
        });

        tecla3.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent ) {

                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    soundPool.play(son_tecla3,1,1,0,0,0);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    soundPool.stop(son_tecla3);
                }
                return false;
            }
        });

        tecla4.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent ) {

                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    soundPool.play(son_tecla4,1,1,0,0,0);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    soundPool.stop(son_tecla4);
                }
                return false;
            }
        });

A: Como comentas, en este caso debes implementar la detección de eventos multi touch:
https://developer.android.com/training/gestures/multi.html

como podria hacer el efecto de cuando se toca una tecla y dezlizando
  hacia izquierda o derecha

De acuerdo a la imagen debes mapear la posición de las teclas (imagenes) y mediante la detección de la coordenada en el eje X podrías saber que tecla estas tocando:
public boolean onTouchEvent(MotionEvent event) {
    ....
    //Obtiene posición.
    float x = event.getX(pointerIndex);
    float y = event.getY(pointerIndex);
}


text:
Q: is it possible to add ansible_ssh_common_args in inventory file i want to jump/SSH Bastion Host using ProxyCommand of ansible_ssh_common_args.
ansible server:10.10.149.2
gateway/Bastion host:10.10.149.70
host to connect:10.32.32.190
So my aim is to connect 10.32.32.190 from 10.10.149.2 trough 10.10.149.70 (ssh tunneling)
ansible --version
ansible 2.1.0.0
my inventory:
[local]
10.10.149.2

[Private]
10.32.32.190

[Private:vars]
ansible_ssh_common_args: '-o ProxyCommand="ssh -W %h:%p -q root@10.10.149.70"'

pingtest.yml:
---
- hosts: Private
  tasks:
- name: test connection
  ping:
  register: ping1
- debug: var=ping1

Issue facing:
 fatal: [10.32.32.190]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true}

So i doubt ansible_ssh_common_args support in inventory file.i do not want to use the ssh.config file.
Logs:
   [root@mavosdsc ansible]# ansible-playbook -i inventory pingtest.yml -e "user=root" --ask-pass -vvvv
   Using /etc/ansible/ansible.cfg as config file
   SSH password:
   Loaded callback default of type stdout, v2.0

   PLAYBOOK: pingtest.yml *********************************************************
   1 plays in pingtest.yml

   PLAY [Private] *****************************************************************

   TASK [setup] *******************************************************************
   <10.32.32.190> ESTABLISH SSH CONNECTION FOR USER: None
   <10.32.32.190> SSH: EXEC sshpass -d12 ssh -C -vvv -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/ansible-ssh-%h-%p-%r 10.32.32.190 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo $HOME/.ansible/tmp/ansible-tmp-1469788026.71-124524328003439 `" && echo ansible-tmp-1469788026.71-124524328003439="` echo $HOME/.ansible/tmp/ansible-tmp-1469788026.71-124524328003439 `" ) && sleep 0'"'"''
   fatal: [10.32.32.190]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true}
   to retry, use: --limit @pingtest.retry

   PLAY RECAP *********************************************************************
   10.32.32.190               : ok=0    changed=0    unreachable=1    failed=0

A: The problem is here:
ansible_ssh_common_args: '-o ProxyCommand="ssh -W %h:%p -q root@10.10.149.70"'
Replace ":" by "=" and write like this:
ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q root@10.10.149.70"'
To help others, keep in mind that your inventory file is a '.ini' file.
'.ini' files e.g ansible.cfg, use '=' to assign variables, as 'yaml' files use ':'.


text:
Q: Rails 3 in test env won't allow records to save, even with latest sqlite3 I saw this post:
Rails/ActiveRecord/SQLite3: Can't save records in test environment
And after upgrading my sqlite version to the very latest (3.7.17), I am still getting the following error:

ActiveRecord::StatementInvalid: SQLite3::SQLException: near "SAVEPOINT": syntax error: SAVEPOINT active_record_1

Any time I try to create anything at all.  If all I do is load my fixtures, everything is fine.
I have confirmed that rails is using the updated sqlite3 version by running "rails db".
In my development environment, I can create objects all day long with no errors (I can even have an object create another object after create).
What is special about my test environment that this is happening?  How can I fix it?
Edit:
If I delete my test database, and redo rake:db:create and rake:db:migrate, I still get the same issues.
Doing "rails console test" lets me use the test environment just fine, and I can create objects all day long and see existing fixtures.  It's only when I type "rake test:units" that I get the errors...  (originally I had errors, but one error was legitimate (I don't know why I wasn't getting it in the development environment, and the adapter error was because apparently you aren't supposed to do "rails console RAILS_ENV="test", so it was looking for an adapter for an envrionment called "RAILS_ENV=test")
Edit: When I type "gem uninstall sqlite3" it uninstalls. When I then type "bundle install" it has a problem reinstalling...working on it now.

    /home/jenny/.rvm/rubies/ruby-1.9.3-p0/bin/ruby extconf.rb --with-sqlite3-dir=/usr/local/bin/sqlite3 checking for sqlite3.h... *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers.  Check

the mkmf.log file for more details.  You may need configuration
  options.

If I type "gem install sqlite3" separately, it works just fine, and then "bundle install" it works.  However, "rake test:units" has the same errors.
Edit:
When I type "which sqlite3" it prints out "/usr/local/bin/sqlite3"
I wasn't even aware sqlite3 headers were a thing, so I doubt I installed them.  I'll try to figure out how to confirm this and see if it helps.
Edit:
I don't see anywhere to download sqlite3 headers on the main site...just source and the precompiled linux binary. There doesn't seem to be a special header in the source, but even if there was, wouldn't it be included in the precompiled binary?
EDIT: link to bundler sqlite3 install error that don't happen when i manually install the gem
http://pastie.org/8063577
EDIT: Not a devise problem. I thought it was, but it turned out I was just creating another object in fixtures, not in the test code.
So, I can create devise User or any other type of object in fixtures all day long, but if I attempt to create one in the unit test, I get the save point error.  Same thing for trying to save a fixture in a unit test.

A: Your problem is most likely related to the fact that you updated your local sqlite but after that you haven't reinstalled your sqlite3 gem.
I'd recommend you follow these steps:

*

*Remove the corresponding line gem 'sqlite3' from your Gemfile

*Run bundle install

*Run gem uninstall sqlite3

*Return the line gem 'sqlite3' to your Gemfile

*Run bundle install one more time

If you simply gem uninstall and then bundle install, it will install the same version and dependencies that were recorded in Gemfile.lock. But since you're now using a different and more updated local version, it's safer to allow Bundler to install a new version if needed.


text:
Q: makefile. Запуск сервера и клиента Привет.
Есть следующая структура:

*

*Прилажка-сервер на python слушает браузер через сокет на порту 8081. Ждёт от него ответа. Браузер в данном случае -- клинет.

*На Go реализован back-end. Здесь реализована начинка системы.

*Дождавшись запроса от браузера, прилажка на python из первого пункта отвечает посылает запрос в начинку и ждёт ответа. После получения ответа запрос отправляется обратно в браузер.

Таким образом, есть некоторый шлюз на питоне, который считает статистику. Шлюз, как и начинка крутятся в бесконечном цикле.
Вопрос. Как реализовать makefile так, чтобы в нём компилилась и запускалась начинка системы и шлюз.
Я не могу это сделать, так как make-file линеен. Т.е. пока не отработает одна инструкция. Другая не запустится.

A: make файл просто запускает команды в консоле.  Поэтому работает классический &
то есть, нужно писать что то вида
run:
    ./first &
    ./second &
    echo "все запущено и работает!"

ну или если сильно нужно - можно запустить в screen/tmux/ сервисом / docker.
run:
    screen ./first
    screen ./second &
    echo "все запущено и работает!"

плюс этого способа в том, что можно будет скрином подцепиться и посмотреть логи. Но можно и просто перенаправить вывод в файл.
И остается последний вопрос - а как сделать завершение? самый простой способ просто кильнуть по имени. Но можно сохранить PID запущенных процессов и задача сильно упрощается.


text:
Q: exclude html attributes in str_replace so i'm trying to do the usual replacing each instance of a company name in wordpress, and i've run into an issue where on occasion (usually in the href of links) it's breaking links.
code i'm using (includes a filter for ACF custom fields)
    //Replace the word lunch with a span
function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'lunch!' => 'lunch!',
        'Lunch!' => 'lunch!',
        'LUNCH!' => 'lunch!'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}

add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');

Is there a way to only replace it outside of stuff like href tags? i've looked into stuff like DOM parses but i'm not sure if there's a simpler method- it doesn't seem to cause grief in any other instances so i'm not sure that pre=processing the entire HMTL and looking for the word is appropriate. I did wonder about searching for the string including a space before and after it, but i wasn't sure how to include leading / trailing spaces, and it felt a bit bodge-y?
Thanks in advance!
Pete

A: ok, so in this instance, which is quite specific, i've found the following code works well enough. added trailing / leading spaces in the initial matching parameters, and also variants to find it directly after html tags including with a space.
less elegant, but sufficient for the purpose here.
function replace_text_wps($text){
    $replace = array(
        // used mid-line
        ' lunch! ' => ' lunch! ',
        ' Lunch! ' => ' lunch! ',
        ' LUNCH! ' => ' lunch! ',
        // used at end of lines
        ' lunch!' => ' lunch!',
        ' Lunch!' => ' lunch!',
        ' LUNCH!' => ' lunch!',
        // used inside html tags like headers
        '>lunch!' => '>lunch!',
        '>Lunch!' => '>lunch!',
        '>LUNCH!' => '>lunch!',
        //used directly after html tags
        '> lunch!' => '> lunch!',
        '> Lunch!' => '> lunch!',
        '> LUNCH!' => '> lunch!',
        //exclude alt tags on images, title attributes etc
        '"lunch!' => '"lunch!',
        'lunch!"' => 'lunch!"',
        '"Lunch!' => '"lunch!',
        'Lunch!"' => 'lunch!"'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');


text:
Q: Can I set my wireless network card to connect only to 2.4 GHz wireless networks? On a laptop or 2-in-1 device with Windows 10 (like the Surface Pro), is there a way to set the WiFi network card to detect and connect only to wireless networks on the 2.4 GHz frequency?
My devices work also with 5 GHz networks and I'm interested (for some experiments) to have them connect to WiFi only on the 2.4 GHz wireless frequency.
Is this possible? How can you make your network card ignore 5 GHz wireless networks, detect and connect only to 2.4 GHz wireless networks?


text:
Q: How to pass sightly variable as an argument to java script This is my code:
<div id="highcharts-sjlyUWsr">
<script src="https://app.everviz.com/inject/sjlyUWsr/" defer="defer" onerror="failed(${sightlyVariable})"></script>
</div>

Notice : I have passed sightly variable in javascript function which is throwing an error message and not working.

A: Did you try this?
 <script src="https://app.everviz.com/inject/sjlyUWsr/"
 data-sly-test.err="failed('${sightlyVariable}')" defer="defer" onerror="${err@ context='attribute'}"
></script>


text:
Q: How to expand card onPress - React Native I am trying to make a ticket app that allows for people to create tickets based on work that needs done. Right now, I need help with the expandable view for each ticket card. What I'm wanting is when a user presses on a specific card, it will expand the view and provide more details for only that card. What it is currently doing is expanding the view for every ticket card in the list. I'm new to React Native and trying my best, but nothing has worked so far.
Here is my parent which is called Home:
import React, {useState, useEffect} from 'react';
import {styles, Colors} from '../components/styles';
import { SafeAreaView } from 'react-native';
import Ticket from '../components/Ticket';

const data = [
    {
        name: 'Josh Groban',
        subject: 'U-Joint',
        desc: 'The bolt that is meant to hold the u-joint in place has the head broken off from it. See attached picture.',
        assignee: 'John Doe',
        assigneeConfirmedComplete: 'NA',
        dateReported: 'Tue Mar 8, 2022',
        vehicle: 'Truck 1',
        media: '',
        key: '1',
        isShowing: false
      },
      // code removed for brevity
];

const Home = ({navigation}) => {

    const [ticketList, setTicketList] = useState(data);

    const getTickets = () => {
        setTicketList(data);
    }
    useEffect(() => {
        getTickets();
    }, []);

    return (
        <SafeAreaView  style={styles.HomeContainer}>
                <Ticket
                    ticketList={ticketList}
                    setTicketList={setTicketList}
                />
        </SafeAreaView>
    )
};

export default Home;

And here is the main component that has all of the ticket card configurations:
import React, {useState, useEffect} from 'react';
import {Text, FlatList, View, SafeAreaView, Button, Image, TouchableOpacity } from 'react-native';
import {styles, Colors} from './styles';
import {Ionicons} from '@expo/vector-icons';

const Ticket = ({ticketList, setTicketList}) => {
    const defaultImage = 'https://airbnb-clone-prexel-images.s3.amazonaws.com/genericAvatar.png';
    const [isComplete, setIsComplete] = useState(false);
    const [show, setShow] = useState(false);

    const showContent = (data) => {
        const isShowing = {...data, isShowing}
        if (isShowing)
            setShow(!show);
    }

    const completeTask = () => {
        setIsComplete(!isComplete);
    }
    return (
        <SafeAreaView style={{flex: 1}}>
        <FlatList showsVerticalScrollIndicator={false}
            data={ticketList}
            renderItem={(data) => {
                return (
            <>
            <TouchableOpacity key={data.item.key} onPress={() => showContent(data.item.isShowing = true)}>
                <View style={styles.TicketCard}>
                    <Image
                        style={styles.TicketCardImage}
                        source={{uri: defaultImage}}
                    />
                    <View style={styles.TicketCardInner}>
                        <Text style={styles.TicketCardName}>{data.item.vehicle}</Text>
                        <Text style={styles.TicketCardSubject}>
                            {data.item.subject}
                        </Text>
                    </View>
                    <TouchableOpacity>
                        <Ionicons
                            name='ellipsis-horizontal-circle'
                            color={Colors.brand}
                            size={50}
                            style={styles.TicketCardImage}
                        />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={completeTask}>
                        <Ionicons
                            name={isComplete ? 'checkbox-outline' : 'square-outline'}
                            color={Colors.brand}
                            size={50}
                            style={styles.TicketCardButton}
                        />
                    </TouchableOpacity>
                </View>
                <View style={styles.TicketCardExpand}>
                    <Text>
                {show &&
                    (<View style={{padding: 10}}>
                        <Text style={styles.TicketCardDesc}>
                            {data.item.desc}
                        </Text>
                        <Text style={{padding: 5}}>
                            Reported by: {data.item.name}
                        </Text>

                        <Text style={{padding: 5}}>
                            Reported: {data.item.dateReported}
                        </Text>
                        {isComplete && (
                        <Text style={{padding: 5}}>
                            Confirmed Completion: {data.item.assigneeConfirmedComplete}
                        </Text>
                        )}
                    </View>
                    )}
                    </Text>
                </View>
            </TouchableOpacity>
            </>
        )}}
        />
        </SafeAreaView>
    )
};

export default Ticket;

Lastly, here are the styles that i'm using:
import {StyleSheet } from "react-native";
import { backgroundColor } from "react-native/Libraries/Components/View/ReactNativeStyleAttributes";
// colors
export const Colors = {
    bg: '#eee',
    primary: '#fff',
    secondary: '#e5e7eb',
    tertiary: '#1f2937',
    darkLight: '#9ca3f9',
    brand: '#1d48f9',
    green: '#10b981',
    red: '#ff2222',
    black: '#000',
    dark: '#222',
    darkFont: '#bbb',
    gray: '#888'
}

export const styles = StyleSheet.create({
    HomeContainer: {
        flex: 1,
        paddingBottom: 0,
        backgroundColor: Colors.bg,
    },
    TicketCard : {
        padding: 10,
        justifyContent: 'space-between',
        borderColor: Colors.red,
        backgroundColor: Colors.primary,
        marginTop: 15,
        flexDirection: 'row',
    },
    TicketCardExpand: {
        justifyContent: 'space-between',
        backgroundColor: Colors.primary,
    },
    TicketCardImage: {
        width: 60,
        height: 60,
        borderRadius: 30
    },
    TicketCardName:{
        fontSize: 17,
        fontWeight: 'bold'
    },
    TicketCardSubject: {
        fontSize: 16,
        paddingBottom: 5
    },
    TicketCardDesc: {
        fontSize: 14,
        flexWrap: 'wrap',
    },
    TicketCardInner: {
        flexDirection: "column",
        width: 100
    },
    TicketCardButton: {
        height: 50,
    }

});

Any help is greatly appreciated!

A: Create a Ticket component with its own useState.
const Ticket = (data) => {
  const [isOpen, setIsOpen] = useState(false);

  const handlePress = () => {
    setIsOpen(!isOpen);
  }

  return (
    <TouchableOpacity
      onPress={handlePress}
    >
      // data.item if you use a list, otherwise just data
      <YourBasicInformation data={data.item} />
      {isOpen && <YourDetailedInformation data={data.item} />}
    </TouchableOpacity>
  )
}

Render one Ticket for every dataset you have.
<List
  style={styles.list}
  data={yourDataArray}
  renderItem={Ticket}
/>

If you don't want to use a List, map will do the job.
{yourDataArray.map((data) => <Ticket data={data} />)}

A: instead of setting show to true or false you can set it to something unique to each card like
setShow(card.key or card.id or smth)

and then you can conditionally render details based on that like
{show == card.key && <CardDetails>}

or you can make an array to keep track of open cards
setShow([...show,card.id])

{show.includes(card.id) && <CardDetails>}

//to remove
setShow(show.filter((id)=>id!=card.id))


text:
Q: How to change a value from parent component in a child component with useState React hook So I am fetching random colors via fetch_API every time I click the button "Get Color", the colors get added into an array and are listed with the .map function where also every div containing the hex value of the color is colored in that color and the button itself is also colored in the latest color. That works all fine. What I wanted to add was an input field where I manually enter a hex and if the hex exists it gets added to the array and if not it just displays an error.
Here is the code of the parent component (I also added drag and drop functionality to the array)
![How it looks][1]
import React, { useState } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import Form from "./Form";

var but = false;

const Colors = () => {
  const [colors, setColors] = useState([]);

  //fetch the color
  const GetColors = async () => {
    const response = await fetch("https://www.colr.org/json/color/random", {
      cache: "reload",
    });
    const color = await response.json();
    but = true;
    //add into the array
    if (color.new_color === null) {
      alert("error");
      return;
    } else {
      setColors([...colors, color.new_color]);
    }
  };

  //Item reordering for drag and drop
  function handleOnDragEnd(result) {
    if (!result.destination) return;
    const items = Array.from(colors);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    setColors(items);
  }
  return (
    <>

        <DragDropContext onDragEnd={handleOnDragEnd}>
          <Droppable droppableId="colors">
            {(provided) => (

                {colors.map((color, index) => {
                  return (
                    <Draggable
                      key={color}
                      draggableId={String(color)}
                      index={index}
                    >
                      {(provided) => (

{color}

                      )}
                    </Draggable>
                  );
                })}
                {provided.placeholder}

            )}
          </Droppable>
        </DragDropContext>

      <button
        type="button"
        className="btn"
        style={{
          background: but ? "#" + colors[colors.length - 1] : "black",
        }}
        onClick={GetColors}
      >
        Get Color
      </button>
      <Form setColors={() => setColors()} />
    </>
  );
};

export default Colors;

Now the component Form.js works in a way that has an useEffect where it checks if the user pressed enter and if he did it calls the function addColor() which should take the value of the input field with the useRef hook and check if it is a valid hex and if it is it should add it into the array of colors, but for some reason, I am getting an error saying "TypeError: Cannot read properties of undefined (reading 'map')" whenever I type anything into the input field, but if it is empty it displays the alert and no error is shown.
The code of the Form js component:
import React, { useEffect, useRef } from "react";

const Form = ({ setColors }) => {
  const colorRef = useRef();
  function addColor() {
    var color = colorRef.current.value;
    console.log(color);
    if (color === "" || color === /^#[0-9A-F]{6}$/i.test("#AABBCC")) {
      alert("This color does not exist! Type a color hex that exists.");
    } else {
      setColors((prevColors) => {
        return [...prevColors, { color }];
      });
    }
    colorRef.current.value = null;
  }

  useEffect(() => {
    const listener = (event) => {
      if (event.code === "Enter" || event.code === "NumpadEnter") {
        event.preventDefault();
        addColor();
      }
    };
    document.addEventListener("keydown", listener);
    return () => {
      document.removeEventListener("keydown", listener);
    };
  }, []);
  return (
    <>

        <form className="form">

              Enter hex:

            <input ref={colorRef} type="text" id="hex" name="hex" />

        </form>

    </>
  );
};

export default Form;

What am I doing wrong here? I know I am missing the setColors() in some way but how?

A: Does switching:
<Form setColors={() => setColors()} />

to:
<Form setColors={setColors} />

Fix your issue? You don't need to create an anonymous function here.


text:
Q: Ruby 3.0 isn't compatible with lower version? Now I am studying Ruby on Rails in Ruby 1.9.3 environment.
But I saw many articles that ruby 1.x sources doesn't work in ruby 2.0 and 3.0.
If so, is it mean that I have to study again Ruby 2.0 or 3.0 when Ruby on Rails has been updated to run under Ruby 2.0 or 3.0?
Thank you in advance!

A: You're confusing Ruby on Rails with Ruby. There is no Ruby 3.0, but there is a Ruby on Rails 3.0.
The current versions of Ruby are: 1.8.7, 1.9.2 and 1.9.3 which was just released.
The current versions of Rails are: 2.3.14, 3.0.10, and 3.1.1.
Ruby 2.0 hasn't seen a release yet and remains a theoretical construct at this point.

A: Ruby is to Rails as Javascript is to Jquery.
One is a language, and the other is really just a bunch of files (scripts, like in a play) that handle a lot of background jobs and tasks that you might need done when building a Ruby application. Rails is more commonly referred to as a framework, it's really just a pattern or paradigm for helping you structure your code.
To make more sense of this, you could try using an alternate framework to Rails, like Padrino, which is written in Ruby too, but is not Rails. It's Padrino. Same idea, ostensibly.
I recommend reading a very simple vanilla book on Ruby, which goes nowhere near any of the frameworks, like this one by Zed Shaw (which was not originally written for Ruby and so doesn't really go into the more complex and exciting stuff for which Ruby is known, like metaprogramming) but which will give you a broad based insight into how it works.
Then, in a month or so, move on to Rails Tutorial. Good luck.


text:
Q: Count orders 12 months back from a certain month group by that month I want to create a table with months counting orders from current month to 12 months back. I have data with a create_date and an order_id. So I need to convert the date to a format of yyyymm and count all order from selected month and sum up all orders that where made until 12 months back.
The outcome should look like:

I started with this query but it only counts orders for the selected month and not includes orders for former months.
SELECT TO_CHAR(create_date,'yyyymm') AS yyyymm,
       COUNT(order_id ) AS Number_of_orders_12_month_period
FROM Orders
WHERE TO_CHAR(create_date,'yyyymm') BETWEEN DATEADD(month,-12,create_date) AND TO_CHAR(create_date,'yyyymm')
group by 1

A: I don't have experience with Redshift but
WHERE TO_CHAR(create_date,'yyyymm') BETWEEN DATEADD(month,-12,create__date) AND TO_CHAR(create_date,'yyyymm')

looks wrong to me. You don't want to compare create_date with itself, you want to compare it with current_date, and you want to compare after each date is converted to a month. For instance:
WHERE TO_CHAR(create_date,'yyyymm') BETWEEN TO_CHAR(DATEADD(MONTH,-12,current_date),'yyyymm') AND TO_CHAR(current_date,'yyyymm')

A: So I managed to fix it with this query
SELECT TO_CHAR(create__date,'yyyymm') as month_id
  , LAG(count(order_id), 0) OVER (ORDER BY create__date) +
    LAG(count(order_id), 1) OVER (ORDER BY create__date) +
    LAG(count(order_id), 2) OVER (ORDER BY create__date) +
    LAG(count(order_id), 3) OVER (ORDER BY create__date) +
    LAG(count(order_id), 4) OVER (ORDER BY create__date) +
    LAG(count(order_id), 5) OVER (ORDER BY create__date) +
    LAG(count(order_id), 6) OVER (ORDER BY create__date) +
    LAG(count(order_id), 7) OVER (ORDER BY create__date) +
    LAG(count(order_id), 8) OVER (ORDER BY create__date) +
    LAG(count(order_id), 9) OVER (ORDER BY create__date) +
    LAG(count(order_id), 10) OVER (ORDER BY create__date) +
    LAG(count(order_id), 11) OVER (ORDER BY last_day_create__date)  as Number_of_orders_12_month_period
FROM orders GROUP BY create__date;

It looks weird but  it gives the correct answer and is relativly fast


text:
Q: Extracting datasets from 1 HDF5 file to multiple files I have actually raised a question in generating img from HDF5.
Now, another problem I have is to generate the h5 from the existing.
For instance, I have a [ABC.h5], inside, there is the dataset for image and its gt_density map. The keys would be [images, density_maps]
I want to have [GT_001.h5], [GT_002.h5]... instead of the single h5 file.
This is the [density_maps] extracted for each image.
How to achieve this? Thanks a lot.
[EDIT]
Here is more related information. Thank you @kcw78 for the guides.
In the original dataset in the CRSNet, there is a single image file and its ground truth density map in h5. This density map is <HDF5 dataset "density": shape (544, 932), type "<f4"> <class 'h5py._hl.dataset.Dataset'>.
Therefore, in this dataset, for each IMG_001.jpg, there is an according to IMG_001.h5.
In the dataset I have, it is a single h5 file with the information:
HDF5 dataset "density_maps": shape (300, 380, 676, 1), type "<f4"> <class 'h5py._hl.dataset.Dataset'> <HDF5 dataset "images": shape (300, 380, 676, 1), type "|u1"> <class 'h5py._hl.dataset.Dataset'>
I have successfully generated the corresponding images from the file. Therefore, my current problem would be how to loop and copy the dataset to another new h5 and built a corresponding density map h5 for each image. To explain with a sample, how can I achieve the IMG_001.h5... from this single H5PY file

A: This answers your question based on my interpretation of your data. If it doesn't solve your problem, please clarify the summary below.
First, please be careful with the term "dataset". It has a specific meaning with h5py. You use "dataset" to refer to a set of data used for training and testing a CNN. That makes it difficult when there are also datasets IN a HDF5 file.
Based on your explanation, this is my understanding of the different files you have for training and testing.
Your original set of training and testing data in the CRSNet:
image files: IMG_###.jpg
ground truth density map files: IMG_###.h5 with attributes: name="density"; shape=(544, 932); type="<f4">
You have pairs of image and density files -- 1 .jpg and .h5 file for IMG_001 thru IMG_NNN.
Your new set of training and testing data:
H5 Filename: [ABC.h5]
H5 Dataset 1: name="images": shape=(300, 380, 676, 1), type="|u1"
H5 Dataset 2: name="density_maps", shape=(300, 380, 676, 1), type="<f4">
You have extracted the data from the "images" dataset in this .h5 file to create IMG_###.jpg (like your original set of training and testing data). Now you want to extract arrays from the "density_maps" dataset in the .h5 file to create IMG_###.h5.
If so, the process is the same as the image extraction procedure. The only difference is you write the data to a .h5 file instead of .jpg file. See below for a pseudo-code.
with h5py.File('yourfile.h5','r') as h5r:
    for i in range(h5r['density_maps'].shape[0]):
        dmap_arr = h5r['density_maps'][i,:]
        h5w=h5py.File(f'IMG_{i:03}.h5','w')
        h5w.create_dataset('density_maps',data=dmap_arr)
        h5w.close()

Note, when you read dmap_arr you may get shape=(380, 676, 1). If so, you can reshape with .reshape(380, 676). Like this:
        dmap_arr = h5r['density_maps'][i,:].reshape(380, 676)


text:
Q: Reading from text files in Visual Basic This is the first challenge on Day 1 of the 2018 Advent of Code
(link: https://adventofcode.com/2018/day/1)
So I am trying to create a program that reads a long list of positive and negative numbers (e.g +1, -2, +3, etc.) and then add them up to create a total. I have researched some methods of file handling in Visual Basic, and have come up with the below method:
    Sub Main()
        Dim objStreamReader As StreamReader
        Dim strLine As String = ""
        Dim total As Double = 0
        objStreamReader = New StreamReader(AppDomain.CurrentDomain.BaseDirectory & "frequencies.txt")
        strLine = objStreamReader.ReadLine
        Do While Not strLine Is Nothing
            Console.WriteLine(strLine)
            strLine = objStreamReader.ReadLine
            total += strLine
        Loop
        Console.WriteLine(total)
        objStreamReader.Close()
        Console.ReadLine()
    End Sub

Here is a link to the list of numbers: https://adventofcode.com/2018/day/1/input
It is not a syntax error I am getting but a logic error. The answer is somehow wrong, but I cannot seem to figure out where! I have tried to remove the signs from each number but that throws me a NullException error when it compiles.
So far I have come out with the answer 549, which the Advent of Code webiste rejects. Any ideas?

A: Make your life easier by using File.ReadLines(fileName) instead of dealing with StreamReader. Use Path.Combine instead of string concatenation to create a path. Path.Combine takes care of adding missing \ or removing extra ones etc.
Your file might contain an extra empty line at its end, that does not convert to a number. Use Double.TryParse to make sure you have a valid number before totalizing it. You should have Option Strict On anyway to enforce explicit conversions.
Dim fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "frequencies.txt")
Dim total As Double = 0
For Each strLine As String In File.ReadLines(fileName)
    Console.WriteLine(strLine)
    Dim n As Double
    If Double.TryParse(strLine, n) Then
        total += n
    End If
Next
Console.WriteLine(total)
Console.ReadLine()

A: For appending two string, please use string builder.
Dim test as new stringbuilder()
Test.append("your string")
It will not affect performance.


text:
Q: Handcrafted OData queries on Exact Online with Invantive We are currently running a number of hand-crafted and optimized OData queries on Exact Online using Python. This runs on several thousand of divisions. However, I want to migrate them to Invantive SQL for ease of maintenance.
But some of the optimizations like explicit orderby in the OData query are not forwarded to Exact Online by Invantive SQL; they just retrieve all data or the top x and then do an orderby.
Especially for maximum value determination that can be a lot slower.
Simple sample on small table:
https://start.exactonline.nl/api/v1/<<division>>/financial/Journals?$select=BankAccountIBAN,BankAccountDescription&$orderby=BankAccountIBAN desc&$top=5

Is there an alternative to optimize the actual OData queries executed by Invantive SQL?

A: You can either use the Data Replicator or send the hand-craft OData query through a native platform request, such as:
insert into NativePlatformScalarRequests
( url
, orig_system_group
)
select replace('https://start.exactonline.nl/api/v1/{division}/financial/Journals?$select=BankAccountIBAN,BankAccountDescription&$orderby=BankAccountIBAN desc&$top=5', '{division}', code)
,      'MYSTUFF-' || code
from   systempartitions@datadictionary
limit  100 /* First 100 divisions. */

create or replace table exact_online_download_journal_top5@inmemorystorage
as
select jte.*
from   ( select npt.result
         from   NativePlatformScalarRequests npt
         where  npt.orig_system_group like 'MYSTUFF-%'
         and    npt.result is not null
) npt
join   jsontable
       ( null
         passing npt.result
         columns BankAccountDescription varchar2 path 'd[0].BankAccountDescription'
         ,       BankAccountIBAN varchar2 path 'd[0].BankAccountIBAN'
       ) jte

From here on you can use the in memory table, such as:
select * from exact_online_download_journal_top5@inmemorystorage

But of course you can also 'insert into sqlserver'.


text:
Q: What will be the value of sub gradient at 0 for function |x| I am learning about Lasso Regression and came across taking gradient with respect to 0. I came to know about subgradient but could not understand what will be it's value at 0.
In lasso regression, we use L1-Regularisation, which means adding the absolute values of weights or coefficients to the cost. So, Inorder for us to do the gradient descent algorithm we have to take the gradients. The gradient of absolute value function at 0 does not exist. Then I have read about something called sub-gradients, but I could not understand much about it. For subgradients for values less than 0, subgradient is -1 and for values greater than 0, subgradient is +1. But I could not understand what will be the value of subgradient at 0, for function |x|?


text:
Q: Give class to the next item in list Hi I've got follow json called list:
{
    "Items" : [
           {
               "InternalID": 1,
               "Name" : "Item 1"
           },
           {
               "InternalID": 2,
               "Name" : "Item 2"
           },
           {
               "InternalID": 3,
               "Name" : "Item 3"
           }
    ]
}

Now I loop this list with a ng-repeat and show the value of "Name" in a div. One item is always active. For example, the item with the "InternalID" = 1 ist at this moment active. The next item in the list, this means in this example the item with the "InternalID" = 2, should become a class with a specifique style. And when I set the item with the "InternalID" = 2 as active, the next item in the list would be the item with the "InternalID" = 3, and this should get the class with the specifique style. I tried it with like this:

In my controller (ctrl) I've set and get the current value of my list. Than I use the ng-init to get the active index by comparing the "InternalID" of my value and my item. After that, I use the ng-class to give my specifique class to the item in the list, which index is + 1 than my active index, so it should be the next item in the list. This works fine, when a open it the first time. After I set a new active item, it does'nt change. The first item with the specifique class does'nt change, it's always the same.
What is the problem here? It was hard to explain it, I hope it's good to understand.
Thanks

A: ng-init executes only once. Why don't you let the controller handle the calculation and pass the template something like this:
{
    "Items" : [
           {
               "InternalID": 1,
               "Name" : "Item 1"
           },
           {
               "InternalID": 2,
               "Name" : "Item 2",
               "class": "special-class"
           },
           {
               "InternalID": 3,
               "Name" : "Item 3"
           }
    ]
}

And let the ng-repeat just put the class on the corresponding item.
You'll have to update the list every time you activate one item. But it's not so hard.

A: I suggest moving quite some logic to the controller or scope:

angular.module("demo", [])
  .controller("myctrl", function() {
    var ctrl = this;

    ctrl.list = {
      "Items": [
        { "InternalID": 1, "Name": "Item 1" },
        { "InternalID": 2, "Name": "Item 2" },
        { "InternalID": 3, "Name": "Item 3" },
        { "InternalID": 4, "Name": "Item 4" }
      ]
    };

    ctrl.activeItem = null;
    ctrl.nextItem = null;

    ctrl.selectItem = function(item) {
      ctrl.activeItem = item;
      var idx = ctrl.list.Items.indexOf(item) + 1;
      ctrl.nextItem = (idx < 0 || idx >= ctrl.list.Items.length) ? null : ctrl.list.Items[idx];
    }
  });
div { margin: 10px; padding: 5px; border: 2px solid gray; }
.cNextItem { background: red; }
.cActiveItem { background: green; }

    {{ item.InternalID }} => {{ item.Name }}
    <button ng-click="ctrl.selectItem(item)">select this item</button>

A: Why not simplify it to:
$scope.activeId= null;
$scope.setActiveId = function (id) {
   $scope.activeId= id;
};


text:
Q: Who designed exceptions? Where did exceptions and exception handling come from?
I like how .NET uses it, I like how C++ supports it (but libraries unfortunately use return code or is written in C instead). I know its pretty much standard in all new languages, but who designed it first or where did it come from?
Is C++ the first language to use it? I don't know of any other that is older.

A: Hof, Mössenböck and Pirkelbauer (in their 1997 paper Zero-Overhead Exception Handling using Metaprogramming) affirm that the concept of exceptions was suggested in the seventies, referring to John B. Goodenough's 1975 Exception handling: Issues and a proposed notation paper in the Communications of the ACM.  In it he conflates modern exception handling with the general idea of registering callbacks, and his proposed notation looks more like modern Attribute metadata specifications than try/catch, but it (or at least its section 2) is a great overview of the state of exception handling in the mid-seventies.
Perhaps of note is also the raise/rescue mechanism in Alef, which one can view as a primitive form of catch blocks, lest we think they sprang fully-formed from Stroustroup's brow like Athena from Zeus's.

A:
Raising and trapping exceptions has been around for quite a time.
  This site says exceptions were introduced in PL/I:
  http://www.math.grin.edu/~rebelsky/Courses/CS302/98S/Outlines/outline.02.html
which was in 1967, according to this page (includes an extensive but
  not exhaustive chart of computer languages and features):
  http://community.borland.com/article/0,1410,22741,00.html
Many languages picked up this technique -- ADA, ALGOL, FORTRAN, ML [...]

Quoted from here.
Wikipedia has more detail about exception handling in PL/1. That page also refers to PL/1 being the first. Of course, this is no scientific proof :-)
As for who in person designed PL/1, the article mentions no names, only various committees at IBM.


text:
Q: How can I allow builtin types to subtract custom class? I have a class like this:
class Variable:

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other

And I want to be able to pass it into general functions and still allow normal operations on it.
Doing this works:
X = Variable(0)
print(X-1)  # -1

However the inverse results in a TypeError:
print(1-X)
TypeError: unsupported operand type(s) for -: 'int' and 'Variable'

Inheriting from float and using a __new__ constructor fixes that issue:
class Variable2(float):
    def __new__(cls, *args, **kwargs):
        return float.__new__(cls, args[0])

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other

x = Variable2(0)
print(1-x)  # 1.0

However when I change the value in X, the subtraction is now wrong:
x.val = 2
print(1-x)  # still #1.0

Is there a way to allow 1-x to use the internal value held by the class?


text:
Q: Percentage Change vs. Percentage Difference So in this particular scenario, I have two processors running the same benchmark. One is faster than the other, with the faster result being the one that takes the least amount of time to complete.
As an example, Processor A completes the benchmark in 42.5 seconds, and Processor B completes it in 32.9 seconds.
The goal here is to obtain how much faster Processor B is against Processor A . When the benchmark results in a "higher is better" result, that's simple. You divide the larger number by the smaller number.
With results indicating "lower is better," however, do I do the same thing? Am I finding the percentage change between the two numbers, or the percentage difference?
Can someone help explain the difference between these two calculations, and which one I need?
Up until now, I've been using #1.

*

*((42.5 / 32.9) * 100) - 100 = 29.179%

*100 - ((32.9 / 42.5) * 100) = 22.588%

A: It's useful to think of it this way: A processor's speed is inversely proportional to the time it takes to complete the task. Therefore, for processor A we can give a "non-dimensional speed" of $\frac{1}{42.5}$. For processor B, this value is $\frac{1}{32.9}$. It's easy to see that B is faster in this case, because the speed is greater.
Now you want to compare their speeds, or in particular answer the question "How many per cent is processor B faster than A?". So you can just calculate the ratio of their speeds like this:
$$
\frac{\left( \frac{1}{32.9}\right)}{\left( \frac{1}{42.5}\right)} = \frac{42.5}{32.9}\approx 1.2917
$$
Therefore, our answer is: Processor B is faster than processor A by $29.2~\%$.
Should you calculate it the other way around, you'd be asking the question "How much slower is processor A compared to processor B?".


text:
Q: files from the array are not loaded I store files in the laravel storage and download them by name
in this case, the file is being downloaded
 <button class="btn btn-success">Download</button>

but not here
 <button class="btn btn-success">Download</button>

Why is this happening?
because the array contains the same value


text:
Q: Induced current in a closed loop in opposing directions When a magnetic field is given to the loop as in the figure(sorry for the horrible drawing);

I'm told that there will be an anticlockwise current induced in both the 'inner' and 'outer' loops, resulting in opposing currents, and since the area of the outer loop is larger, the net current flows so that it's anticlockwise in the outer loop.
I'm confused. Isn't there just one closed loop here? Doesn't a circuit have to be closed for current to be induced in it?

A: When the B-field is applied as indicated in the picture, according to the Maxwell-Faraday law:
$$\nabla\times E = -\frac{\partial B}{\partial t}$$
In order to know the direction of the induced E-field, the curl follows the right hand rule. So, because of the minus sign, the conventional current flows counterclockwise.
The only role of the inner part of the loop is to reduce its area $S$, reducing the magnetic flow. If the same length of wire formed a circle for example, $S$ would be bigger. The integral form of the equation above is:
$$\oint_{\partial \Sigma} \mathbf{E} \cdot \mathrm{d}\boldsymbol{\ell}  = - \frac{\mathrm{d}}{\mathrm{d}t} \iint_{\Sigma} \mathbf{B} \cdot \mathrm{d}\mathbf{S}$$
Or, renaming some terms:
$$\epsilon= -(d\phi/dt)= -(d(BS)/dt)  $$

A: Well you are right in your understanding that there is only one loop. Anyone who has used the terms "inner" and "outer" must specify what he/she means.
There is one more thing about your question. You seem to have a bit of problem with the concept here. Let me explain.

This is what your loop looks like with the magnetic field. Now the current that is induced in this is zero. The reason for this is Faraday's law that governs electromagnetic induction.
$$\epsilon = -N\frac{d\phi}{dt}$$
where,
$\epsilon$ is the induced electromotive force (or more appropriately voltage)
$\phi$ is the flux of the magnetic field through the loop
$N$ is the number of loops.
For our case, $N$ is $1$.
Now if our loop is a conductor, we will observe current. And in such a case, how do we determine the direction of our current? The magnitude is given by ohm's law.
There are two ways which you can use to arrive at the direction.
Method 1: Using Lenz's law
According to Lenz's law, the induced current will be such that the magnetic field due to it will oppose the original magnetic field. If you are a high-school student, it is highly recommended you use this law because of its simplicity.
Method 2: Using Faraday's Law
Faraday's law is self sufficient in determining the direction of the current. For this you need to have a look at one of the Maxwell's equation:
$$\nabla \times \mathbf{E} = -\frac{\partial{\mathbf{B}}}{\partial{t}}$$
The mathematical complexity should be evident by now. However, if you are well acquainted with vector calculus, you may proceed as follows:
You have the Magnetic Field, therefore you can obtain the Electric field in its vector form. After doing so(it will be a lengthy process) you can analyze the effect of the electric field on an electron in the conductor. With the direction of electron movement you can get the direction of current.
Now use these laws in the case you have mentioned, and you will see that the current is zero.
Hint: The magnetic field and the area of the loop are both constant with no time dependence.
Hope this helps you! Feel free to comment and ask any questions you have!

EDIT 1:
Okay so in the comments the OP asked about why the current is zero. This edit is regarding that comment.
Since you want to know why the current is zero, you must take a look at the laws governing the magnitude of the current.
In Faradays law, we see the term $\phi$ which is the flux of the magnetic field through the loop. This flux is given by,
$$\phi=\mathbf{B.A}$$
Now we have three quantities that may change with time:

*

*The Magnetic field $\mathbf{B}$

*The magnitude of Area of the loop $A$

*The angle between the normal to the loop surface(direction of the Area vector) and the magnetic field.

Now look at your case to see if $\phi$ which is given by the above expression is a function of time. You will find the answer.

A: For simplicity assume that magnetic field is uniform in a downward direction and increasing in magnitude at a constant rate. I will explain in a minute why I have made this assumption from the information that you have provided.
Without saying anything about the nature of the loop other than it is of constant area $A$, the rate of change of magnetic flux is $\frac {d(BA)}{dt} = A \frac {dB}{dt}$ and this is the induced emf in the loop (Faraday).
If the loop is conducting then the induced emf induces a current in the circuit which you have stated to be anticlockwise in the top left hand corner and the same current flow though each part of the loop although there may be ambiguity about direction if one tries to use the terms anticlockwise and clockwise for each segment of the loop.
At each part of the loop the induced current produces a magnetic field which is upwards within the loop ie in the opposite direction to the increasing external magnetic field.
This is Lenz's law in action as the induced current is trying to reduce the rate at which the magnetic field (and hence the magnetic flux) is changing within the loop.
That is happening for all segments of the conducting loop and so those bits of the loop where the current seems to go clockwise still produce a magnetic field in opposition to the changing external magnetic field.
So the shape of the loop does not matter.
What does matter is the enclosed area $A$, the rate of change of external magnetic field (and the resistance of the loop).


text:
Q: Is there any way to delete shared preference value from our local storage without knowing full name of the key? I want to delete values from my sharedPreference but I don't know the exact name of my key. Means I want to delete all values using a regex which contains some specific words for e.g. if any key contains world "text" that value should be deleted.
Thanks in advance.


text:
Q: MySQL query optimization related to unified ID I have 2 tables. In one table I add events, ID are auto-increment. The second table contains personal events.
So if I create event, it adds to both tables.
Here down below is a example of my code. So first of all I add a new event to general table. Then I want to add the same event to schedule table, but I need to get the ID of just added event. So I execute that second query.
Is there any optimized way how to do this or at least get the ID of just added event without extra query?
mysql_query("INSERT INTO events (title, description, user) VALUES ('$title', '$description', '".$user['id']."')");

$id = mysql_fetch_array(mysql_query("SELECT id FROM events WHERE user='".$user['id']."' ORDER BY date_added DESC LIMIT 1"));

mysql_query("INSERT INTO schedule (uid, event) VALUES ('".$user['id']."', '".$id['id']."')") or die(mysql_error());

A: mysql_insert_id() is what you are after, I think...
You could also use the MySQL native LAST_INSERT_ID() in your second INSERT query:
mysql_query("INSERT INTO schedule (uid, event) VALUES ('".$user['id']."', LAST_INSERT_ID())") or die(mysql_error());

...and skip retrieving the ID in PHP altogether.

A: there is no "optimized" way.
there is the right way of getting inserted id, called mysql_insert_id().

A: I guess you're looking for the last inserted id: LAST_INSERT_ID()

A: the native php function mysql_insert_id() will do it for sure
http://php.net/manual/en/function.mysql-insert-id.php
consider wrapping in a transaction?  under high concurrency you could end up with the wrong id using this


text:
Q: Networked Remotely-Managed Media Player We're looking to replace our current in-store video distribution model, which involves the production of a DVD ISO and several people burning discs and shipping them out.
Cost-benefit analysis shows that utilizing the existing WAN connections at each store to update a playlist weekly with new videos instead of shipping a DVD to each location once a month would be more cost-effective.
However, I'm having some trouble locating a device that does or can be reprogrammed to do what we want.
We need something that can be remotely managed over Ethernet, can sync a folder of videos with a remote server, and play those according to a playlist file that will also be provided.  It shouldn't really need end-user interaction, nor would we want that.  We prefer that it have component or HDMI output, but will settle for S-Video/Composite if that is what is available.
We don't want a full box running this at each location, something embedded that just plays videos/music will do, but it must have the functionality, or the openness that we can add the functionality, that we need.
Our current budget for this project allows up to about $400 per device.  Any ideas?

A: you can use XBMC with an ION nettop, which costs about $200-300 and has HDMI output.
It can be managed locally or through a web interface remotely.

A: Last year at my church we ended up with this solution to display weekly announcements and schedules in the lobby on a TV.  I think it will do everything you need except stay in budget :/.  It's about 3x your budget and is standard def only.  You didn't say if you required HD but I'm guessing by reading between the lines of using HDMI that it's probably desirable.  The HD units we found were 2-3x the cost of the standard def units. But basically this is an embedded Linux box running samba and apache serving a web application for remote control, putting together playlists of images, audio, and videos as well as allow for scheduling.
The cheapest way and possibly only option with your budget constraints is to go the DIY route and build a small computer with a hdmi video card. Then use standard file shares with rdesktop or vnc to connect to the box and make your playlists and get them playing.  Then if you're running Windows on it you may be able to write some vbs or wmi scripts with the scheduler to stop/start the media player playing a certain playlist.  If you choose Linux then you should be able to use some cron scripts to do the scheduling bit.  Rsync or any number of file sync solutions should be able to distribute your files....even a private bittorrent would probably work well.

A: I just had another thought.  Although probably not as ideal but if your real underlying goal is for a cheaper distribution model this may work.
Make your DVD as normal and then create an iso of it.  Then setup a private bittorrent server to distribute the image to all the stores using an rss feed.  A computer with a burner is probably already present in most stores...if not these are relatively cheap.


text:
Q: Joomla site stop working after install libmysql-ruby libmysqlclient-dev Ruby on Rails and Joomla site hosting on same server. after install libmysql-ruby libmysqlclient-dev joomla site giving me 'Error displaying the error page: Application Instantiation Error' error..
i already check configuration.php in joomla which is correct ..
Rails site is up and running but Joomla !!!!!
any suggestion how can fix joomla site problem..


text:
Q: Running 2 jQuery on same page I am trying to use 2 jQuery objects on the same page, however, I cannot seem to get them both working simultaneously, If I play around with the code I can get one or the other working but not at the same time. I am quite new to this stuff so really appreciate your help on this.
The code in the head section is as follows
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js">
</script>

    <script src="jquery.easing.1.3.js" type="text/javascript"></script>
  <script type="text/javascript">
        $(document).ready(function() {

            $curtainopen = false;

            $(".rope").click(function(){
                $(this).blur();
                if ($curtainopen == false){
                    $(this).stop().animate({top: '0px' }, {queue:false, duration:350, easing:'easeOutBounce'});
                    $(".leftcurtain").stop().animate({width:'60px'}, 2000 );
                    $(".rightcurtain").stop().animate({width:'60px'},2000 );
                    $curtainopen = true;
                }else{
                    $(this).stop().animate({top: '-40px' }, {queue:false, duration:350, easing:'easeOutBounce'});
                    $(".leftcurtain").stop().animate({width:'50%'}, 2000 );
                    $(".rightcurtain").stop().animate({width:'51%'}, 2000 );
                    $curtainopen = false;
                }
                return false;
            });

        });
    </script>

A: i think the problem is that there is conflict
jQuery defines a nice solution to resolve conflicts: jQuery.noConflict. By using this function you can define your own name, where jQuery will be accessible.
var $jq = jQuery.noConflict(true);


text:
Q: HTML button submitting form I have a javascript function which changes some fields on a form, I have two buttons one to call javascript function, and the other submits the form. Problem is the button to call javascript function submits the form. I have tried changing button type to "button", which brakes the button and it does not work.
 $("#button1").click(function () {

        //$("#usernameField").attr("value","");
        //$("#passwordField").attr("value","");

        if (authType == 0) {

            $("#usernameLabel").hide();
            $("#usernameField").hide().find('input:text').val("");

            $("#passwordLabel").hide();
            $("#passwordField").hide().find('input:text').val("");

            //$("#initialCatalogLabel").show();
            //$("#initialCatalogField").show();

            document.getElementById("button1").textContent = "Intergrated";
            $('#authType').val(1);

        }
        else {

            $("#usernameLabel").show();
            $("#usernameField").show();
            $("#passwordLabel").show();
            $("#passwordField").show();
            //$("#initialCatalogLabel").hide();
            //$("#initialCatalogField").hide();

            document.getElementById("button1").textContent = "SQL Authentication";
            $('#authType').val(0);
            //return false;

        }

Create

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

<fieldset>
    <legend>connection</legend>

       Authentication Type

      <button id="button1" value="Intergrated" name="intergrated">SQL Authentication</button>

        Connection Name

        @Html.EditorFor(model => model.conName)
        @Html.ValidationMessageFor(model => model.conName)

       Data Source

        @Html.EditorFor(model => model.dataSource)
        @Html.ValidationMessageFor(model => model.dataSource)

       Initial Catalog

        @Html.EditorFor(model => model.initialCatalog)
        @Html.ValidationMessageFor(model => model.initialCatalog)

       Username

       @Html.EditorFor(model => model.username)
        @Html.ValidationMessageFor(model => model.username)

       Password

        @Html.EditorFor(model => model.password)
        @Html.ValidationMessageFor(model => model.password)

        <input type="hidden" name="authType" id="authType" value="@Model.authType" />

        <input type="submit" value="Create"/>
        @{
if (!string.IsNullOrEmpty(ViewBag.error))
{

                   @ViewBag.error

}
        }

</fieldset>

}

A:  <input type="button" id="button1" value="Integrated" />

Maybe the wrong type of button you tried?

A: You need to target the form, not the button
No need to use e.preventDefault(); when using jquery.
$('form').submit(function(e){
    return false;
});


text:
Q: Why is my GPA Double value not working correctly in Swift? why isn't this code working when I addA for the first time it works but then it goes to 2.66 and keeps going down from there when it should stay at 4.0.
import UIKit

//Quantity of          A    A-   B+   B    B-   C+   C    C-   D+   D    D-   F
var gradesQuantity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
var gradesAdded = 0.0
var gpa = 0.0

func addGrades(grades: [Double]) -> Double {
    for grade in grades {
        gradesAdded += grade
        if gradesQuantity[0] <= 0 {
            gradesQuantity[0] = 0
        }
    }

    return gradesAdded
}

func calcGPA(grades: [Double]) -> Double {
    gpa = (grades[0] * 4.0 + grades[1] * 3.7 + grades[2] * 3.3 + grades[3] * 3.0 + grades[4] * 2.7 + grades[5] * 2.3 + grades[6] * 2.0 + grades[7] * 1.7 + grades[8] * 1.3 + grades[9] * 1.0 + grades[10] * 0.7) / gradesAdded

    return gpa
}

class ViewController: UIViewController {

    @IBOutlet weak var GPALabel: UILabel!
    @IBOutlet weak var GPANumber: UILabel!
    @IBOutlet weak var AQuantity: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func AddA() {
        gradesQuantity[0] += 1.0
        addGrades(gradesQuantity)
        let x = calcGPA(gradesQuantity)
        GPANumber.text = String(x)
        AQuantity.text = String(Int(gradesQuantity[0]))
    }

    @IBAction func SubtractA() {
        gradesQuantity[0] -= 1.0
        addGrades(gradesQuantity)
        let x = calcGPA(gradesQuantity)
        GPANumber.text = String(x)
        AQuantity.text = String(Int(gradesQuantity[0]))
    }
}

can somebody please help i put this in playground and add code under it that is the same in the buttons and it works but in the project it doesnt work. This leads me to believe the problem is in the addA and subtractA buttons.

A: You are writing functions with side effects (modifying external variables). Try to avoid that. Also, you may want to have a bit more structure in your program. Associate positional value of gradesQuantity to a letter grade is ok, but you can do better with a Dictionary:
enum GradeLetter: Double {
    case A = 4.0
    case AMinus = 3.7
    case BPlus = 3.3
    case B = 3
    case BMinus = 2.7
    case CPlus = 2.3
    case C = 2
    case CMinus = 1.7
    case DPlus = 1.3
    case D = 1
    case DMinus = 0.7
    case F = 0
}

func calculateGPA(grades: [GradeLetter: Int]) -> Double {
    let courseCount = grades.reduce(0.0) { aggregate, grade in
        return aggregate + Double(grade.1)
    }
    let totalPoint = grades.reduce(0.0) { aggregate, grade in
        return aggregate + grade.0.rawValue * Double(grade.1)
    }

    return totalPoint / courseCount
}

Let's say you have 1 A, 2 A- and 3 B:
var grades = [GradeLetter: Int]()
grades[.A] = 1
grades[.AMinus] = 2
grades[.B] = 3

print(calculateGPA(grades))

A: I think the root cause of your problem is that you are doing too much work. If you delete the addGrades function (which isn't really adding any functionality as far as I can tell) and replace your AddA and SubtractA functions with the following, then it will work as intended:
@IBAction func AddA() {
    gradesQuantity[0] += 1.0
    gradesAdded += 1.0
    GPANumber.text = String(calcGPA(gradesQuantity))
    AQuantity.text = String(Int(gradesQuantity[0]))
}

@IBAction func SubtractA() {
    gradesQuantity[0] -= 1.0
    gradesAdded -= 1.0
    GPANumber.text = String(calcGPA(gradesQuantity))
    AQuantity.text = String(Int(gradesQuantity[0]))
}

For further development, I would recommend creating a subclass array that has functions to add and subtract grades and return the GPA. This should make things much more readable and reusable.


text:
Q: how to change relativeLayout background color from inside a thread I have a button btnSwitch and I want to make the flash light blink and the background color to change continuously as long as I'm holding the button and to stop doing that when I release my finger the colors for the background are white and black the flash is working right but the background changes one time only the black and never returns to white.
This is the code:
public class MainActivity extends AppCompatActivity {
    public static RelativeLayout relativeLayout;
    public Button btnSwitch;

      btnSwitch.setOnTouchListener(new View.OnTouchListener() {
            private Handler handler;
            @Override
            public boolean onTouch(View v,  MotionEvent event) {

                switch (event.getAction()){

                    case MotionEvent.ACTION_DOWN:
                        if (handler != null) return true;
                        handler = new Handler();
                        handler.postDelayed(thread, 14);
                        break;

                    case MotionEvent.ACTION_UP:
                       if (handler == null) return true;
                        handler.removeCallbacks(thread);
                        handler = null;
                        break;
            }
                return false;
            }
           Runnable thread= new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        try {
                            this.wait(7);
                            relativeLayout.setBackgroundColor(Color.BLACK);
                            turnonflash();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        try {
                            this.wait(7);
                            relativeLayout.setBackgroundColor(Color.WHITE);
                            turnofflash();

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        handler.postDelayed(this, 14);
                    }}
           };
        });
    }

and this is the XML FILE
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/backv">

<Button

    android:id="@+id/btnSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dip"

    android:text="switch"

    android:contentDescription="@null"
    />

A: You need to call relativeLayout.setBackgroundColor(color);on the UiThread:
 activity.runOnUiThread(new Runnable() {
      @Override
          public void run() {
              relativeLayout.setBackgroundColor(color);
     }
 });


text:
Q: Finding a string inside a string twice as big effectively I'm looking to see if the difference between every adjacent number in an array is the same as another array, or a rotation of it, for example
A = {1,2,4}, so the differences are {1,1,2}
B = {4,6,7}, the differences are {1,2,1}

If all elements in {1,2,1} were moved clockwise one-element, the result is {1,1,2}, which is correct.
so far I convert the differences to strings, and then see if the differences of the second array is found in the first concatenated with itself
valid if "1 2 1" is in "1 1 2 1 1 2"

my code so far looks like this
        count is the length of the array, both have the same length
    int c = count - 1;
    StringBuilder b1 = new StringBuilder();
    StringBuilder b2 = new StringBuilder();
    for (int i = 0; i < c; i++) {
        b1.append(array1[i + 1] - array1[i]);
        b1.append(" ");
        b2.append(array2[i + 1] - array2[i]);
        b2.append(" ");
    }
    b1.append((array1[0] - array1[c]) + d);
    b1.append(" ");
    b2.append((array2[0] - array2[c]) + d);

    String a2 = b2.toString();
    String a3 = b1.toString() + b1.toString();

    System.out.println(a3.contains(a2) ? "valid" : "not valid"); //bottleneck here

My problem is when I use big arrays (up to about 250,000 elements) I get a massive bottleneck at the last line with the .contains(). I'm wondering if there is either a faster way of check if its inside the method than what I'm using, or if I can check while building up the string, or if there is a completely different way of doing this?

A: You need a more efficient algorithm then the one that is used in contains method(it actually depends on a concrete implementation, but it looks like it is not efficient in the version of Java you are using).
You can use Knuth-Morris-Pratt algorithm: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm. It has linear time and space complexity in the worst case so it works fast even for very big arrays. Note that there is no need to convert an array to a string, because this algorithm works for arrays, too.


text:
Q: How can I view a part of an other website on my website? I want to show a specific part of an external website on my website.

How do I do this?
Can this action be illegal in some way?
**no embed available on this website. It looks pretty old too.

A:

and this css#ab {display : block;overflow : hidden}iframe{margin: -50px -60px}
use minus margin so it will goes in that div and unuseful content will not be displayed in webpage. specify height of div and iframe

A: im not sure if u can do that.. der may be a few privacy issue.. But u can show a different page in you webpage by using the iframe tag.
http://www.w3schools.com/tags/tag_iframe.asp
Or HTML 5 supposrt video tags.. So if you can download the video u can display it using the video tags..
http://www.w3schools.com/html/html5_video.asp

A: You can do it using iframes. This HTML element can embed another document from another page, but it also acts as other page.
Simple targetting with the selectors does not seem to be a solution.
But you could use iframe to load the page and than extract part of it with jQuery.
I think this should work for you:
video = $("your_frame_selector").contents().find("selector_of_the_DOM_element")

A: Here is the simplest way to do this:
http://jsfiddle.net/hAtul/vk9avk7e/
Thank you guys :) !
CSS:

  #ab {
      display : block;
      overflow : hidden;
      width: 724px;
      height: 391px;

}
  iframe {
            height: 387px;
            width: 641px;
            margin-left: -42px;         }

HTML:


text:
Q: SSD totally bricked after installing in different laptop I've never had this issue before:
I had an OWC ssd in my 2009 macbook pro, and I put it into a 2008 aluminum macbook.  It worked perfectly.  Then, I took it out and put it back in my macbook pro, but the computer wouldn't start up.  It wouldn't even get past the grey screen (not even an apple logo!).  Now it won't work in either computer.
I've tried starting up in recovery mode: nada.
I put it in my external HD enclosure and connected it to my macbook air.  Nothing is showing up in the disk utility or in disk warrior (and yes, the enclosure works OK, I checked the SATA cable, etc, etc).  I'm at a loss for what to do next.

A: This is more than likely a hardware problem with the SSD. Specifically, the SATA input/or SSD controller, based on the following:

*

*The problem occurred after swapping the drive out from one machine into another.

*You have connected the SSD to three different SATA cables (two internal, one external). None have recognized it. This rules out a bad SATA cable.

*The drive is not recognized in any form of recovery. This rules out a corrupted filesystem.

*The drive does not even mount when connected externally. This rules out a corrupted partition scheme and is a common symptom of physical failure.

All of the above point to physical failure of the drive.
First, I'd clean the SATA input on the drive using 99% isopropyl alcohol (not 91!%), then test again using the mentioned enclosure.
If it still isn't mounting, at all, check the drive's warranty and contact the manufacturer for a replacement, if applicable. Best of luck.


text:
Q: Convert classis asp if statement to php Am still very new to PHP and need to convert existing pages to php, could anyone show me how to convert the code below to php please?
<%If rsMembership.Fields.Item("MemberOfGroup").Value = "0" then response.write ("Main Member")Else response.write ("Belongs to Member = ")&(rsMembership.Fields.Item("MemberOfGroup").Value)End if%>

Update: This works, not sure if its correct, cant seem to be able to put value as ="0", only works if I put <"1"
    <?php
if ($row_rsMembership['MemberOfGroup']< "1")
   {
   echo "Main Member";
   }
else
   {
   echo "Belongs to Member =" . $row_rsMembership['MemberOfGroup'];
   }
?>

A: To compare a value in a PHP If statement use == and not =, i.e.:
if ($row_rsMembership['MemberOfGroup'] == "0")
   {
   echo "Main Member";
   }
else
   {
   echo "Belongs to Member =" . $row_rsMembership['MemberOfGroup'];
   }


text:
Q: Best known bounds for Ramsey numbers I realize a similar question has been asked before but what I want to know is a little different and is not answered by the link in the answer to that question. I am interested in knowing the best known general upper and lower bounds (non-asymptotic) for an arbitrary Ramsey number $R(k,l)$. Similarly the best known general upper and lower bounds for an arbitrary diagonal Ramsey number $R(k,k)$. It would be good if someone could also tell me asymptotic bounds in these cases as well.(I am not sure whether wikipedia is upto date.)
Thanks.

A: I suggest you take a look at this paper by  Radziszowski. This site is also up to date with new results about $R(k,l)$.


text:
Q: Process exited with value 3221225477 where is the problem? whenever i execute the program it returns "Process exited with value 3221225477" and nothing else, i know it means out of bounds or something like that but i cant see where  the problem here is, everything to me looks like it should work i know for a fact it in my "pas" function because the others are copy-paste and they always have worked, here is my code:
#include<bits/stdc++.h>
using namespace std;
string longDivision(string number, int divisor)
{

    string ans;

    int idx = 0;
    int temp = number[idx] - '0';
    while (temp < divisor)
       temp = temp * 10 + (number[++idx] - '0');

    while (number.size() > idx)
    {

        ans += (temp / divisor) + '0';

        temp = (temp % divisor) * 10 + number[++idx] - '0';
    }

    if (ans.length() == 0)
        return "0";

    return ans;
}

string multiply(string num1, string num2)
{
    int len1 = num1.size();
    int len2 = num2.size();
    if (len1 == 0 || len2 == 0)
    return "0";

    vector<int> result(len1 + len2, 0);

    int i_n1 = 0;
    int i_n2 = 0;

    for (int i=len1-1; i>=0; i--)
    {
        int carry = 0;
        int n1 = num1[i] - '0';

        i_n2 = 0;

        for (int j=len2-1; j>=0; j--)
        {
            int n2 = num2[j] - '0';

            int sum = n1*n2 + result[i_n1 + i_n2] + carry;

            carry = sum/10;

            result[i_n1 + i_n2] = sum % 10;

            i_n2++;
        }

        if (carry > 0)
            result[i_n1 + i_n2] += carry;

        i_n1++;
    }

    int i = result.size() - 1;
    while (i>=0 && result[i] == 0)
    i--;

    if (i == -1)
    return "0";

    string s = "";

    while (i >= 0)
        s += to_string(result[i--]);

    return s;
}

    string pas(string a, int b){

string c;
c[0]='1';
for(int i=1; i<=a.size()-1; i++){
    c[i]='0';
}
string a1=a;
a1[0]=a1[0]-c[0];
string p=to_string(b);
string k69=longDivision(a1,b);
string k=multiply(k69,p);

string pasuxi=a;
int ksize=k.size()-1;
for(int i=a.size()-1; i>=a.size()-p.size(); i--){
    if(k[ksize]>a[i]){
        pasuxi[i]=a[i]-k[ksize]+10;
        a[i-1]=a[i-1]-1;
        pasuxi[i-1]=a[i-1];
            }else{
                pasuxi[i]=a[i]-k[ksize];

            }
ksize--;

}

return pasuxi;

}

int main(){

    int n,k;
    cin>>n>>k;
    string a;
    string k1=to_string(k);
    for(int i=0; i<n; i++){
        if(i<k1.size()){
            a[i]=k1[i];
        }else{
            a[i]='0';
        }

    }

    cout<<pas(a, k);

system("pause");

}