Q:

Skolem sequence generator algorithm

My teacher wants me to write a function that get a integer value N and return array that his length is 2n and contains a skolem sequence for the value.
For example: function(4) will return {4,2,3,2,4,3,1,1}
I don't have idea how to do that.

A:

The Skolem sequence for a number n is a sequence of integers of size 2×n that meets two criteria:

for every non-negative number k < n, there exist exactly two elements si, and sj in the sequence such that si = sj = k
if si = sj = k and i < j then j−i = k

See http://mathworld.wolfram.com/SkolemSequence.html
Basically, this means that you need to create a sequence with numbers from 1 to n where each number appears twice. To turn the sequence into a skolem sequence, the two 1's have to be next to each other, the two 2's have to have one number between them, the 3's have to have 2 numbers between them and so on.
This algorithm is more difficult than one would think to create. The easiest way to do this is to check every permutation of your sequence, and  return the first one that works. This is (2n)! complexity, which is horribly slow. Here is one reference for an algorithm which doesn't have n! complexity:
http://www.cs.mun.ca/~dchurchill/pdf/honours.pdf
I have written the naive algorithm in C++. This will generate Skolem sequences for any given input. This algorithm is horribly slow, but I hope you get the point:
#include<iostream>
#include<vector>
#include<algorithm>
void start(int num, std::vector<int>& v) { //creates the |2n| sequence
        for(int i = 1; i<=num; i++) {
                v.push_back(i);
                v.push_back(i);
        }
}
bool check(std::vector<int>& v) { //checks to see if sequence is a skolem sequence
        for(int i = 1; i<=v.size()/2; i++) {
                auto j = std::find(v.begin(), v.end(), i);
                auto k = std::find(j+1, v.end(), i);
                if(k-j != i) {
                        return false;
                }
        }
        return true;
}
void skolem(int num, std::vector<int>& v) { //permutes the vector to find skolem sequences
        start(num, v);
        while(std::next_permutation(v.begin(), v.end())){
                if(check(v))
                        break;
        }
}
int main()
{
        int num;
        std::cin>>num;
        std::vector<int> v;
        skolem(num, v);
        std::cout<<"found it"<<std::endl;
        print(v);
}

This algorithm will only work for small numbers (less than 10). If you need to process larger sequences, I suggest you check out that link above.


Q:

Cannot refer to the non-final local variable button defined in an enclosing scope, Random method error

I am getting an error in my project with eclipse:
Cannot refer to the non-final local variable button defined in an enclosing scope

This my class:
import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {
Button buttonblack;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     buttonblack = (Button)findViewById(R.id.Button01);

     startRandomButton(buttonblack);

}

public static Point getDisplaySize(@NonNull Context context) {
    Point point = new Point();
    WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    manager.getDefaultDisplay().getSize(point);
    return point;
}

private void setButtonRandomPosition(Button button){
    int randomX = new Random().nextInt(getDisplaySize(this).x);
    int randomY = new Random().nextInt(getDisplaySize(this).y);

    button.setX(randomX);
    button.setY(randomY);
}

private void startRandomButton(Button button) {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            setButtonRandomPosition(button);
        }
    }, 0, 1000);//Update button every second
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

The problem is in this method:
private void startRandomButton(Button button) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setButtonRandomPosition(button);// Cannot refer to the non-final local variable button defined in an enclosing scope
            }
        }, 0, 1000);//Update button every second
    }

Can someone help me fix this? Or suggest any other code that could be better than this?

A:

You have declared Button buttonblack; Globally in MainActivity..
you can pass buttonblack like this  setButtonRandomPosition(buttonblack); without referring it as final.


Q:

Title on Action Bar displaying garbage value

I'm trying to display the name of the Listview item on the action bar as it's title on the next activity screen using intents.
Here is my code.
MathematicsDBEntry.java
public class MathematicsDBEntry extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Intent i = getIntent();
        String newActionBarTitle = i.getStringExtra("Position");

        super.onCreate(savedInstanceState);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(newActionBarTitle);
        setContentView(R.layout.activity_mathematics_dbentry);

    }

}

MathsActivity.java
public class MathsActivity extends ListActivity implements AdapterView.OnItemClickListener{

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

        // storing string resources into Array
        String[] math_data = getResources().getStringArray(R.array.maths_list_data);

        ListView listView = getListView();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, math_data);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView textView = (TextView) view;
        //Toast.makeText(this, textView.getText().toString() + " " + position, Toast.LENGTH_LONG).show();
        Intent intent = new Intent(getApplicationContext(), MathematicsDBEntry.class);
        intent.putExtra("Position", textView.toString());
        startActivity(intent);
    }
}

But all I get is the garbage value shown below.

A:

You need to use the getText() method of TextView to get the data from it.
You need to change:
intent.putExtra("Position", textView.toString());

to:
intent.putExtra("Position", textView.getText().toString());


Q:

json data char '&' disturbs ajax post request data

i am generating a json string using JSON.stringify and my json string will be like
jsonstring=[{"step1":[{"nm":"John & joe"},{"title":"Hello & hai"}]},{"step2":[{"desc":"1234"},{"usr":"abc@xyz.com"}]}]`

i am escaping & with \& and sending this json string to server through ajax.
$.ajax({
url:"test-usr-data.php",
type:"post",
data:"usrdata="+jsonstring,
success: function(response){
console.log("data is "+response);
},
complete:function (jqXHR, textStatus){
console.log("ajax Request completed"+textStatus);
    }
});

The problem is with & char in json string, even though i am escaping & to \& data is not posted to server but ajax request status is success.
I tried removing & from json string it works fine and data is posting to server correctly.
Can any one help me in correct way to escaping & in json string.

A:

Who told you that escaping in URL's works by prepending a backslash?
jQuery will take care of it, just do
data: {usrdata: jsonstring},

FYI: You could use encodeURIComponent as well
data: "usrdata=" + encodeURIComponent(jsonstring),


Q:

Force directed graph in D3 not showing the graph

I am trying to imitate a force directed graph from the d3.js website:  http://bl.ocks.org/mbostock/4062045
I created my own example here:
https://plnkr.co/edit/vTRy5akEzGlhcfNblEDP?p=preview
Writing below junk code as pasting all the code will be overkill here:
<div class="left">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

However I am not able to see the graph.

A:

HTTP and HTTPS don't mix very well. Since the page is served as HTTPS the script must also be https.
<script src="https://d3js.org/d3.v3.min.js"></script>

or if I correct your example


Q:

rails 4 - undefined method `valid?'

I recently upgraded my rails to Rails 4
This query used to work :
@user = User.joins(:cars).where('cars.color' => "blue")

But now I got this error message:

undefined method `valid?' for #<
  User::ActiveRecord_Relation:0x00000100bbc668 >

Any idea ?

A:

The query User.joins(:cars).where('cars.color' => "blue") returns an ActiveRecord::Relation instance. Check docs here.
If you really want to operate over an instance (of User class), you must take a user from that collection, for example:
@user = User.joins(:cars).where('cars.color' => "blue").first

An ActiveRecord::Relation doesn't respond to methods like: .save, .update_attributes


Q:

tracking where unchecked (or checked?) exceptions get lost

how would you track where unchecked exceptions are getting lost? I'm developing a Swing GUI with embedded Processing Views, but somehow exceptions aren't shown on STDERR or anywhere. Everytime I had to go through the whole application through debugging until the error occured. But now it seems to be somewhere in a large loop and I don't get the cause. The stack is as follows:
Thread [DestroyJavaVM] (Running)

Thread [AWT-Shutdown] (Running)

Thread [AWT-EventQueue-0] (Running)

Thread [Animation Thread] (Running)

and if I pause the application every thread is suspended (which is normal) and the AWT-Event-Queue thread is in unsafe park, whereas I don't know what this means. I'm almost sure an exception has been thrown somewhere.
best regards,
Johannes

A:

With eclipse (and other IDEs...) you can set a breakpoint to halt when an exception is thrown. Just debug the application, configure the breakpoint (break on an exception type) and the debugger will show where it occured.


Q:

How to change value in xml string?

I have the following method
string UpdateXmlString(string xmlString) {...}

I would like to find all tags which name contain password and delete a value;
Before:
<job xmlns:i=\"...\" xmlns=\"...">
<password>asdfasdf</password>
<adminPassword>asd</adminPassword>
...</job>

Expected result:
<job xmlns:i=\"..." xmlns=\"...">
<password></password>
<adminPassword></adminPassword>
...</job>

How to implement this method?

A:

You should simply be using XmlDocument or XDocument to parse this. I wouldn't manipulate XML strings manually.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace XDocumentTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                String xml = "<?xml version=\"1.0\"?><rootElement>";
                xml += "<user id=\"1\"><password>temp</password></user>";
                xml += "<user id=\"2\"><adminPassword>foobar</adminPassword></user>";
                xml += "<user id=\"3\"><somePassWORDelement>foobarXYZ</somePassWORDelement></user>";
                xml += "</rootElement>";
                XDocument doc = XDocument.Parse(xml);
                foreach (XElement element in doc.Descendants().Where(
                    e => e.Name.ToString().ToLower().Contains("password")))
                {
                    Console.WriteLine(element);
                    // Delete your value here. Either changing the text node
                    // or by removing the password node. E.g.

                    element.Value = string.Empty;
                }

                Console.WriteLine(doc.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            while (Console.ReadKey(true).Key != ConsoleKey.Escape)
            {
            }
        }
    }
}


Q:

search a word in a string for exact match / even startingwith the word is not working

I have a id and a text field.
I need to search a word with exact match or starting with the word in a string with single mysql query.
E.g select * from tablename where textfield like "%cam%.
This will return all the text id which cam is found anywhere in the single .
but i need to get the result that can be queried by splitting single words in a sentence.
id text
1 Camel_walk.
2 camel does drink water.
3 does Camel_store water.
4 In deset people can find_camel
5 this will not return

when i query for
select * from tablename where textfield like "%camel%.
return first 1,2,3,4
but i need to get the id in which the word start with camel
1)select * from tablename where textfield like "Camel%"
return 1,3 ( which is not working for me)
or even
2)select * from tablename where textfield like "%Camel"
return 4

These two queries is not working
Can some one help
Thanks

A:

select * from tablename where textfield like "Camel%" or textfield like ' %Camel'

Notice the space before % in second condition. These two conditions will match when any word starts with Camel in your string, doesn't matter if it is the first word or not.


Q:

Association setup for messages with recipients

I am wonder what the best way to set up the models and associations are with what I am trying to achieve.
A user can create a message. The message can have one or many recipients who are users.
How do I set it up the associations so I can view the messages that are made by a user, but also messages where the recipient is their user id? Do I do a join model, or do I do:
A user has_many messages, a message has many recipients (stores message_id and user_id) and if that's the best way how do I access the messages where the user is not the owner of the message but a recipient?

A:

class User << ApplicationRecord
  has_many :sent_messages, class_name: "Message"
  has_many :recipients
  has_many :received_messages, :through => :recipients, :source => :message
end

class Message << ApplicationRecord
  belongs_to :sender, class_name: "User"
  has_many :recipients
  has_many :receivers, through: :recipients
end

class Recipients<< ApplicationRecord
  belongs_to :message
  belongs_to :receiver, class_name: "User"
end

Then you can:
user = User.find(1)     # First user
user.sent_messages      # Messages sent by user
user.received_messages  # Messages received by user


Q:

Python regular expression to match file-date.txt

I am trying to match file names in the format filename-isodate.txt
>>> DATE_NAME_PATTERN = re.compile("((.*)(-[0-9]{8})?)\\.txt")
>>> DATE_NAME_PATTERN.match("myfile-20101019.txt").groups()
('myfile-20101019', 'myfile-20101019', None)

However I need to get the filename and -isodate parts in seperate groups.
Any suggestions and/or explainations would be much appreciated

A:

You need: DATE_NAME_PATTERN = re.compile("((.*?)(-[0-9]{8})?)\\.txt")

.* performs a gready match so the second part is never used.
FYI in my opiniomy you shouldn't use regular expression where normal string manipulation is enough ( simple split() will do ).


Q:

Flex Cairngorm - How to update the model without losing focus in Datagrid?

In my Flex Project using Cairngorm, I have a model that stores a bindable ArrayCollection displayed by a DataGrid. My problem occurs when the model is updated by the responder (from a Java service, after an "update" event), because the focus located in a cell of the DataGrid is lost (the scroll position il also lost). So, I retrieve the position before the update, with DataGridEvent.ITEM_FOCUS_IN event :
myModel.focusedCell.rowIndex = e.rowIndex;
myModel.focusedCell.columnIndex = e.columnIndex;

But, from where restore these parameters ? How to trigger this update only when the model is updated ?
Thanks in advance.

A:

for information, I resolved my problem as follows:
to avoid losing focus (or rather the next cell being edited), one has to update the model without re-instantiating it.
After that, we must resolve a problem with the scroll as explained in the following post:
How to data bind DataGrid component without scrolling up?


Q:

Any advice on parsing an OPML file with PHP so I can import the addresses into a mySql database?

I want to be able to have the user select an OPML file that contains a large number of bookmarks, then loop through each one and toss it in a mysql database.
Any direction would be much appreciated.

A:

In the end, parsing any file comes down to a few things:

Get the file from $_FILES
Handling File Uploads (Documentation)
Load the file into a reader
 SimpleXML (Documenation)
Check that it is in the right format
(This will most likely just be checking that SimpleXML didn't throw an error)
Loop through the data
Sanitize any data going into the database
Enter it into the database

If this is a big file, you will also want to look it things like max_upload_size and other upload size restrictions. Also, look into a way to let the user know you are working if the script takes a while to process the file.


Q:

Pop WeChat/Weixin Safari-like Share Sheet in my app UIActivityViewController?

I'm trying to pop the built in Safari share WeChat in my iOS app. But can't find a way to make WeChat app show up in the UIActivityViewController!

I noticed that the WeChat app icon shows up when sharing images from the Photo Gallery, and Safari link sharing. The native Notes app doesn't have WeChat option.
Not sure how that's working, any help is appreciated! Thanks!

A:

This is done using "Share" extensions. See Apple docs for more information: https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ShareSheet.html#//apple_ref/doc/uid/TP40014214-CH12-SW1
Regarding why some apps appear in certain sharing contexts but not in others, this is because a Share extension has to declare to iOS which kind of data it supports for sharing. Presumably, WeChat developers did not enable their Share extension for "pure" text content, like in the Notes app. See here for how to set which kind of data a Share extension accepts: https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW8
Unfortunately you won't be able to add the WeChat Share extension on behalf of them if they didn't allow it, but you might be able to use some WeChat API to develop your own app extension with text content enabled.
Hope it helped.


Q:

Loading profile image and username in the navigation bar from firebase

image of database structure
code for database structure
I am trying to retrieve the profile image and username that is saved by the user during the registration process in the navigation header. Here is something that I did . At first I tried to get string current user  but it showed me null pointer exception then I tried with if statement and changed the child from current user id to Users , it only solved the null pointer but this didn't retrive the data from firebase.
MainActivity.java
   import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private RecyclerView postlist;
    private Toolbar mToolbar;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private FirebaseAuth mAuth;
    private FirebaseUser FirebaseUser;
    private DatabaseReference  UsersRef;
    private CircleImageView NavProfileImage;
    private TextView NavProfileUserName;
    String currentUserID;

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

        FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
        if (mFirebaseUser != null) {
            currentUserID = mFirebaseUser.getUid();
        }
        mAuth = FirebaseAuth.getInstance();

        mToolbar =(Toolbar) findViewById(R.id.main_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("Home");

        drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
       actionBarDrawerToggle =  new ActionBarDrawerToggle(MainActivity.this,drawerLayout,R.string.drawer_open, R.string.drawer_close);
        navigationView = (NavigationView)findViewById(R.id.navigation_view);
       drawerLayout.addDrawerListener(actionBarDrawerToggle);
       actionBarDrawerToggle.syncState();
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        View navView = navigationView.inflateHeaderView(R.layout.nav_header);
        NavProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
        NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);

        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
        UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                if(dataSnapshot.exists())
                {   if (dataSnapshot.hasChild("fullname")){
                    String fullname = dataSnapshot.child("fullname").getValue().toString();
                    NavProfileUserName.setText(fullname);
                }if (dataSnapshot.hasChild("profileimages")) {
                    String image = dataSnapshot.child("profileimages").getValue().toString();
                    Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);

                }else {
                    Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
                }

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item)
            { UserMenuSelector(item);

                return false;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser == null)
        {
            sendUserToLoginActivity();
        }else{
            CheckUserExistance();
        }
    }

    private void CheckUserExistance()
    {
        final String current_user_id = mAuth.getCurrentUser().getUid();
          UsersRef.addValueEventListener(new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {
                  if (!dataSnapshot.hasChild(current_user_id)){
                      sendUserToSetupActivity();
                  }
              }

              @Override
              public void onCancelled(DatabaseError databaseError) {

              }
          });
    }

    private void sendUserToSetupActivity() {
        Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
        setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(setupIntent);
        finish();

    }

    private void sendUserToLoginActivity()
    {
        Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
         loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
         startActivity(loginIntent);
         finish();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item))
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void UserMenuSelector(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.nav_home:
                Toast.makeText(this,"Home",Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_post:
                break;
            case R.id.nav_Profile:
                Toast.makeText(this,"profile",Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_find_friends:
                Toast.makeText(this,"frns",Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_logout:
                mAuth.signOut();
                sendUserToLoginActivity();
                break;
        }
    }
}

A:

After seeing your database structure I believe that the child inside Users node is the UID of current firebase user and in the Users node if you are trying to fetch user details of current user then your query should be like this
if (mFirebaseUser != null) {
            currentUserID = mFirebaseUser.getUid();
        }
 UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
     UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                if(dataSnapshot.exists())
                {   if (dataSnapshot.hasChild("fullname")){
                    String fullname = dataSnapshot.child("fullname").getValue().toString();
                    NavProfileUserName.setText(fullname);
                }if (dataSnapshot.hasChild("profileimages")) {
                    String image = dataSnapshot.child("profileimages").getValue().toString();
                    Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);

                }else {
                    Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
                }

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


Q:

div se muestra al pulsar sobre botón pero no se oculta al pulsar sobre el mismo botón

Buenas,
Tengo un pequeño div en mi código en el que al pulsar sobre un elemento se me abre un pequeño desplegable para iniciar sesión, pero quiero que al pulsar en ese mismo elemento, desaparezca. El caso es que no consigo hacer que esta segunda parte ocurra y no entiendo dónde tengo el error.
Código HTML:

   Login avanzado
   Registrarse

           <input type="text" name="" value="">
           <input type="password" name="" value="">

    <input class="submit_login" type="submit" name="submit_login" value="►">

Por otra parte el código del fichero .js, es más extenso pero muestro sólo lo que es relevante a mi parecer:
$(document).ready(main);

var count = 0;

function main(){

$('#invitado').click(function(){
    if (count == 0) {
        document.getElementById('sesion_popup').style.display = 'block';
        document.getElementById('invitado').style.color = 'black';
        document.getElementsByClassName('inicio_registro').style.display = 'none';
        count = 1;
    } else {
        document.getElementById('sesion_popup').style.display = 'none';
        document.getElementById('invitado').style.color = 'white';
        document.getElementsByClassName('inicio_registro').style.display = 'block';
        count = 0;
    }

})
};

En teoría el valor de la variable count pasa de 0 cuando el div está oculto a 1 cuando sí que se muestra. Al pulsar de nuevo sobre el elemento con id="invitado" debería de pasar de nuevo al valor 0 y ocultarse, pero eso no ocurre.
También tengo un problema con la línea de código document.getElementsByClassName('inicio_registro').style.display = 'none'; puesto que no me oculta los 2 elementos  de inicio de sesión y de registro.
Gracias de antemano.

A:

Te dejo un ejemplo que (creo) interpreta tu caso de uso. Hay un elemento a que muestra u oculta la cada de login. Ésta parte oculta y el visitante sólo ve el link "invitado"

$(document).ready(function() {

var count = 0;

  $('#invitado').click(function(){
      console.log(count);
      if (count == 0) {
          document.getElementById('sesion_popup').style.display = 'block';
          document.getElementById('invitado').style.color = 'grey';
          count = 1;
      } else {
          document.getElementById('sesion_popup').style.display = 'none';
          document.getElementById('invitado').style.color = 'black';
          count = 0;
      }

  });

});
#sesion_popup {
  display:none;
}

Invitado

   Login avanzado
   Registrarse

           <input type="text" name="" value="">
           <input type="password" name="" value="">

    <input class="submit_login" type="submit" name="submit_login" value="►">


Q:

CheckBox in UITableView

In UITableView, I want to put check uncheck buttons,when I click on first row[indexpath.row=0] remaining rows will uncheck and when click on indexpath.row>0 then row=0 unchceck. I have to do  viceversa  ,
intially I took an array with all objects uncheck and when check it that index will replace object check,
for(int i=0; i<[carwasharray count]; i++)
{
    [arrayCheckUnchek addObject:@"Uncheck"];
}
/cell row at indexpath my code is
cell.textLabel.text = [carwasharray objectAtIndex:indexPath.row];
if (indexPath.row==0) {
     button1 = [UIButton buttonWithType:UIButtonTypeCustom];
     [button1 setImage:[UIImage imageNamed:@"uncheck_icon.png"] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(buttonClic:) forControlEvents:UIControlEventTouchUpInside];
    button1.tag=1;
    [button1 setFrame:CGRectMake(150.0, 7.0, 30.0, 30.0)];
    [cell.contentView addSubview:button1];
}
else{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(150.0, 7.0, 30.0, 30.0)];
    button.tag=2;
if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
    [button setImage:[UIImage imageNamed:@"uncheck_icon.png"] forState:UIControlStateNormal];
else
    [button setImage:[UIImage imageNamed:@"check_icon"] forState:UIControlStateNormal];

[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
}
return cell;

}
-(void)buttonClic:(id)sender
{
//Getting the indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:carwashtable];
NSIndexPath *indexPath = [carwashtable indexPathForRowAtPoint:touchPoint];
UIButton *button = (UIButton *)sender;
if (button1.tag==1)
{
    if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
    {

     //[button1 setImage:[UIImage imageNamed:@"check_icon.png"] forState:UIControlStateNormal];
        //[button setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
       // [arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:@"Check"];
        button.tag=3;
        [self buttonClicked:button];
    }
    else
    {
        //[button1 setImage:[UIImage imageNamed:@"check_icon.png"] forState:UIControlStateNormal];
        [arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:@"Check"];

        button.tag=3;
        [self buttonClicked:button];

    }
}
else if(button1.tag==0){
    [button1 setImage:[UIImage imageNamed:@"uncheck_icon.png"] forState:UIControlStateNormal];

}

}
-(void)buttonClicked:(id)sender
{
//Getting the indexPath of cell of clicked button
 CGPoint touchPoint = [sender convertPoint:CGPointZero toView:carwashtable];
NSIndexPath *indexPath = [carwashtable indexPathForRowAtPoint:touchPoint];
// No need to use tag sender will keep the reference of clicked button
UIButton *button = (UIButton *)sender;
if (button.tag==2) {
    if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
    {
        [button setImage:[UIImage imageNamed:@"check_icon.png"] forState:UIControlStateNormal];
        [button1 setImage:[UIImage imageNamed:@"uncheck_icon.png"] forState:UIControlStateNormal];
        [arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:@"Check"];

        button1.tag=1;
    }
    else
    {
        [button setImage:[UIImage imageNamed:@"uncheck_icon.png"] forState:UIControlStateNormal];
        [arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:@"Uncheck"];

    }
}
else
{
    if ([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:@"Check"]) {
        [button setImage:[UIImage imageNamed:@"uncheck_icon.png"] forState:UIControlStateNormal];

    }
    [button1 setImage:[UIImage imageNamed:@"check_icon.png"] forState:UIControlStateNormal];

}

now its working only 1st time when I click row=1, the row=0 wil uncheck, upto this ok, but when I recheck row=0 it will also check..
thank in advance

A:

Hi thanks every one who given me a reply.... I got the answer it working fine now
same code but slightly changes...
//cell for row at indexpath....
  if (indexPath.row==0) {

    [button1 addTarget:self action:@selector(completebuttonClic:) forControlEvents:UIControlEventTouchUpInside];
     button1.tag=1;
    [button1 setFrame:CGRectMake(240.0, 7.0,25.0, 25.0)];
    [cell.contentView addSubview:button1];
}
else{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(240.0, 7.0, 25.0, 25.0)];
    button.tag=2;
    if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
        [button setImage:[UIImage imageNamed:@"uncheck_ico.png"] forState:UIControlStateNormal];
    else
        [button setImage:[UIImage imageNamed:@"check_icon.png"] forState:UIControlStateNormal];

    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:button];
}
return cell;

}
//calling button targets

-(void)completebuttonClic:(id)sender
{
//completebutton clicked
//Getting the indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:carwashtable];
NSIndexPath *indexPath = [carwashtable indexPathForRowAtPoint:touchPoint];
UIButton *button = (UIButton *)sender;
if (button1.tag==1)
{
    if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
    {

        button.tag=3;
        button1.tag=0;
        [self buttonClicked:button];
    }
    else
    {

        button.tag=3;
        [self buttonClicked:button];

    }
}
else if(button1.tag==0){
    [button1 setImage:[UIImage imageNamed:@"uncheck_ico.png"] forState:UIControlStateNormal];
     [selectrows removeObject:[carwashtypeid objectAtIndex:indexPath.row]];
}
NSLog(@"%@",selectrows);

}
-(void)buttonClicked:(id)sender
{
//Getting the indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero tablviewname];
NSIndexPath *indexPath = [tableviewname indexPathForRowAtPoint:touchPoint];
// No need to use tag sender will keep the reference of clicked button
UIButton *button = (UIButton *)sender;
if (button.tag==2) {
    if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
    {       NSLog(@"%ld",(long)indexPath.row);
[button setImage:[UIImage imageNamed:@"check_icon.png"] forState:UIControlStateNormal];
 [button1 setImage:[UIImage imageNamed:@"uncheck_ico.png"] forState:UIControlStateNormal];
      if (button1.imageView.image==[UIImage imageNamed:@"uncheck_ico.png"]) {
  //adding selected rows in a selectrows array
            [selectrows removeObject:[carwashtypeid objectAtIndex:0]];
        }
        [arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:@"Check"];
        [selectrows addObject:[carwashtypeid objectAtIndex:indexPath.row]];
        button1.tag=1;
    }
    else
    {
        [button setImage:[UIImage imageNamed:@"uncheck_ico.png"] forState:UIControlStateNormal];
        [arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:@"Uncheck"];
        [selectrows removeObject:[carwashtypeid objectAtIndex:indexPath.row]];
    }
}
else
{
    for (int i=1; i<[carwasharray count]; i++) {
        if ([[arrayCheckUnchek objectAtIndex:i] isEqualToString:@"Check"]) {
            [arrayCheckUnchek replaceObjectAtIndex:i withObject:@"Uncheck"];
            [carwashtable reloadData];
            [selectrows removeObject:[carwashtypeid objectAtIndex:i]];
        }}
    [button1 setImage:[UIImage imageNamed:@"check_icon.png"] forState:UIControlStateNormal];
    [selectrows addObject:[carwashtypeid objectAtIndex:indexPath.row]];
}
NSLog(@"%@",selectrows);


Q:

Local java processes are grayed when trying to connect via JMX

I'm running a number of java processes on a windows XP professional machine.  When i attempt to connect to these processes via a local JConsole the processes are grayed out.
However i can run the same processes on another machine and connect via a local JConsole on that machine.
Both machines are running java 1.6 version for the processes and jconsole.
Any ideas why these processes are grayed out?

A:

I'm fighting with this issue right now and I found out a work around:
You can change the local user's temp dir to something that they can definitely access (e.g. D:\temp). Make sure to do this for the process you're trying to monitor and the jconsole process.
Another thing that can apparently cause issues are usernames with uppercase letters in them. The directory will always be created with all lowercase letters, but simply renaming it to exactly how it's being shown in the Task Manager made all the issues go away: http://planeofthought.com/wp/?p=75

A:

if the processes are running as a different user (e.g. if you start them as services), then you won't be able to connect to them.  also, if they are running under an older jvm, you most likely won't be able to talk to them either.
in some cases, the local jmx communication mechanism uses the local filesystem and may have issues if permissions are not defined correctly.  are you possibly running any of these processes on networked filesystems (nfs, samba)?

A:

Say your windows user name you use to start your java application seen in task manager is YOUR_USER_NAME.
Please check a folder whose name looks like hsperfdata_XXXXX (XXXXX should be your user name) in your temp folder and make sure YOUR_USER_NAME and XXXXX are exactly the same (be careful about the upper and lower case).


Q:

Синхронизация доступа к ArrayList

Здравствуйте. Такой вопрос:

В javadoc написано, что для thread-safe доступа к ArrayListу его нужно декорировать через Collections.synchronizeList. Я так понял, что этот метод просто возвращает list методы которого synchronized, это так?

Из того же javadoc:
List list = Collections.synchronizedList(new ArrayList());
synchronized(list) {
  Iterator i = list.iterator(); // Must be in synchronized block
  while (i.hasNext())
    foo(i.next());
}

It is imperative that the user manually synchronize on the returned list when iterating over it: ...

Зачем в этом случае вручную синхронизировать через synchronized(list)? Или это нужно делать, только когда работаешь с итераторами, и не обязательно, если обращаешься к листу через get(), add(), set()?
Спасибо.

A:

Ну так посмотрите, что делает  Collections.synchronizedList.. в IDE контрол-клик и читайте, что написано. Но вообще, вы обнаружите, что да, там каждый метод synchronized.
Соответственно, этот факт и является причиной того, что есть необходимость синхронизоваться отдельно. Всё дело в том, что итератор сломается, если кто-то выполнит модификауцию списка между вызовами next(). Чтобы этого избежать и приходится делать более крупный блок synchronized.
И да, нарушение внутреннего состояния списка внутри методов set никто не отменял: одновременный вызов метода set из разных поток с высокой вероятностью разрушит список. Поэтому, надо делать synchronizedList. Ну или можно просто руками везде синхронизовать, а не оборачивать. Лично я обычно так и делаю и редко пользуюсь этим декоратором. Он обычно полезен, если вы отдаёте список куда-то наружу, чего я стараюсь всеми правдами и неправдами избежать.


Q:

Postgresql.conf variables

I have been playing around with the postgresql.conf file for a couple days now. I was wondering what variables you guys like customizing and why?
Here is a sample of the file:
# - TCP Keepalives -
# see "man 7 tcp" for details
#tcp_keepalives_idle = 0        # TCP_KEEPIDLE, in seconds;
                    # 0 selects the system default
#tcp_keepalives_interval = 0        # TCP_KEEPINTVL, in seconds;
                    # 0 selects the system default
#tcp_keepalives_count = 0       # TCP_KEEPCNT;
                    # 0 selects the system default

#------------------------------------------------------------------------------
# RESOURCE USAGE (except WAL)
#------------------------------------------------------------------------------

# - Memory -

shared_buffers = 64MB           # min 128kB or max_connections*16kB
                    # (change requires restart)
#temp_buffers = 8MB         # min 800kB
#max_prepared_transactions = 5      # can be 0 or more
                    # (change requires restart)
# Note:  Increasing max_prepared_transactions costs ~600 bytes of shared memory
# per transaction slot, plus lock space (see max_locks_per_transaction).
#work_mem = 1MB             # min 64kB
#maintenance_work_mem = 16MB        # min 1MB
#max_stack_depth = 2MB          # min 100kB

# - Free Space Map -

max_fsm_pages = 204800          # min max_fsm_relations*16, 6 bytes each
                    # (change requires restart)
#max_fsm_relations = 1000       # min 100, ~70 bytes each
                    # (change requires restart)

# - Kernel Resource Usage -

#max_files_per_process = 1000       # min 25
                    # (change requires restart)
shared_preload_libraries = '$libdir/plugins/plugin_debugger.dll'        # (change requires restart)

# - Cost-Based Vacuum Delay -

#vacuum_cost_delay = 0          # 0-1000 milliseconds
#vacuum_cost_page_hit = 1       # 0-10000 credits
#vacuum_cost_page_miss = 10     # 0-10000 credits
#vacuum_cost_page_dirty = 20        # 0-10000 credits
#vacuum_cost_limit = 200        # 1-10000 credits

# - Background Writer -

#bgwriter_delay = 200ms         # 10-10000ms between rounds
#bgwriter_lru_maxpages = 100        # 0-1000 max buffers written/round
#bgwriter_lru_multiplier = 2.0      # 0-10.0 multipler on buffers scanned/round

#------------------------------------------------------------------------------
# WRITE AHEAD LOG
#------------------------------------------------------------------------------

# - Settings -

#fsync = on             # turns forced synchronization on or off
#synchronous_commit = on        # immediate fsync at commit
#wal_sync_method = fsync        # the default is the first option
                    # supported by the operating system:
                    #   open_datasync
                    #   fdatasync
                    #   fsync
                    #   fsync_writethrough
                    #   open_sync
#full_page_writes = on          # recover from partial page writes
#wal_buffers = 64kB         # min 32kB
                    # (change requires restart)
#wal_writer_delay = 200ms       # 1-10000 milliseconds

#commit_delay = 0           # range 0-100000, in microseconds
#commit_siblings = 5            # range 1-1000

# - Checkpoints -

#checkpoint_segments = 3        # in logfile segments, min 1, 16MB each
#checkpoint_timeout = 5min      # range 30s-1h
#checkpoint_completion_target = 0.5 # checkpoint target duration, 0.0 - 1.0
#checkpoint_warning = 30s       # 0 is off

# - Archiving -

#archive_mode = off     # allows archiving to be done
                # (change requires restart)
#archive_command = ''       # command to use to archive a logfile segment
#archive_timeout = 0        # force a logfile segment switch after this
                # time; 0 is off

#------------------------------------------------------------------------------
# QUERY TUNING
#------------------------------------------------------------------------------

# - Planner Method Configuration -

#enable_bitmapscan = on
#enable_hashagg = on
#enable_hashjoin = on
#enable_indexscan = on
#enable_mergejoin = on
#enable_nestloop = on
#enable_seqscan = on
#enable_sort = on
#enable_tidscan = on

# - Planner Cost Constants -

#seq_page_cost = 1.0            # measured on an arbitrary scale
#random_page_cost = 4.0         # same scale as above
#cpu_tuple_cost = 0.01          # same scale as above
#cpu_index_tuple_cost = 0.005       # same scale as above
#cpu_operator_cost = 0.0025     # same scale as above
effective_cache_size = 32768

# - Genetic Query Optimizer -

#geqo = on
#geqo_threshold = 12
#geqo_effort = 5            # range 1-10
#geqo_pool_size = 0         # selects default based on effort
#geqo_generations = 0           # selects default based on effort
#geqo_selection_bias = 2.0      # range 1.5-2.0

# - Other Planner Options -

#default_statistics_target = 10     # range 1-1000
#constraint_exclusion = off
#from_collapse_limit = 8
#join_collapse_limit = 8        # 1 disables collapsing of explicit
                    # JOIN clauses

#------------------------------------------------------------------------------
# ERROR REPORTING AND LOGGING
#------------------------------------------------------------------------------

# - Where to Log -

log_destination = 'stderr'      # Valid values are combinations of
                    # stderr, csvlog, syslog and eventlog,
                    # depending on platform.  csvlog
                    # requires logging_collector to be on.

# This is used when logging to stderr:
logging_collector = on      # Enable capturing of stderr and csvlog
                    # into log files. Required to be on for
                    # csvlogs.
                    # (change requires restart)

# These are only used if logging_collector is on:
#log_directory = 'pg_log'       # directory where log files are written,
                    # can be absolute or relative to PGDATA
#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'    # log file name pattern,
                    # can include strftime() escapes
#log_truncate_on_rotation = off     # If on, an existing log file of the
                    # same name as the new log file will be
                    # truncated rather than appended to.
                    # But such truncation only occurs on
                    # time-driven rotation, not on restarts
                    # or size-driven rotation.  Default is
                    # off, meaning append to existing files
                    # in all cases.
#log_rotation_age = 1d          # Automatic rotation of logfiles will
                    # happen after that time.  0 to disable.
#log_rotation_size = 10MB       # Automatic rotation of logfiles will
                    # happen after that much log output.
                    # 0 to disable.

# These are relevant when logging to syslog:
#syslog_facility = 'LOCAL0'
#syslog_ident = 'postgres'

# - When to Log -

#client_min_messages = notice       # values in order of decreasing detail:
                    #   debug5
                    #   debug4
                    #   debug3
                    #   debug2
                    #   debug1
                    #   log
                    #   notice
                    #   warning
                    #   error

#log_min_messages = notice      # values in order of decreasing detail:
                    #   debug5
                    #   debug4
                    #   debug3
                    #   debug2
                    #   debug1
                    #   info
                    #   notice
                    #   warning
                    #   error
                    #   log
                    #   fatal
                    #   panic

#log_error_verbosity = default      # terse, default, or verbose messages

#log_min_error_statement = error    # values in order of decreasing detail:
                    #   debug5
                    #   debug4
                    #   debug3
                    #   debug2
                    #   debug1
                    #   info
                    #   notice
                    #   warning
                    #   error
                    #   log
                    #   fatal
                    #   panic (effectively off)

#log_min_duration_statement = -1    # -1 is disabled, 0 logs all statements
                    # and their durations, > 0 logs only
                    # statements running at least this time.

#silent_mode = off          # DO NOT USE without syslog or
                    # logging_collector
                    # (change requires restart)

# - What to Log -

#debug_print_parse = off
#debug_print_rewritten = off
#debug_print_plan = off
#debug_pretty_print = off
#log_checkpoints = off
#log_connections = off
#log_disconnections = off
#log_duration = off
#log_hostname = off
log_line_prefix = '%t '         # special values:
                    #   %u = user name
                    #   %d = database name
                    #   %r = remote host and port
                    #   %h = remote host
                    #   %p = process ID
                    #   %t = timestamp without milliseconds
                    #   %m = timestamp with milliseconds
                    #   %i = command tag
                    #   %c = session ID
                    #   %l = session line number
                    #   %s = session start timestamp
                    #   %v = virtual transaction ID
                    #   %x = transaction ID (0 if none)
                    #   %q = stop here in non-session
                    #        processes
                    #   %% = '%'
                    # e.g. '<%u%%%d> '
#log_lock_waits = off           # log lock waits >= deadlock_timeout
#log_statement = 'none'         # none, ddl, mod, all
#log_temp_files = -1            # log temporary files equal or larger
                    # than specified size;
                    # -1 disables, 0 logs all temp files
#log_timezone = unknown         # actually, defaults to TZ environment
                    # setting

#------------------------------------------------------------------------------
# RUNTIME STATISTICS
#------------------------------------------------------------------------------

# - Query/Index Statistics Collector -

#track_activities = on
#track_counts = on
#update_process_title = on

# - Statistics Monitoring -

#log_parser_stats = off
#log_planner_stats = off
#log_executor_stats = off
#log_statement_stats = off

#------------------------------------------------------------------------------
# AUTOVACUUM PARAMETERS
#------------------------------------------------------------------------------

#autovacuum = on            # Enable autovacuum subprocess?  'on'
                    # requires track_counts to also be on.
#log_autovacuum_min_duration = -1   # -1 disables, 0 logs all actions and
                    # their durations, > 0 logs only
                    # actions running at least that time.
#autovacuum_max_workers = 3     # max number of autovacuum subprocesses
#autovacuum_naptime = 1min      # time between autovacuum runs
#autovacuum_vacuum_threshold = 50   # min number of row updates before
                    # vacuum
#autovacuum_analyze_threshold = 50  # min number of row updates before
                    # analyze
#autovacuum_vacuum_scale_factor = 0.2   # fraction of table size before vacuum
#autovacuum_analyze_scale_factor = 0.1  # fraction of table size before analyze
#autovacuum_freeze_max_age = 200000000  # maximum XID age before forced vacuum
                    # (change requires restart)
#autovacuum_vacuum_cost_delay = 20  # default vacuum cost delay for
                    # autovacuum, -1 means use
                    # vacuum_cost_delay
#autovacuum_vacuum_cost_limit = -1  # default vacuum cost limit for
                    # autovacuum, -1 means use
                    # vacuum_cost_limit

#------------------------------------------------------------------------------
# CLIENT CONNECTION DEFAULTS
#------------------------------------------------------------------------------

# - Statement Behavior -

#search_path = '"$user",public'     # schema names
#default_tablespace = ''        # a tablespace name, '' uses the default
#temp_tablespaces = ''          # a list of tablespace names, '' uses
                    # only default tablespace
#check_function_bodies = on
#default_transaction_isolation = 'read committed'
#default_transaction_read_only = off
#session_replication_role = 'origin'
#statement_timeout = 0          # 0 is disabled
#vacuum_freeze_min_age = 100000000
#xmlbinary = 'base64'
#xmloption = 'content'

# - Locale and Formatting -

datestyle = 'iso, dmy'
#timezone = unknown         # actually, defaults to TZ environment
                    # setting
#timezone_abbreviations = 'Default'     # Select the set of available time zone
                    # abbreviations.  Currently, there are
                    #   Default
                    #   Australia
                    #   India
                    # You can create your own file in
                    # share/timezonesets/.
#extra_float_digits = 0         # min -15, max 2
#client_encoding = sql_ascii        # actually, defaults to database
                    # encoding

# These settings are initialized by initdb, but they can be changed.
lc_messages = 'English_Canada'          # locale for system error message
                    # strings
lc_monetary = 'English_Canada'          # locale for monetary formatting
lc_numeric = 'English_Canada'           # locale for number formatting
lc_time = 'English_Canada'              # locale for time formatting

# default configuration for text search
default_text_search_config = 'pg_catalog.english'

# - Other Defaults -

#explain_pretty_print = on
#dynamic_library_path = '$libdir'
#local_preload_libraries = ''

#------------------------------------------------------------------------------
# LOCK MANAGEMENT
#------------------------------------------------------------------------------

#deadlock_timeout = 1s
#max_locks_per_transaction = 64     # min 10
                    # (change requires restart)
# Note:  Each lock table slot uses ~270 bytes of shared memory, and there are
# max_locks_per_transaction * (max_connections + max_prepared_transactions)
# lock table slots.

#------------------------------------------------------------------------------
# VERSION/PLATFORM COMPATIBILITY
#------------------------------------------------------------------------------

# - Previous PostgreSQL Versions -

add_missing_from = on
#array_nulls = on
#backslash_quote = safe_encoding    # on, off, or safe_encoding
#default_with_oids = off
#escape_string_warning = on
#regex_flavor = advanced        # advanced, extended, or basic
#sql_inheritance = on
#standard_conforming_strings = off
#synchronize_seqscans = on

# - Other Platforms and Clients -

#transform_null_equals = off

I am mostly looking for efficiency or wise use of resources. I know it depends on how I am planning on using it and other such "it depends" answers. What I am looking for is the important or common variables customizations; which ones do people most often change and why?
Thx!

A:

It's impossible to know what might be appropriate to change without knowing how you are going to use the database. Will you have a high transaction load? Will you have mostly static bulk data with a lot of queries? Will you be mostly reading existing data (SELECT), adding new data (INSERT), or changing existing data (UPDATE)?
Also, even knowing how you are using it, you will need to do benchmarks and query plan analysis to determine what aspect of the configuration you might need to change to address any performance problems you are encountering. This may require the assistance of a PostgreSQL expert.
The defaults will be suitable for all but the most demanding of applications.


Q:

GridFS Nginx check if data exist

I use (File System Based) static html files for caching, for some reasons i don like this. I want store cache files (html, images) in database.
Now it work like that:
if nginx can get cache:
    return cache to user
else
    proxy_pass request to backend server

It looks like this in my Nginx config file
if (-f $cache_dir_prefix/$query) {
    rewrite (.*) $query break;
}

if (!-f $cache_dir_prefix/$query) {
    proxy_pass http://lionyzer;
    break;
}

It's posible to do IF check with GridFS Or Amazon S3 or Mysql or anything alse?
Thanks alot
AND THE ANSWER IS
location /assets/ {
    gridfs assets field=filename type=string;
    mongo 127.0.0.1:27017;
    error_page 404 = @scale;
}

location @scale {
    include fastcgi.conf;
    fastcgi_pass unix:/tmp/php-fpm;
    fastcgi_param SCRIPT_FILENAME scaleme.php;
}

A:

You can use the nginx-gridfs module to serve GridFS files directly from Nginx, and then catch a 404 for files not found and proxy those to the other server.


Q:

Same datatype multiple variable declaration in swift

in objective-c we can declare variable like
-NSString *a,*b,*c;
in swift there a way to declare same datatype multiple variable variable rather than doing like below
var a: NSString = ""
var b: NSString = ""
var c: NSString = ""

So, is it possible to declare all a,b,c variable into one line like
var (a,b,c): a:NSstring=("","","") or something?

A:

You can declare multiple constants or multiple variables on a single
  line, separated by commas:
var a = "", b = "", c = ""

NOTE
If a stored value in your code is not going to change, always declare
  it as a constant with the let keyword. Use variables only for storing
  values that need to be able to change.

Type Annotations:

You can define multiple related variables of the same type on a single
  line, separated by commas, with a single type annotation after the
  final variable name:
var red, green, blue: Double

NOTE
It is rare that you need to write type annotations in practice. If you
  provide an initial value for a constant or variable at the point that
  it is defined, Swift can almost always infer the type to be used for
  that constant or variable, as described in Type Safety and Type
  Inference.

Documentation HERE.

A:

Swift has an odd design decision here. Placing a type on a variable affects all previous non-explicitly typed variables in a multi-line definition. Same for constants.
These two lines are equivalent (a, b and c are Double):
var a, b, c: Double
var a: Double, b: Double, c: Double

And these two are equivalent (a and b are Int, while c and d are Double):
var a, b: Int, c, d: Double
var a: Int, b: Int, c: Double, d: Double


Q:

Freeing an array after it has been written to by MPI_Recv

I have a malloc'd array of integers that I fill with MPI_Recv
MPI_Recv(d.current, n, MPI_INT, 0, TAG_CURRENT_ARRAY, MPI_COMM_WORLD, &status);

I have tested the value of d.current both before and after the MPI_Recv and it doesn't change (which is correct).
My data arrives correctly.
However if I try to free the data I get an error:
*** Error in `./bin/obddhe-mpi': free(): invalid next size (fast): 0x0965e988 ***

The exact same free before the receive works perfectly.
I.e...
This Works:
free(d.current);
//MPI_Recv(d.current, n, MPI_INT, 0, TAG_CURRENT_ARRAY, MPI_COMM_WORLD, &status);

This Fails:
MPI_Recv(d.current, n, MPI_INT, 0, TAG_CURRENT_ARRAY, MPI_COMM_WORLD, &status);
free(d.current);

What could MPI_Recv be doing that invalidates the free!?

A:

A SSCCE would be very helpful.
That said, I'll try to answer as good as I can:

I have a malloc'd array of integers that I fill with MPI_Recv
MPI_Recv(d.current, n, MPI_INT, 0, TAG_CURRENT_ARRAY, MPI_COMM_WORLD, &status);

How large is that array? How exactly did you malloc() it? What is n in this case and how is it related to the malloc()ed size?
Your observations show that MPI_Recv() is the reason for this error to occur. In order to make this error occur, MPI_Recv() has written beyond the end of the malloc()ed memory area, which it isn't allowed to. This messes up either the linked list used internally by memory management or the size of blocks behind it or both, leading to the said error.

I have tested the value of d.current both before and after the MPI_Recv and it doesn't change (which is correct).

(How should it? You are passing the pointer to the function, not its address. So the pointer cannot change.)

However if I try to free the data I get an error:

* Error in `./bin/obddhe-mpi': free(): invalid next size (fast): 0x0965e988 *

The exact same free before the receive works perfectly.

That is another clue for what I wrote above: the meory behind the block you use has been freed and contains a pointer to the next free area. If you free() your memory, the library tries to merge the free blocks, the second of those being corrupt, leading to this error.
Imagine you have the following situation:

Your memory manager prepends each memory block, be it free or allocated, with its length.
The free blocks have the address of the next free block at their start - this is the linked list I mentioned.
Your allocated block, prepended with its length, is followed by

a free block, prepended with its length and containing the address of the next free block of NULL if there is no next free block.

Then, if you write past the end of your memory block, the length and content of the next block will be touched and tampered with.
This doesn't affect anything - till now.
But if you call free() on your block, this block will be merged with the free block after it.
In order to do so, the following actions must occur:

Traverse the linked list in order to find adjacent free blocks - which already might lead to this error because the "next" pointer of the 2nd free block is garbage.
Calculate the size of the bigger free block from the other blocks. If one of these contains garbage, the garbage will be used for calculating the new, bigger free block size and the confusion is perfect.


Q:

Sampajañña: what is the correct action?

One of Buddha's four ways of training the mind for Sampajañña ("clear comprehension") is to know the suitability of an action. From an anecdote given by Joseph Goldstein, his meditation master was haggling with a seller. When asked why, he replied

The path of the Dhamma is to be simple, not a simpleton.

The following are two situations which I deal with on a daily basis, and I still am unsure what is the suitable or correct action to take.

Two people are walking towards each other on a narrow path, do you yield first and let the other pass?
Two people both make eye contact, who should avert their gaze first to avoid a staredown contest?

The more abstract problem here might be described as, the correct action to take when you and another have conflicting interests. An answer to that is appreciated as well, but I really do mean to ask, how do you deal with the two concrete situations given above?

A:

I really do mean to ask, how do you deal with the two concrete situations given above?
I am inclined to "yield first", although it doesn't often (or hardly ever) happen in practice that I'm walking on a path that narrow.
When I'm on a bicycle on a shared footpath, pedestrians are usually inclined to yield to me, and then I allow them to yield (they walk on one side of the path and I cycle past them); or you could say I yield i.e. I cycle around them. I slow, slow to a stop, or dismount when necessary (e.g. on a single-lane footpath under a bridge, when passing small children or off-leash dogs, or on a pedestrian side-walk).
Sometimes I drive a car on a single-track road. There is a (unwritten?) convention for which car is supposed to yield in that case, i.e. it's supposed to be whichever car is able to yield the most easily:

The car which has a lay-by in front of it, which it can pull into
The car which is closest to the lay-by behind it (i.e. the car which has most recently passed a lay-by) into which it can reverse
The car which can most easily reverse (e.g. the car which will be reversing down-hill rather than up-hill, or the smaller car)

Sometimes I stop for 4 &half seconds to see whether the other car (which is probably driven by someone who's more familiar with the road than I am) goes into reverse, and if not then I start to reverse.
The more abstract problem here might be described as, the correct action to take when you and another have conflicting interests. An answer to that is appreciated as well ...
I don't see this as a conflicting interest. I want to get around in a friendly and more-or-less cooperative way, I want to be non-aggressive and I don't want to frighten people. I assume (and my experience has confirmed) that these ambitions are socially acceptable and not a "conflicting interest".
When one car yields to another is conventional for both drivers to do a small hand-wave to the other as they pass each other (each to acknowledge the other's politeness and savoir faire perhaps).
On foot if I make eye-contact with someone (outside a city) then I'm likely to say "Good day!" to them (and vice versa, they do too). Someone said once that according to the older and more formal rules of politeness in this country it's conventional that it should be the more junior person who should be the first to say "Good day!"; but I'm happy ignore that and wish a good day to anyone, older or younger.

A:

'Sampajañña' means to be clearly cognizant in the application & use of various kinds of 'pañña' (wisdom; discernment) that relate to giving up craving & the cessation & suffering. The scriptures state:

The monk ardent (ātāpī), clearly-comprehending (sampajāno) & mindful (satimā) puts aside covetousness & distress with reference to the world.
MN 118

Despite Joseph possibly often having secular audiences, sampajañña does not relate to haggling for goods in the marketplace, which simply requires 'worldly shrewdness'.
When people are walking towards me on a narrow path, I generally always yield & let the other pass since I am generally walking without a particular craving (unless there is an inherent danger that must be decided on, such as when walking on a narrow path near a cliff).
Similarly, sampajañña would generally not be used stare-down contests because using sampajañña to apply the 8 fold path results in abandoning hostility & egoism.

And what is the faculty of discernment (pañña)? There is the case where a monk, a disciple of the noble ones, is discerning, endowed with
  discernment of arising & passing away — noble, penetrating, leading to
  the right ending of stress. He discerns, as it has come to be: 'This
  is stress... This is the origination of stress... This is the
  cessation of stress... This is the path of practice leading to the
  cessation of stress.' This is called the faculty of discernment.
Indriya-Vibhanga Sutta

A:

A true disciple of the Supreme Buddha is humble by nature as he/she has gotten rid of arrogance in its entirety. On the other hand a person who is not sincere, humble and innocent enough to surrender to the true Dhamma, has a greater degree of arrogance. So when two people are walking towards each other on a narrow path…, it is the one who has the alertness and awareness ( sampajañña), and who has true humility that will give way to the other.
Then to the question about two people both make eye contact, who should avert their gaze first to avoid a staredown contest?…  it is the one who has the alertness and awareness ( sampajañña), that would give in as he/she is one who practises the five Sekha strengths. He/she lives in association with the five Sekha strengths and does not abandon them. What are these Sekha Dhamma? They are… Saddha (Confidence), Hiri (shame), Ottappa (fear), Viriya (energy) and Panna (wisdom). Such a person is humble enough to see what’s going on in that present moment, that would lead to a staredown contest, and to understand the eventual pain that would come as a result.


Q:

How do I bust my cache key based on the params in the URL?

I have a Profile#Index view, where I render a partial like so:
<% cache @profiles do %>

  <% @profiles.to_a.in_groups_of(3, false).each do |profiles| %>

         <%= render partial: "profile", collection: profiles, cached: true %>

    <% end %>

<% end %>

But in my app/views/profiles/_profile.html.erb, I have the following:
  <% cache profile do %>
    <% elsif current_user.has_role?(:coach) && params[:rating].present? %>

          Speed: <%= profile.ratings.find_by(user: current_user).speed %>

          Tackling: <%= profile.ratings.find_by(user: current_user).tackling %>

    <% end %>
  <% end %>

What the above does is produce the labels at the bottom of the results, and those labels should only come up on the results when there is the params check in the above code is valid/true.
So, when a logged in user goes to / they should see a list of profiles, which works and looks like this:

Then they go trigger the same root_path but with params, and it looks (correctly) like this:

However, the issue is that when I go back to the root page, it mixes and matches the results from the param's version of the page, with the normal vanilla ones from the root_path, where it should just be the same results from the first image above (aka just the vanilla results).

How do I fix this?
Edit 1
Per Austio's suggestion, I added the params[:rating] to both the partial view and the collection view.
So my app/views/profiles/_profile.html.erb now looks like this:
<% cache [params[:rating], profile] do %>
    <% elsif current_user.has_role?(:coach) && params[:rating].present? %>

          Speed: <%= profile.ratings.find_by(user: current_user).speed %>

          Tackling: <%= profile.ratings.find_by(user: current_user).tackling %>

    <% end %>
  <% end %>

Both don't work properly though, but here are the logs the requests with the code snippet above.
This is for the correct cached view.
Started GET "/profiles?rating=speed" for ::1 at 2016-11-07 10:05:34 -0500
Processing by ProfilesController#index as HTML
  Parameters: {"rating"=>"speed"}
  User Load (10.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 7], ["LIMIT", 1]]
  Role Load (3.3ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Role Load (4.1ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Role Load (2.6ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'player') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
   (2.7ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'player') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
   (2.1ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
   (4.9ms)  SELECT "ratings"."profile_id" FROM "ratings" WHERE "ratings"."user_id" = $1 ORDER BY "ratings"."speed" DESC  [["user_id", 7]]
  Profile Load (6.2ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" IN (5, 18, 14, 7, 22, 13, 9, 17)
  Tournament Load (2.6ms)  SELECT  "tournaments".* FROM "tournaments" ORDER BY "tournaments"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Rendering profiles/index.html.erb within layouts/application
Read fragment views/profiles/5-20161105043153971213/profiles/18-20161101223838805685/profiles/14-20161105042425134917/profiles/7-20161101001052922220/profiles/22-20161106175803133611/profiles/13-20161104221749051281/profiles/9-20161104221706306433/profiles/17-20161105043606243802/59a852f082290d51847bb12ee90b9d25 (0.3ms)
  Rendered profiles/index.html.erb within layouts/application (15.0ms)
  CACHE (0.0ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Rendered shared/_navbar.html.erb (15.1ms)
  Rendered layouts/_messages.html.erb (1.8ms)
  Rendered shared/_footer.html.erb (0.6ms)
Completed 200 OK in 914ms (Views: 671.1ms | ActiveRecord: 39.3ms)

This is for the incorrect cached view:
Started GET "/" for ::1 at 2016-11-07 10:06:17 -0500
  User Load (8.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 7], ["LIMIT", 1]]
Processing by ProfilesController#index as HTML
  Role Load (6.4ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Role Load (2.8ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Role Load (3.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'player') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
   (6.2ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'player') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
   (5.1ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Profile Search (148.2ms)  curl http://localhost:9200/profiles_development/_search?pretty -d '{"query":{"match_all":{}},"size":1000,"from":0,"timeout":"11s","_source":false}'
  Tournament Load (2.3ms)  SELECT  "tournaments".* FROM "tournaments" ORDER BY "tournaments"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Rendering profiles/index.html.erb within layouts/application
  Profile Load (4.9ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" IN (14, 22, 12, 21, 9, 5, 4, 15, 6, 7, 16, 18, 13, 23, 17)
Read fragment views/profiles/14-20161105042425134917/profiles/22-20161106175803133611/profiles/12-20161101225114614189/profiles/21-20161103035514173735/profiles/9-20161104221706306433/profiles/5-20161105043153971213/profiles/4-20161103035528589634/profiles/15-20161029013919242687/profiles/6-20161105043216951643/profiles/7-20161101001052922220/profiles/16-20161029020526832889/profiles/18-20161101223838805685/profiles/13-20161104221749051281/profiles/23-20161104062851335443/profiles/17-20161105043606243802/59a852f082290d51847bb12ee90b9d25 (6.3ms)
Read fragment views//profiles/12-20161101225114614189/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
   (5.6ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."voter_id" = $1 AND "votes"."voter_type" = $2 AND "votes"."votable_id" = $3 AND "votes"."votable_type" = $4 AND "votes"."vote_scope" IS NULL AND "votes"."vote_flag" = $5  [["voter_id", 7], ["voter_type", "User"], ["votable_id", 12], ["votable_type", "Profile"], ["vote_flag", true]]
  Position Load (3.2ms)  SELECT  "positions".* FROM "positions" INNER JOIN "positions_profiles" ON "positions"."id" = "positions_profiles"."position_id" WHERE "positions_profiles"."profile_id" = $1 ORDER BY "positions"."id" ASC LIMIT $2  [["profile_id", 12], ["LIMIT", 1]]
  School Load (4.4ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  CACHE (0.1ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
Write fragment views//profiles/12-20161101225114614189/01a5673b1dc193ec7173e62efba21a9b (0.2ms)
  Rendered collection of profiles/_profile.html.erb [2 / 3 cache hits] (68.4ms)
Read fragment views//profiles/21-20161103035514173735/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
   (2.8ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."voter_id" = $1 AND "votes"."voter_type" = $2 AND "votes"."votable_id" = $3 AND "votes"."votable_type" = $4 AND "votes"."vote_scope" IS NULL AND "votes"."vote_flag" = $5  [["voter_id", 7], ["voter_type", "User"], ["votable_id", 21], ["votable_type", "Profile"], ["vote_flag", true]]
  Position Load (2.6ms)  SELECT  "positions".* FROM "positions" INNER JOIN "positions_profiles" ON "positions"."id" = "positions_profiles"."position_id" WHERE "positions_profiles"."profile_id" = $1 ORDER BY "positions"."id" ASC LIMIT $2  [["profile_id", 21], ["LIMIT", 1]]
  School Load (3.8ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
Write fragment views//profiles/21-20161103035514173735/01a5673b1dc193ec7173e62efba21a9b (2.2ms)
  Rendered collection of profiles/_profile.html.erb [2 / 3 cache hits] (46.5ms)
Read fragment views//profiles/4-20161103035528589634/01a5673b1dc193ec7173e62efba21a9b (0.0ms)
   (2.6ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."voter_id" = $1 AND "votes"."voter_type" = $2 AND "votes"."votable_id" = $3 AND "votes"."votable_type" = $4 AND "votes"."vote_scope" IS NULL AND "votes"."vote_flag" = $5  [["voter_id", 7], ["voter_type", "User"], ["votable_id", 4], ["votable_type", "Profile"], ["vote_flag", true]]
  Position Load (2.6ms)  SELECT  "positions".* FROM "positions" INNER JOIN "positions_profiles" ON "positions"."id" = "positions_profiles"."position_id" WHERE "positions_profiles"."profile_id" = $1 ORDER BY "positions"."id" ASC LIMIT $2  [["profile_id", 4], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
Write fragment views//profiles/4-20161103035528589634/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
Read fragment views//profiles/15-20161029013919242687/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
   (2.3ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."voter_id" = $1 AND "votes"."voter_type" = $2 AND "votes"."votable_id" = $3 AND "votes"."votable_type" = $4 AND "votes"."vote_scope" IS NULL AND "votes"."vote_flag" = $5  [["voter_id", 7], ["voter_type", "User"], ["votable_id", 15], ["votable_type", "Profile"], ["vote_flag", true]]
  Position Load (5.3ms)  SELECT  "positions".* FROM "positions" INNER JOIN "positions_profiles" ON "positions"."id" = "positions_profiles"."position_id" WHERE "positions_profiles"."profile_id" = $1 ORDER BY "positions"."id" ASC LIMIT $2  [["profile_id", 15], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (3.7ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
Write fragment views//profiles/15-20161029013919242687/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
Read fragment views//profiles/6-20161105043216951643/01a5673b1dc193ec7173e62efba21a9b (0.3ms)
   (2.9ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."voter_id" = $1 AND "votes"."voter_type" = $2 AND "votes"."votable_id" = $3 AND "votes"."votable_type" = $4 AND "votes"."vote_scope" IS NULL AND "votes"."vote_flag" = $5  [["voter_id", 7], ["voter_type", "User"], ["votable_id", 6], ["votable_type", "Profile"], ["vote_flag", true]]
  Position Load (3.0ms)  SELECT  "positions".* FROM "positions" INNER JOIN "positions_profiles" ON "positions"."id" = "positions_profiles"."position_id" WHERE "positions_profiles"."profile_id" = $1 ORDER BY "positions"."id" ASC LIMIT $2  [["profile_id", 6], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
Write fragment views//profiles/6-20161105043216951643/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
  Rendered collection of profiles/_profile.html.erb [0 / 3 cache hits] (83.4ms)
Read fragment views//profiles/16-20161029020526832889/01a5673b1dc193ec7173e62efba21a9b (0.0ms)
   (2.3ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."voter_id" = $1 AND "votes"."voter_type" = $2 AND "votes"."votable_id" = $3 AND "votes"."votable_type" = $4 AND "votes"."vote_scope" IS NULL AND "votes"."vote_flag" = $5  [["voter_id", 7], ["voter_type", "User"], ["votable_id", 16], ["votable_type", "Profile"], ["vote_flag", true]]
  Position Load (3.9ms)  SELECT  "positions".* FROM "positions" INNER JOIN "positions_profiles" ON "positions"."id" = "positions_profiles"."position_id" WHERE "positions_profiles"."profile_id" = $1 ORDER BY "positions"."id" ASC LIMIT $2  [["profile_id", 16], ["LIMIT", 1]]
  CACHE (0.2ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
Write fragment views//profiles/16-20161029020526832889/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
  Rendered collection of profiles/_profile.html.erb [2 / 3 cache hits] (28.6ms)
Read fragment views//profiles/23-20161104062851335443/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
   (1.8ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."voter_id" = $1 AND "votes"."voter_type" = $2 AND "votes"."votable_id" = $3 AND "votes"."votable_type" = $4 AND "votes"."vote_scope" IS NULL AND "votes"."vote_flag" = $5  [["voter_id", 7], ["voter_type", "User"], ["votable_id", 23], ["votable_type", "Profile"], ["vote_flag", true]]
  Position Load (2.9ms)  SELECT  "positions".* FROM "positions" INNER JOIN "positions_profiles" ON "positions"."id" = "positions_profiles"."position_id" WHERE "positions_profiles"."profile_id" = $1 ORDER BY "positions"."id" ASC LIMIT $2  [["profile_id", 23], ["LIMIT", 1]]
  School Load (2.2ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
Write fragment views//profiles/23-20161104062851335443/01a5673b1dc193ec7173e62efba21a9b (0.1ms)
  Rendered collection of profiles/_profile.html.erb [2 / 3 cache hits] (27.6ms)
Write fragment views/profiles/14-20161105042425134917/profiles/22-20161106175803133611/profiles/12-20161101225114614189/profiles/21-20161103035514173735/profiles/9-20161104221706306433/profiles/5-20161105043153971213/profiles/4-20161103035528589634/profiles/15-20161029013919242687/profiles/6-20161105043216951643/profiles/7-20161101001052922220/profiles/16-20161029020526832889/profiles/18-20161101223838805685/profiles/13-20161104221749051281/profiles/23-20161104062851335443/profiles/17-20161105043606243802/59a852f082290d51847bb12ee90b9d25 (0.1ms)
  Rendered profiles/index.html.erb within layouts/application (357.4ms)
  CACHE (0.0ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Rendered shared/_navbar.html.erb (20.6ms)
  Rendered layouts/_messages.html.erb (2.4ms)
  Rendered shared/_footer.html.erb (0.6ms)
Completed 200 OK in 1704ms (Views: 1262.0ms | Searchkick: 148.2ms | ActiveRecord: 89.4ms)

It still doesn't work. Hopefully that log illustrates something that can help me get to the bottom of this.
Edit 2
When I add params[:rating] to both my collection & partial cache keys, it still doesn't work on the root_page (aka it shows incorrect partials). Here is the log from the result of that:
Started GET "/" for ::1 at 2016-11-07 11:50:15 -0500
  User Load (23.9ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 7], ["LIMIT", 1]]
Processing by ProfilesController#index as HTML
  Role Load (2.3ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Role Load (4.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Role Load (3.9ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'player') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
   (4.2ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'player') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
   (1.8ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Profile Search (157.6ms)  curl http://localhost:9200/profiles_development/_search?pretty -d '{"query":{"match_all":{}},"size":1000,"from":0,"timeout":"11s","_source":false}'
  Tournament Load (4.6ms)  SELECT  "tournaments".* FROM "tournaments" ORDER BY "tournaments"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Rendering profiles/index.html.erb within layouts/application
  Profile Load (7.1ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" IN (14, 22, 12, 21, 9, 5, 4, 15, 6, 7, 16, 18, 13, 23, 17)
Read fragment views//profiles/14-20161105042425134917/profiles/22-20161106175803133611/profiles/12-20161101225114614189/profiles/21-20161103035514173735/profiles/9-20161104221706306433/profiles/5-20161105043153971213/profiles/4-20161103035528589634/profiles/15-20161029013919242687/profiles/6-20161105043216951643/profiles/7-20161101001052922220/profiles/16-20161029020526832889/profiles/18-20161101223838805685/profiles/13-20161104221749051281/profiles/23-20161104062851335443/profiles/17-20161105043606243802/c6925e7eaf791cab78909b69752bd7f8 (0.3ms)
  Rendered profiles/index.html.erb within layouts/application (30.5ms)
  CACHE (0.0ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)) OR ((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  CACHE (0.1ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'coach') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 7]]
  Rendered shared/_navbar.html.erb (26.9ms)
  Rendered layouts/_messages.html.erb (3.3ms)
  Rendered shared/_footer.html.erb (0.9ms)
Completed 200 OK in 1677ms (Views: 1264.0ms | Searchkick: 157.6ms | ActiveRecord: 28.1ms)

A:

It looks like your Profile#Index view is making use of collection caching for the profile partial which makes use of an internal cache key:
<%= render partial: "profile", collection: profiles, cached: true %>

This is causing Lola Hessel and Jeremy Verley (as well as the others) being cached when a logged in user goes to /. Visiting the root_path with params afterwards causes the remaining profiles to be cached. The third page load then has cache hits for every profile and renders them as cached before. The caching within your profile partial has no effect since the collection caching serves first.
You can read about that here: http://guides.rubyonrails.org/caching_with_rails.html#collection-caching
I assume, that removing the collection caching from your partial rendering combined with a properly adapted cache statement (such as <% cache [profile, params[:rating].present?] do %>) within the profile partial does the trick.