What gives Steam XP?

Question: From the faq I know that the following give XP:

Crafting a badge ("most badges give 100 XP")
Upgrading a badge (it looks the same as crafting a badge: mostly 100 XP)
Years of Service badge (the faq is vague. What is the formula for XP gained?)
"Special events on Steam also frequently have badges" (?)

What other activities give XP? Are there any ways to get XP other than getting badges? Do regular achievements for Steam games give XP?
Comment: Great question :) !
Answer: From what I've seen so far:

Crafting a game badge grants 100 XP
Leveling a game badge grants 100 XP
Years of Service awards 50 XP per year
The games in your game collection award XP (The math is not clear to me, I have 414 for 209 games currently)

Steam Special Events appear to grant XP, although the formula is unclear to me.  The individual data is incomplete for most of the previous events.  Ones that I can confirm count for some amount of XP are:

Steam Holiday Sale (2011 & 2012) - I've seen up to 130 XP for 2011, and 100 for 2012
Steam Summer Sale (2012) - I have this one complete, I believe, for 100 XP
Steam Summer Camp (2011) - I've seen up to 130 XP
The Potato Sack (2011) - a "gold potato" gives 200 XP
The Great Steam Treasure Hunt (2010) - I've seen this one up to 130 XP

For community contributions there are other bonuses (with thanks to Koraktor in the comments):

Anyone can get the Pillar of Community (100 XP) or Community Ambassador (100 XP) badges for doing some simple tasks related to their Steam profile.
Some translators get a badge worth 100 XP
Steamworks developers get a badge worth 500 XP
Community moderators get a badge worth 500 XP
Valve employees also get a 1000 XP bonus, although that one might be kind of hard to get ;)
Comment: There are also additional badges for translators (100 XP), Steamworks developers (500 XP) and community moderators (500 XP)
Comment: And great answer ;)
Comment: Might be worth mentioning, Community Ambassador is the level 2 version of Pillar of Community. It's gained after 22/26 community tasks are completed.
Comment: They added today another one, Game Collector. It gives XP depending on number of games in user's library. It seems to be linear, with 203 games it gave me 402 XP and with 207 games it was 405 XP. For more details and source [see](http://steamcommunity.com/groups/tradingcards#announcements/detail/1837748658627226301).
Comment: @slawek, thanks for the heads up, I added that info to the answer
Comment: @agent86 The values for the game collection badge XP changed July 24, 2013. The formula has always been linear only within each tier. Here's what they now work out to based on sample data: 1-> 94+6*#ofGames XP, 5-> 100+5*#ofGames XP, 10-> floor(116.5+3.35*#ofGames) XP, 25 -> 150+2*#ofGames XP
50 -> floor(175+1.5*#ofGames) XP, 100 -> floor(208.25+1.1675*#ofGames) XP (approx. Still testing)
all tiers above 250 -> 250+#ofGames XP. Each tier gets a base value and each game past the tier threshold gets a multiplier and is added - I just worked back from the threshold to make simpler math.
Comment: Also, Community Ambassador is 200 XP, not 100.
Comment: The translator badge is AFAIK awarded by being a top 10 translator for 12 weeks straight.
Comment: for games you own: +100 first games, then + how much money you spend.

What gives Steam XP?


Multithreading: waiting for a thread to finish so I can retry a deadlock

Question: I have 2 threads, and I have to make the successful thread wait while the deadlocked one retries. The current code only works for the first loop, because the successful thread exits.
I've tried using Thread.Join() with no success.
How can I make the thread in which 'success' is 'true' to wait for the for the deadlocked thread to finish?
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread thread1 = new Thread(new ThreadStart(procedure1));
            Thread thread2 = new Thread(new ThreadStart(procedure2));

            thread1.Start();
            thread2.Start();
        }

        private void procedure1()
        {
            Console.WriteLine("thread 1");
            bool success = false;
            int retryCount = 1;
            while ((retryCount <= 3) && success == false)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection1"].ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand(ConfigurationManager.AppSettings.Get("execProcedure1"), connection);
                        connection.Open();
                        cmd.ExecuteNonQuery();
                        success = true;
                    }
                }
                catch (SqlException ex)
                {
                    if (ex.Number == 1205)
                    {
                        if (retryCount == 1) Console.WriteLine("Thread 1 deadlocked");
                        Console.WriteLine("Thread 1 deadlock retry number " + retryCount.ToString());
                        retryCount++;
                    }
                    else
                        Console.WriteLine(ex.Message);
                }
            }
        }

        private void procedure2()
        {
            Console.WriteLine("thread 2");
            bool success = false;
            int retryCount = 1;
            while ((retryCount <= 3) && success == false)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection1"].ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand(ConfigurationManager.AppSettings.Get("execProcedure2"), connection);
                        connection.Open();
                        cmd.ExecuteNonQuery();
                        success = true;
                    }
                }
                catch (SqlException ex)
                {
                    if (ex.Number == 1205)
                    {
                        if (retryCount == 1) Console.WriteLine("Thread 2 deadlocked");
                        Console.WriteLine("Thread 2 deadlock retry number " + retryCount.ToString());
                        retryCount++;
                    }
                    else
                        Console.WriteLine(ex.Message);
                }
            }
        }
    }

The SQL procedures used for the deadlock:
CREATE OR ALTER PROCEDURE deadlockP1
AS
BEGIN
    BEGIN TRAN;
        UPDATE Employee SET position = 'handler' WHERE employee_code = 4037;
        WAITFOR DELAY '00:00:05';
        UPDATE Shop SET shop_name = 'TITANUS' WHERE shop_code = 2019;
    COMMIT TRAN;
END

CREATE OR ALTER PROCEDURE deadlockP2
AS
BEGIN
    BEGIN TRAN;
        UPDATE Shop SET shop_name = 'TITANUS' WHERE shop_code = 2019;
        WAITFOR DELAY '00:00:05';
        UPDATE Employee SET position = 'manager' WHERE employee_code = 4037;
    COMMIT TRAN;
END

Comment: join is the solution to your problem. Could add your code segment to show how exactly did you use join?
Comment: _"I have 2 threads, and I have to make the successful thread wait while the deadlocked one retries. "_ - do you, though?
Comment: @Fildor I also am confused by the requirement they must wait on each other. Maybe there is other implementations that arent listed where they have to be in-sync
Comment: The requirement is that I have to retry the the deadlocked thread a number of times (3 in my code), until it is considered finished ('retryCount is '3').
Comment: Why does that requirement imply that the other thread waits?
Comment: It doesn't, but I guess if I want to retry the procedure, I have to make the other thread wait, isn't it so?
Answer:
How can I make the thread in which 'success' is 'true' to wait for the for the deadlocked thread to finish?

Consider using a Barrier if all threads must finish at similar times and wait for each other. Otherwise I recommend using Join(see below).

A group of tasks cooperate by moving through a series of phases, where each in the group signals it has arrived at the Barrier in a given phase and implicitly waits for all others to arrive. The same Barrier can be used for multiple phases.

When you use a barrier it basically means that all the threads you assign to be in the barrier have to all reach a "checkpoint" before each can continue.
Here's a quick example of what that might look like:
public partial class Form1 : Form
{
    // create a barrier with 2 slots
    private Barrier barrier = new Barrier(2);

    private void procedure1()
    {
        Console.WriteLine("thread 1");
        bool success = false;
        int retryCount = 1;
        while ((retryCount <= 3) && success == false)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection1"].ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand(ConfigurationManager.AppSettings.Get("execProcedure1"), connection);
                    connection.Open();
                    cmd.ExecuteNonQuery();
                    success = true;
                }
            }
            catch (SqlException ex)
            {
                if (ex.Number == 1205)
                {
                    if (retryCount == 1) Console.WriteLine("Thread 1 deadlocked");
                    Console.WriteLine("Thread 1 deadlock retry number " + retryCount.ToString());
                    retryCount++;
                }
                else
                    Console.WriteLine(ex.Message);
            }
        }

        // wait for all other tasks in barrier to get to this checkpoint before returning
        barrier.SignalAndWait();
    }

    private void procedure2()
    {
        Console.WriteLine("thread 2");
        bool success = false;
        int retryCount = 1;
        while ((retryCount <= 3) && success == false)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection1"].ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand(ConfigurationManager.AppSettings.Get("execProcedure2"), connection);
                    connection.Open();
                    cmd.ExecuteNonQuery();
                    success = true;
                }
            }
            catch (SqlException ex)
            {
                if (ex.Number == 1205)
                {
                    if (retryCount == 1) Console.WriteLine("Thread 2 deadlocked");
                    Console.WriteLine("Thread 2 deadlock retry number " + retryCount.ToString());
                    retryCount++;
                }
                else
                    Console.WriteLine(ex.Message);
            }
        }

        // wait for all other tasks in barrier to get to this checkpoint before returning
        barrier.SignalAndWait();
    }
}

It should be noted though that similar effects can be accomplished using Task.WhenAll(async)  and Task.WaitAll(sync), that are easier to implement along with Join(but you said you didn't want to use/couldn't use join).
If you want to reconsider using Join, consider passing a reference of the thread you want to wait on to the other thread. Join blocks the current thread(waits) while the instance of the thread that it calls Join on finishes up.
Here's how Join works in a nutshell, just make sure not to get two threads trying to wait for each other. You'll be waiting a long time for them to figure it out.
void ThreadOne(Thread other)
{
    // do work
    // ...

    // wait for other to finish
    other?.Join();
}

void ThreadTwo()
{
    // do work
    // ...
}

When you use Joins you run into a problem when two tasks have to wait on eachother. In your example you want to wait(Join) when the current thread has finished it's work, but the other hasn't. How do we know when the other thread has finished it's work?
We should use a sentinel value to notify other threads that work has either been done, or still needs to be completed.
We can use a bunch of things for sentinel values, from encapsulating variables, class variables and even WaitHandles.
If we use a sentinel value we can use Join by passing each Thread a reference to each other.
Here's what that might look like:
public partial class Form1 : Form
{
    // create sentinels
    bool thread1Status = false;
    bool thread2Status = false;

    // create a spot to store the threads so they can reference each other
    Thread thread1;
    Thread thread2;

    private void Form1_Load(object sender, EventArgs e)
    {
        thread1 = new Thread(new ThreadStart(procedure1));
        thread2 = new Thread(new ThreadStart(procedure2));

        thread1.Start();
        thread2.Start();
    }

    private void procedure1()
    {
        Console.WriteLine("thread 1");
        bool success = false;
        int retryCount = 1;
        while ((retryCount <= 3) && success == false)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection1"].ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand(ConfigurationManager.AppSettings.Get("execProcedure1"), connection);
                    connection.Open();
                    cmd.ExecuteNonQuery();
                    success = true;

                    // notify other thread that we finished work
                    thread1Status = true;
                }
            }
            catch (SqlException ex)
            {
                if (ex.Number == 1205)
                {
                    if (retryCount == 1) Console.WriteLine("Thread 1 deadlocked");
                    Console.WriteLine("Thread 1 deadlock retry number " + retryCount.ToString());
                    retryCount++;
                }
                else
                    Console.WriteLine(ex.Message);
            }
        }

        // wait for the other thread to finish work if it hasn't
        if(success && thread2Status == false)
        {
             thread2?.Join();
        }
    }

    private void procedure2(Thread other)
    {
        Console.WriteLine("thread 2");
        bool success = false;
        int retryCount = 1;
        while ((retryCount <= 3) && success == false)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection1"].ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand(ConfigurationManager.AppSettings.Get("execProcedure2"), connection);
                    connection.Open();
                    cmd.ExecuteNonQuery();
                    success = true;

                    // notify other thread that we finished work
                    thread2Status = true;
                }
            }
            catch (SqlException ex)
            {
                if (ex.Number == 1205)
                {
                    if (retryCount == 1) Console.WriteLine("Thread 2 deadlocked");
                    Console.WriteLine("Thread 2 deadlock retry number " + retryCount.ToString());
                    retryCount++;
                }
                else
                    Console.WriteLine(ex.Message);
            }
        }

        // wait for the other thread to finish work if it hasn't
        if(success && thread1Status == false)
        {
             thread1?.Join();
        }
    }
}


java server: start a new thread for each received packet?

Question: I am currently learning how to program a tcp server in java. I am creating a new thread for new each client connection (multithreaded server).
After the client connects to the server, I want to send data from the client to the server. On serverside the server is in a while loop reading data from the sockets inputstream. I want to ask now: Should I create a new thread for each received packet?
For example the client sends the string "Hello". Should the server handle this packet in a new thread so it can continue reading, because I think if I don't create a new thread, server doesn't go back on reading and if client sends another packet after the "Hello" packet for example "Bye", the server might not read it because it could still be busy handling the "Hello" packet.
To be clear I am not talking about serversockets accept method, I am talking about the data from sockets inputstream.
Please enlighten me about this.
Comment: Every time the server retrieves a socket from `accept()`, it should assign a new thread to handle the conversation. Each new client connecting to the server will trigger the server to obtain a `Socket` from `accept`. I'd recommend you Google for some examples, e.g. http://www.kieser.net/linux/java_server.html.
Answer: If your packet handle task is not very heavy (probably it is not), you shouldn't. Thread will handle a message and come back to receiving new messages. No data will be lost - if nobody reads from inputstream, data transfer just holds (after all buffers filled).
Just keep one thread per client, it is enough in most cases.
Comment: +1 Yes - don't worry about it, (with TCP anyway).  The lower-layer Winsock buffering and flow-control will ensure that nothing gets lost.  Unless you spend such a large amount of time processing the data that a client with a timeout decides that the server is dead, you will be fine.
Comment: ok thanks, according to your answer I will now decide whether to start a thread or not, seems like the best solution to me
Comment: Yes - start one thread per client and pass it the socket from the accept().  That's the 'classic' synchronous server design where the server<>client thread code can be simply written 'in-line'.  There are surely asynchronous designs that can perform/scale better, but are inevitably more complex since you must then provide your own state-machine.
Answer: Yes you must delegate to another thread in order to have a responsive server. No, don't create a thread per request (unless the client load is trivial) but use a thread pool instead.
Example skeleton code (of course you will have to break out of the loop somehow):
<code>private static final ExecutorService threadPool = Executors.newCachedThreadPool();

while(true){

  final Socket clientConnection = serverSocket.accept();
  threadPool.execute(new Runnable(){
            public void run(){
                  processConnection(clientConnection);
            });

}
</code>

Should I create a new thread for each received packet?

No. Each thread will process its own connection (which receives the client packets) so connecting clients will be serviced faster since the main listener will continue accepting connections
Answer: One thread per each client connection is fine for a small application. However, one thread per each client request / packet is not a good approach at all. Just make sure your server can communicate to the client in time.
Please note that the number of threads you create is no way unlimited, it depends on the OS you are working with. Real applications use thread pools for handling such cases.


System.IO.FileNotFoundException:

Question: I have build an setup from my project. I have instal my project setup on the pc were i create the setup project an work, but when i try to instal on other pc the setup file and lunch the .exe i get an exception:
System.IO.FileNotFoundException: C:\Users\adrian.moldovan\Desktop\New folder (2)\DataLogger\DataLogger\Resources\Cattura_3.jpg
I think i have a problem with the image location or image deploy.
I have use the image for a background image and i have use this code:
<code>pBox.BackgroundImage = Image.FromFile("C:\Users\adrian.moldovan\Desktop\New folder (2)\DataLogger\DataLogger\Resources\Cattura_3.jpg")
</code>
Have anyone an idea how to solve this?
Comment: Add the image as a resource in your project properties window. It'll then get built in which your installer etc.
Comment: check whether the image is present in the path or not `C:\Users\adrian.moldovan\Desktop\New folder (2)\DataLogger\DataLogger\Resources\Cattura_3.jpg`
Answer: A FileNotFoundException means your file path is messed up or something. First, I would not expect both pc's to have the same user name. But, if they are the same, the easy way would be to go to file explorer, go to the picture file, hold shift + right click the file, go to 'copy file path' and paste that path into your code
Answer: Add the image as a resource in your project properties window. It'll then get built in with your installer.

System.IO.FileNotFoundException:


Quotient map between homotopy equivalent spaces

Question: $\require{AMScd}$
Let $X$ be some top. space and $X/{\raise.17ex\hbox{$\scriptstyle\sim$}} $ a quotient space with quotient map $q$:
\begin{CD}
X @>q>> X/{\raise.17ex\hbox{$\scriptstyle\sim$}}
\end{CD}
such that X is homotopy equivalent (or homeomorphic if that makes a difference) to $X/{\raise.17ex\hbox{$\scriptstyle\sim$}} $.
Is it true that $q$ is then a homotopy equivalence?
Thinking about 'nice' examples this seemed reasonable, at least I didn't see an example where it goes wrong. Trying to prove it though, there didn't seem to be any reasoning why $q$ should be homotopic to the given homotopy equivalence. So I assume this doesn't hold in general? Is it perhaps true for 'nice' spaces such as CW-complexes?
Answer: There should be enough counterexamples to this when your space is "big enough" (but otherwise well-behaved).
Consider, for example, the discrete countable space $\mathbb{N}$. Given any partition of $\mathbb{N}$ into finite subsets $\mathbb{N}=\coprod_{n \in \mathbb{N}}F_n$, there is the quotient $X/\sim$ where $\sim$ is the equivalence such that $F_n$'s are its equivalence classes, i.e. $x \sim y$ iff $x, y \in F_n$for some $n$. Then $X$ and $X/\sim$ are homeomorphic (for example by $n \mapsto F_n,$ both are countable discrete spaces). But the quotient map is not a homotopy equivalence, because it does not induce bijection on the set of path-components, which are singletons in both cases, unless all the sets $F_n$ are themselves singletons.
Similarly, you can take e.g. $X=\mathbb{C}\setminus \mathbb{Z}$, and the quotient $X/\sim$ obtained by shrinking $\{z \in \mathbb{C}\;|\; 0\neq |z| \leq\frac{1}{2}\}$ into a point. Then again, $X/\sim$ is homeomorphic to $X$ (both are a plane with countable set of isolated punctures), but the quotient map does not induce isomorphism on fundamental groups,  because the non-trivial loop that goes once around the origin in X becomes trivial after applying $q$.
Answer: Here is (only) a partial answer regarding CW complexes. It's proposition 0.17 in Hatcher's book:

If $(X,A)$ is a $CW$ pair consisting of a $CW$ complex $X$ and a contratible subcomplex $A,$ then the quotient map $X\to X/A$ is a homotopy equivalence.


Integrate javascript in android

Question:
Possible Duplicate:
JavaScript alert not working in Android WebView

I am developing an app in which i have to use java script but i am unable to get desired results . My java code is as follows:
 myWebView = (WebView) findViewById(R.id.webview);
            myWebView.loadUrl("file:///android_asset/neww.html");

            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

//          myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

My html code is as follows:
<!DOCTYPE html>

    <input type="button" onclick="show_alert()" value="Show alert box" />

When the app starts, this page gets displayed...:

...and when i click on show alert box it shows nothing and the following screen appears:
Comment: And what results *are* you getting?
Comment: simchona, i have edited my question and i have mentioned that i am getting
Answer: You have a syntax error in your script block.  Change show_alert( to show_alert() on line 5 of your HTML page and it should function.
Answer:      function show_alert( )

here it seems extra space is given between "(" and  ")". try this
       function show_alert()

May be it will solve.
Comment: Extra whitespace in JavaScript doesn't matter, so this would make no difference.
Comment: @Aditya1510 http://code.google.com/p/android/issues/detail?id=752 check this if it helps u
Comment: @harrison_m but he put show_alert( ) at line 5
Comment: Mishu Cn , the space is not the issue , i have checked the space

Integrate javascript in android


Task Schedular Giving Error while scheduling R Script for saving PDF

Question: I am scheduling R script which contains ggsave for saving pdf.
my code is running but on the line of ggsave("plot.pdf), it is skipping code. But instead of saving pdf if i use png format then it is fine. but only for pdf it is giving problem.
Below is my sample code.
    library(ggplot2)
    library(data.table)
    a <- data.frame(a = c(1:5))
    p <- ggplot(data.frame(x = 1:5, y = 1:5), aes(x, y)) + geom_point()
    fwrite(a,"abc1.csv")
    ggsave("plot.pdf")

Answer: Does ggsave(p, "plot.pdf", device = "pdf") work?  You may not have been specifying the plot to be saved or perhaps it doesn't know to export as pdf from only the file path that you gave?
EDIT: It should be ggsave("plot.pdf", p, device = "pdf") so that the arguments are in the correct order.
Comment: `ggsave("plot.pdf", p)`  I think the arguments are meant to be the other way around


The scrolling speed of the GridView is slow as it is stopped

Question: In one fragment of my current application, there are three lists in a listview, and each list displays a GridView, with about eight to fifteen imageViews as items in the GridView. So I make adapter A and adapter B. Adapter A acts as a bridge between the ListView and the string representing the title of the ListView and each GridView. Adapter B connects the GridView with its ImageView(8~15). So, in the getView method of adapter A, I inserted code that created the adapter B and connect to the corresponding gridView. The reason for calling the adapter from within the adapter (and of course my personal guess) is that the data and images are well connected to the gridView, and even though it is well connected to the ListView, the scrolling speed of the GridView is slow as if the scrolling stopped.
My question is
1] I want to know why the scroll speed of gridView is slow as it is stopped.

Personally, I do not think it's because of the size of the image. (This is because the scrolling speed of the GridView was exactly the same as it was before the image was entered into the image view.)

2] What is the solution?

I tried to load the image using AsyncTask. But my images are in a drawable folder (int variable) and I do not know how to load them (eg, int mimageResource = R.drawable.image) While attempting, the image will still have empty image items When the GridView is open, the speed of the GridView is similar at that time, so I wonder if AsyncTask is a solution.

I would really appreciate your advice.
---------------------------these are my code---------------------------------
1] SiteAdapter.java(link gridview and item)
public class SiteAdapter extends ArrayAdapter<Site> {
private Site currentSite;
private final int REQUEST_WIDTH = 256;
private final int REQUEST_HEIGHT = 256;
public Context context;

public SiteAdapter(Context context, ArrayList<Site> sites) {
    super(context, 0, sites);
    this.context = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;
    SiteViewHolder viewHolder;
    if(listItemView == null){
        listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent,false);

        viewHolder = new SiteViewHolder();
        viewHolder.icon = (ImageView) listItemView.findViewById(R.id.image);
        viewHolder.icon_name = (TextView) listItemView.findViewById(R.id.name);

        listItemView.setTag(viewHolder);
    }
    else
        viewHolder = (SiteViewHolder) listItemView.getTag();

    currentSite = getItem(position);
    viewHolder.position = position;

    //new ThumbnailTask(position, viewHolder).execute((currentSite.getMsite_imagesource()));

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getContext().getResources(),currentSite.getMsite_imagesource(),options);
    options.inSampleSize = setSimpleSize(options, REQUEST_WIDTH, REQUEST_HEIGHT);
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),currentSite.getMsite_imagesource(),options);

    viewHolder.icon.setBackground(new ShapeDrawable(new OvalShape()));
    viewHolder.icon.setClipToOutline(true);
    viewHolder.icon.setImageBitmap(bitmap);
    viewHolder.icon_name.setText(currentSite.getMsite_name());

    return listItemView;
}
private int setSimpleSize(BitmapFactory.Options options, int requestWidth, int requestHeight){
    int originalWidth = options.outWidth;
    int originalHeight = options.outHeight;

    int size = 1;

    while(requestWidth < originalWidth || requestHeight < originalHeight){
        originalWidth = originalWidth / 2;
        originalHeight = originalHeight / 2;

        size = size * 2;
    }
    return size;
}

2] ListAdapter (link list_title(String), GridView to ListView)
public class ListAdapter extends BaseAdapter {

public Context mcontext;
public Hashtable<String, ArrayList<Site>> mdata;
public Map.Entry<String,ArrayList<Site>> copyData;
public ArrayList<String> keySet = new ArrayList<String>();
private String key;
private int num=0;
public String currentName;
private ArrayList<Site> currentSite;
private int [] count = {0,0,0};

public ListAdapter(Context context,Hashtable<String, ArrayList<Site>> data){
    mcontext = context;
    mdata = data;
    Iterator it = data.entrySet().iterator();
    while(it.hasNext()) {
        copyData = (Map.Entry<String, ArrayList<Site>>) it.next();
        keySet.add(copyData.getKey());
    }
}

public String getKey(int position){
    //Iterator it = mdata.entrySet().iterator();
    //copyData = (Map.Entry<String, ArrayList<Site>>) it.next();
    return keySet.get(position);
}

@Override
public int getCount() {
    /*Iterator it = mdata.entrySet().iterator();
    while(it.hasNext())
    {
        num++;
    }
    return num;*/
    return keySet.size();
}

@Override
public ArrayList<Site> getItem(int position) {
    return mdata.get(keySet.get(position));
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
    View view = convertView;
    final ArrayList<Site> currentSite;
    ListViewHolder holder;

    if(view == null) {
        view = LayoutInflater.from(mcontext).inflate(R.layout.site_list, parent, false);

        holder = new ListViewHolder();
        holder.list_title = (TextView) view.findViewById(R.id.title_site_list);
        holder.lists = (GridView) view.findViewById(R.id.gridView);

        view.setTag(holder);
    }

    else
        holder = (ListViewHolder) view.getTag();

    currentName = keySet.get(position);
    holder.list_title.setText(currentName);

    currentSite = getItem(position);

    final SiteAdapter siteAdapter = new SiteAdapter(mcontext,currentSite);
    holder.lists.setAdapter(siteAdapter);

    final ViewSwitcher viewSwitcher = (ViewSwitcher) view.findViewById(R.id.visibility);
    holder.list_title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(count[position]%2==0){
                viewSwitcher.setVisibility(View.VISIBLE);
                viewSwitcher.showNext();
                count[position]++;
            }
            else if(count[position]%2==1){
                viewSwitcher.setVisibility(View.GONE);
                viewSwitcher.showNext();
                count[position]++;
            }
        }
    });

    holder.lists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            final Site site = currentSite.get(position);
            if (site.getMsite_name() == "Gist home") {
                PopupMenu popupIFWB = new PopupMenu(mcontext.getApplicationContext(), view);

                popupIFWB.getMenuInflater().inflate(R.menu.insta_facebook_web_blog_popup_menu, popupIFWB.getMenu());
                popupIFWB.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                            case R.id.webIFWB:
                                openWebPage(site.getMsite_urlW());
                                break;
                            case R.id.blogIFWB:
                                openWebPage(site.getMsite_urlB());
                                break;
                            case R.id.facebookIFWB:
                                openWebPage(site.getMsite_urlF());
                                break;
                            case R.id.instaIFWB:
                                openWebPage(site.getMsite_urlI());
                                break;
                        }
                        return false;
                    }
                });
                popupIFWB.show();
            } else
                openWebPage(site.getMsite_url());
        }

    });
    return view;
}

private static class ListViewHolder{
    public TextView list_title;
    public GridView lists;
}

public void openWebPage(String url){
    Uri webpage = Uri.parse(url);
    Intent siteMove = new Intent(Intent.ACTION_VIEW, webpage);
    if(siteMove.resolveActivity(mcontext.getPackageManager()) != null)
        mcontext.startActivity(siteMove);
}

}
3] OfficialFragment.java(same as home)
public class OfficialFragment extends Fragment {

private int count = 0;
private ArrayList<String> arrayGroup = new ArrayList<String>();
private Hashtable<String, ArrayList<Site>> arrayChild = new Hashtable<String, ArrayList<Site>>();

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View viewMain = inflater.inflate(R.layout.listview, null);
    super.onCreate(savedInstanceState);
    ListView listView = (ListView) viewMain.findViewById(R.id.listView);

    //GridView gridView = (GridView) viewMain.findViewById(R.id.gridView);
    setArrayData();

    ListAdapter listAdapter = new ListAdapter(getActivity(),arrayChild);
    listView.setAdapter(listAdapter);

    return viewMain;
}

public void openWebPage(String url){
    Uri webpage = Uri.parse(url);
    Intent siteMove = new Intent(Intent.ACTION_VIEW, webpage);
    if(siteMove.resolveActivity(getActivity().getPackageManager()) != null)
        startActivity(siteMove);
}

public void setArrayData(){

    arrayGroup.add("공식 사이트 모음");
    arrayGroup.add("조직 사이트 모음");
    arrayGroup.add("동아리 사이트 모음");

    ArrayList<Site> arrayOfficial = new ArrayList<Site>();
    arrayOfficial.add(new Site("Gist home", "https://www.gist.ac.kr/kr/","https://blog.naver.com/gist1993","https://www.facebook.com/GIST.ac.kr/","https://www.instagram.com/gist1993/", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("Zeus system", "https://zeus.gist.ac.kr", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("Portal system", "https://portal.gist.ac.kr/intro.jsp", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("Email system", "https://mail.gist.ac.kr/loginl?locale=ko_KR", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("Gist college", "https://college.gist.ac.kr/", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("Gist library", "https://library.gist.ac.kr/", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("학내공지", "https://college.gist.ac.kr/main/Sub040203", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("GIST 창업진흥센터", "https://www.facebook.com/gistbi/?ref=py_c", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("전기전자컴퓨터공학부", "http://eecs.gist.ac.kr/", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("신소재공학부", "http://mse.gist.ac.kr", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("기계공학부", "http://me.gist.ac.kr", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("지구·환경공학부", "http://env1.gist.ac.kr", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("생명과학부", "http://life1.gist.ac.kr", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("물리·광과학과", "http://phys.gist.ac.kr/", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("화학과", "http://chem.gist.ac.kr", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("융합기술원", "http://iit.gist.ac.kr", R.drawable.ic_dashboard_black_24dp));
    arrayOfficial.add(new Site("나노바이오재료전자공학과", "http://wcu.gist.ac.kr/", R.drawable.ic_dashboard_black_24dp));

    ArrayList<Site> arrayOrganization = new ArrayList<Site>();
    arrayOrganization.add(new Site("Gist 총학생회", "https://www.facebook.com/gistunion/", R.drawable.gistunion));
    arrayOrganization.add(new Site("Gist 동아리연합회", "https://www.facebook.com/gistclubunite/", R.drawable.clubnight));
    arrayOrganization.add(new Site("Gist 하우스", "https://www.facebook.com/GISTcollegeHOUSE/", R.drawable.gisthouse));
    arrayOrganization.add(new Site("Gist 문화행사위원회", "https://www.facebook.com/Moonhangwe/", R.drawable.moonhangwe));
    arrayOrganization.add(new Site("Gist 신문","http://gistnews.co.kr/", "https://www.facebook.com/pg/GistSinmoon/posts/", R.drawable.gistnews));
    arrayOrganization.add(new Site("Gist 홍보대사", "http://blog.naver.com/PostList.nhn?blogId=gist1993&from=postList&categoryNo=28", R.drawable.gionnare));

    ArrayList<Site> arrayCircle = new ArrayList<Site>();
    arrayCircle.add(new Site("영화 동아리 Cinergy", "https://www.facebook.com/gistcinergy/", R.drawable.cinergy));
    arrayCircle.add(new Site("영상편집 동아리 The Gist", "https://www.facebook.com/Gentletist/","https://www.youtube.com/channel/UCMUDHS0SZvQilFe5h6eI9rA/videos", R.drawable.thegist));
    arrayCircle.add(new Site("문예창작 동아리 사각사각", "https://www.facebook.com/GIST-%EC%82%AC%EA%B0%81%EC%82%AC%EA%B0%81-238788459851229/", R.drawable.sagaksagak));
    arrayCircle.add(new Site("gist 고양이 지냥이", "https://www.facebook.com/giscats/", R.drawable.giscat));
    arrayCircle.add(new Site("요리동아리 이쑤시개", "https://www.facebook.com/%EC%9D%B4%EC%91%A4%EC%8B%9C%EA%B0%9C-%EC%9A%94%EB%A6%AC%ED%95%98%EB%8A%94-GIST%EC%83%9D-272551203239747/?ref=py_c", R.drawable.essosigae));
    arrayCircle.add(new Site("칵테일 동아리 MixoloGIST", "https://www.facebook.com/Mixologist-1584231725157207", R.drawable.mixologist));
    arrayCircle.add(new Site("보드게임 동아리 BGM", "https://www.facebook.com/GISTBGM", R.drawable.bgm));
    arrayCircle.add(new Site("성소수자 모임 speQtrum", "https://www.facebook.com/gistspeqtrum/", R.drawable.speqtrum));
    arrayCircle.add(new Site("만화 동아리 erutlucbus", "https://www.facebook.com/Erutlucbus/", R.drawable.eru));
    arrayCircle.add(new Site("천체관측 동아리 SpaceBar", "https://www.facebook.com/GISTspacebar/", R.drawable.spacebar));
    arrayCircle.add(new Site("전산 동아리 WING", "https://www.facebook.com/GISTWING/", R.drawable.wing));
    arrayCircle.add(new Site("환경 동아리 온새미로", "https://www.facebook.com/onsaemiro123/", R.drawable.onsaemiro));
    arrayCircle.add(new Site("축구 동아리 Kickass", "https://www.facebook.com/gistkickass/?ref=br_rs", R.drawable.kickass));

    arrayChild.put(arrayGroup.get(0),arrayOfficial);
    arrayChild.put(arrayGroup.get(1),arrayOrganization);
    arrayChild.put(arrayGroup.get(2),arrayCircle);

}

}
4] SiteHolder.java(ViewHolder contain item of GridView)
public class SiteViewHolder {
public ImageView icon;
public TextView icon_name;
public int position;
}

Comment: Migrate to RecyclerView
Comment: Thank you for your advice. I already use Viewholder in Grid View and List View, do you think using RecyclerView will improve the scrolling speed better than it is now?
Comment: RecyclerView will increase the performance & speed depending on your Implementation :)
Answer: Without any code it's difficult to help you.
However you have to split the Loading and the Display procedure. Your Adapters should only hold/display textual/numeric data and leave the image as Empty/Null. Then in the "Adapter.getView()" you have to create an AsyncTask that extracts the image from your drawable folder (doung this in its "doInBackground()" method) and then put it in the relative ImageView (doing this in its "onPostExecute()" method) at the right row position of the ListView.
Comment: I attached the code. Can you check my code?( I have not been able to solve this problem all day.....)
Thank you.


If $f$ is continuous and with a limit at infinity then $f$ is uniformly continuous

Question:
Let $f : [a, +\infty) \rightarrow \mathbb{R}$ be continuous, such that
  $\lim_{x \rightarrow +\infty} f(x) = l \in \mathbb{R}$. Show that f is
  uniformly continuous.

I want to split the domain - one in which we have continuity, and the other in which the values of f are approaching $l$. This means there are theree possibilities for our $x$ and $y$ using the uniformly continuous definition: x and y are in the first part, x and y are in the second, x is in the first and y in the second.
How would I do this proof?
Comment: To avoid splitting into three cases, you could allow the pieces to overlap and make sure to choose $\delta$ less than the width of the overlap. This avoids the case where $x$ is in one piece and $y$ is in the other.
Comment: @GregordeCillia A uniformly continuous function can have unbounded derivative
Comment: Yes. That's why I deleted my comment after a few mjnutes. I was thinking anout lipschitz continuouity and wanted to give an osciallator-like counterexample
Comment: Fix epsilon. Let delta(x) be the maximum delta used in the definition of continuity at x. Show delta(x) has a nonzero limit given the conditions of the problem.
Answer: It suffices you do the following. Given $\epsilon>0$, take $N$ large so that, for $x>N$,
$$|f(x)- l|<\varepsilon/2$$
It follows that if $x,y>N$, then $|f(x)-f(y)|<\varepsilon$. Now consider the interval $[a,N+1]$, which is compact. Here $f$ is uniformly continuous, so there is some $\delta >0$ such that if $|x-y|<\delta$ then $|f(x)-f(y)|<\varepsilon$. We can assume that $\delta<1$.
Consider now arbitrary $x,y\geqslant a$ that are at most $\delta$ units apart. If both $x,y\leqslant N+1$, then you're done. Our choice of $\delta$ is such that if $x> N+1$ then also $y>N$, and you're also done.
Comment: it is still true if limit at $\infty$ exist but not in R ?


Is the Indicator documentation removed?

Question: At the start of the week I started developing my indicator program and the documentation has disappeared since then. Is there plans to remove the functionality or something like that?
Comment: Can you give me the URL you were using please ?
Answer: Is this what you are looking for ?
https://wiki.ubuntu.com/DesktopExperienceTeam/ApplicationIndicators
http://developer.ubuntu.com/resources/technologies/application-indicators/
Comment: http://developer.ubuntu.com/api/ubuntu-12.04/python/AppIndicator3-0.1.html Is the one I was looking for
Answer: Unfortunately most links for indicator API/documentation are dead, but I have managed to find a few here.

Is the Indicator documentation removed?


Defragment disk using Ubuntu

Question: Is it possible to defragment my disk to make more space using Ubuntu?
I searched for tools but I'm not sure which is recommended for this task.
Which is the best way to defragment my complete disk using Ubuntu?
Comment: Defragmentation does not free up space. Linux filesystems do not need to be defragmented. So, what are you trying to do? Which filesystem do you want to operate on?
Answer: Defragmenting disks does not save space, it just reorganises the blocks of data in your files so they can be read faster. It was/is a big problem on file systems used by Windows, but is much less of an issue on filesystems that are (typically) used on Ubuntu installs. I've run linux bases systems for 18 years and never had to do it!
Suggest you use "Disk usage analyser" app to find what's eaten your space up. Also, if you've had the machine for a long time, try this at a terminal:
$ sudo apt autoremove

This will remove packages that don't need to be there any more. Ubuntu is terrible at not removing old kernels that you don't need any more and this has been known to completely fill up disks.
You might also try sudo apt clean which will remove the .deb packages that your packages were installed from.
And of course, check your Recycle Bin!
Hope this helps.

Defragment disk using Ubuntu


Pentaho Report Designer stacked percentage chart Y values

Question: I'm new to Pentaho, and I have a small problem I cannot seem find an answer to.   I'm running stock Pentaho 5.0.1 stable Report Designer. I have a bar chart that I have setup with a data source, everything there is showing/working correctly. I have changed the bar chart to a stacked percentage, and it stacks as expected.   The problem is the values of the chart show from 0.0 to 1.0 incrementing by 0.1. Aesthetically I'd prefer this range from 0% - 100%, but don't see a way to change how it displays.
I see some solutions related to CCC/CGG, but I'm not running any plugins. This is just a out of the box Bar Chart. Playing around with y-axis settings does change the scaling/min/max values but none of that changes the visual display of the chart from the calculated range of 0-1 to is percentage counter part.
Thanks,
Answer: On the chart properties, go to Y-Axis and change the property y-tick-fmt-str (stands for Y ticks format string) to 0.0%.


How to use an AWS elastic load balancer with React HTML5 page

Question: I have an React-app web site that plays HTML5 video hosted on EC2.  I have two instances running and I can view the web page on each of the two instances.  If I set up an ELB that points to a single instance and use the load balancer's URL, the web page works as well.  However, with both machines in the target group, the page fails about 50% of the time when going through the load balancer's URL.
This is the error in _webpack_require_:
<code>TypeError: modules[moduleId] is undefined
modules[moduleId]: undefined

modules: (1) […]
modules["./node_modules/@babel/runtime/helpers/arr…dules/@babel/runtime/helpers/arrayWithoutHoles.js(module, exports)
installedModules: {…}

moduleId: "./node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"
</code>
An internet search for an undefined modules[moduleId] looks like it's all over the place.  And I'm not sure I know enough to ask this question properly.
It looks like some people use nginx (https://www.freecodecamp.org/news/production-fullstack-react-express/), which presumably means not using the AWS ELB, which I expect is much harder to control than AWS.
Answer: Most streaming protocols require session affinity. Try setting up sticky sessions on your load balancer. Here's how to for classic ELB: https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-sticky-sessions.html
Unfortunately that also pins the other traffic as well, but better than 50% failure.
Comment: You can still do it with ALBs: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html#sticky-sessions.
Comment: I had to drop the Application Load Balancer and switch to the Classic Load Balancer to find sticky options.  Thanks!


MC++ interop array access

Question: Using Managed C++ (VS 2005), how would you pass a array< unsigned char > to a function as a unsigned char*?
<code> ref class Utils
 {
     public:

     static void A(array<unsigned char, 1> a)
     {
       //How do I call B()????
     }

     static void B(const unsigned char* a)
     {
        //do stuff
     }

 };
</code>
Answer: Do you do it this way?
<code> void A(array<unsigned char, 1> a)
 {
     pin_ptr<unsigned char> pData= &a[0];
     B(pData);
 }
</code>

MC++ interop array access


Is it possible to use the same Resource Style in multiple buttons and change the background image individually on a IsMouseOver event in XAML

Question: The following code effectively displays an image as the background for a button and changes the image on a isMouseOver event. What I would like to be able to do is use the same style for multiple buttons but be able to change the background image (ImageBrush) individually for each button since each one will use a different image.
Is it possible to use the same Resource Style in multiple buttons and change the background image individually on an IsMouseOver or do I need separate styles for each one?
Style
<Window.Resources>

    </Style>
</Window.Resources>

Use
<Button x:Name="MyButton"
    Style="{StaticResource MainMenuButtonTemplate}"
    Margin="0,50,0,0"
    Width="auto"
    Height="60"
    Command="{Binding FindrViewCommand}"
    BorderBrush="{x:Null}"
    Foreground="White" >
    <Button.Background>
        <ImageBrush ImageSource="Design/Images/my-hover-image.png" Stretch="None"/>
    </Button.Background>
</Button>

Comment: Another answer written by me, which shows attached DP using for IsMouseOver trigger: https://stackoverflow.com/a/45909174/1506454
Answer: The Button class only contains one Dependency Property (DP) for Background, there is no DP for IsMouseOver background.
You have multiple choices, here's a few :
1) Create an Attached Property named IsMouseOverBackground of type Brush and bind to it in your Style.
C#
namespace WpfApp1
{
    public class ButtonHelper
    {
        public static readonly DependencyProperty IsMouseOverBackgroundProperty =
            DependencyProperty.RegisterAttached("IsMouseOverBackground", typeof(Brush), typeof(ButtonHelper), new PropertyMetadata(null));

        public static Brush GetIsMouseOverBackground(DependencyObject obj)
        {
            return (Brush)obj.GetValue(IsMouseOverBackgroundProperty);
        }

        public static void SetIsMouseOverBackground(DependencyObject obj, Brush value)
        {
            obj.SetValue(IsMouseOverBackgroundProperty, value);
        }
    }
}

XAML

<Trigger Property="IsMouseOver" Value="True">
    <Setter TargetName="button" Property="Background" Value="{Binding (local:ButtonHelper.IsMouseOverBackground), RelativeSource={RelativeSource TemplatedParent}}" />
</Trigger>

Note the use of parentheses in the Binding, that is needed when binding to an Attached Property.
2) Create a IsMouseOverButton class that inherits from Button, add a DP called IsMouseOverBackground of type Brush and bind to it in your Style.
C#
namespace WpfApp1
{
    public class IsMouseOverButton : Button
    {
        public static readonly DependencyProperty IsMouseOverBackgroundProperty =
            DependencyProperty.Register("IsMouseOverBackground", typeof(Brush), typeof(IsMouseOverButton), new PropertyMetadata(null));

        public Brush IsMouseOverBackground
        {
            get { return (Brush)GetValue(IsMouseOverBackgroundProperty); }
            set { SetValue(IsMouseOverBackgroundProperty, value); }
        }
    }
}

XAML


Symfony2 File upload form don't display errors

Question: I have a promblem with displaing errors of form that upload file.
Entity:
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Class Document
 *
 * @package    Cfw\SiteBundle\Entity
 * @ORM\Entity(repositoryClass="Cfw\SiteBundle\Entity\Repository\Document\DocumentRepository")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table
 */

class Document
{
    use IdentityEntity;

    use TimestampableEntity;

    CONST UPLOAD_LIMIT = 10;

    /**
     * Document path
     * @var string
     *
     * @ORM\Column(type="text", length=255, nullable=false)
     */
    protected $path;

    /**
     * @var string
     *
     * @ORM\Column(type="text", length=50, nullable=false)
     */
    protected $type;

    /**
     * @var string
     *
     * @ORM\Column(type="text", length=255, nullable=false)
     */
    protected $name;

    /**
     * Image file
     *
     * @var File
     *
     */
    protected $file;
    ....
}

Form Type:
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\DependencyInjection\ContainerInterface;

class DocumentType extends AbstractType
{
    /**
     * @var ContainerInterface $container
     */
    protected $container;

    /**
     * DocumentType constructor.
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'file',
            null,
            [
                'required' => false,
                'attr' => [
                    'label' => false,
                    'title' =>  'form.document.browse',
                ],
                'validation_groups' => ['Default', 'Document'],
            ]
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'error_bubbling' => true,
                'data_class' => 'Cfw\SiteBundle\Entity\Document\Document',
                'translation_domain' => 'messages',
                'cascade_validation' => true,
                'validation_groups' =>  ['Default', 'Document'],
            ]
        );
    }

    public function getName()
    {
        return 'cfw_document';
    }
}

Controller:
public function documentAction(Request $request)
{
    /**
     * @var $user \Cfw\UserBundle\Entity\User
     */
    $user = $this->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    $form = $this->createForm('cfw_document');

    $form->handleRequest($request);

    if ($form->isValid()) {
        $this->get('cfw.document')->uploadDocument($form->getData(), $user);
    }

    return $this->render(
        'CfwUserBundle:Profile:document.html.twig',
        [
            'form' => $form->createView(),
            'documents' => $this->get('cfw.document')->getUserDocuments($user),
            'upload_limit' => $this->get('cfw.document')->getUploadLimit(),
        ]
    );
}

View:
{{ form_start(form) }}

        {{ form_errors(form) }}

{{ 'form.document.title'|trans }}

            {{ 'form.document.description'|trans }}

            {{ form_widget(form.file) }}

            {{ 'form.document.allowed_types'|trans }}

            {{ 'form.document.allowed_size'|trans }}

            <button type="submit" class="btn btn-warning btn-block">{{ 'form.document.submit'|trans }}</button>

{{ form_end(form) }}

Validation config is:
Cfw\SiteBundle\Entity\Document\Document:
    properties:
        file:
            - File:
                maxSize: "10M"
                mimeTypes: ["image/jpeg", "image/gif", "image/png", "image/tiff", "application/pdf"]
                maxSizeMessage: document.file.wrong_size
                mimeTypesMessage: document.file.wrong_format
                groups: [Default, Document]

Trouble is if I upload zip file need to display error of wrong type. But, nothing is displaying, also file is not uploaded (when is pdf or image is ok).
if change in view to {{ form_errors(form.file) }} errors are displayed, but I think is not correct. In profiler error shown on field file, but $form->getErrors() is empty.
Can somebody say what is wrong?
Comment: I get error in FormType need to add
    'error_bubbling' => true
to the field "file", not to setDefaults()
Answer: I get error in DocumentType. Need to add
'error_bubbling' => true

to the field "file", not to setDefaults()


Qt: Sometimes wheelEvent() is not called immediately when rotating the mouse wheel

Question: I use Qt's wheelEvent to implement scrolling in a custom widget. Normally, this works fine.
However, when dragging the mouse and scrolling with the mouse wheel at the same time, it sometimes happens that rotating the mouse wheel by one step does not do anything at first (no wheelEvent is received). This might even randomly happen a few times successively. The next time the application does receive a wheelEvent, it comes with an accumulated event->angleDelta() of all previous events that were not reported separately. Apparently the events are buffered together in this case. Note that the wheelEvent may happen a long time after the initial mouse wheel rotation(s) in this case: it only happens once the wheel is rotated again.
This is an issue, since it means that my widget sometimes does not properly react to scrolling. Is there any way to avoid this kind of buffering and receive all wheel events immediately instead?
Notably this behavior is only well reproducible if at the same time dragging the mouse within the widget, which performs some non-trivial actions as a result. So I suspect it might happen if the event loop seems busy. But it certainly isn't busy enough to be unable to handle each wheelEvent. So I would like to disable this buffering.
I observe this on Linux with Qt 5.12.0. Any help is appreciated, thanks.
Answer: I am answering my own question here since I found the answer after writing it (but was unable to google it before).
The same problem has been reported here (with a somewhat non-descriptive title): Qt QOpenGLWidget wheelEvent strange behaviour
For me, setting Qt::AA_CompressHighFrequencyEvents (see https://doc.qt.io/qt-5/qt.html#ApplicationAttribute-enum) to false seems to have fixed the issue, as posted by @gatis paeglis as an answer to that question.
Comment: That an isolated first event without subsequent events gets hold back forever seems like a bug in the compression algorithm...
Comment: This doesn't fix the same problem for me in Qt 6.4.


How to get powershell runspace status in c#

Question: I'm working with Powershell runspaces in ASP.Net MVC and finding it difficult to get documentation on how to check the status of an existing Powershell Runspace.
Really appreciate any insight!
Controller
public class DemoController : ApiController
{
    PowerShell psInstance = PowerShell.Create();
    static Runspace rSpace = RunspaceFactory.CreateRunspace();

...

private void Initialise()
    {
        try
        {
            psInstance.Runspace = rSpace;
            if (HOW TO CHECK IF RUNSPACE IS ALREADY OPEN?) <<--
            {
                DO NOTHING
            }
                else
            {
                rSpace.Open();
                LoadModules();
            }
        }
        catch (CmdletInvocationException e)
        {
            rSpace.Close();
            rSpace.Dispose();
            psInstance.Dispose();
            throw e;
        }
    }

Comment: Did you not find the [documentation](https://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.runspace.runspacestateinfo(v=vs.85).aspx) for it? Also, why not create a static/class constructor and just `Open` it once there?
Comment: Good point....I might just do that!
Answer: Inspect the RunspaceStateInfo property
if(rSpace.RunspaceStateInfo.State == RunspaceState.Opened)
{
    // runspace is open, do stuff
}
else if(rSpace.RunspaceStateInfo.State == RunspaceState.BeforeOpen)
{
    // call rSpace.Open() before invocation
}
else
{
    // runspace state is either broken, already in use or closed
}

Comment: You sir, are a gentleman and a scholar. Worked a treat, thank you!


MP3 Tag editing with an encrypted home directory

Question: Why can MP3 tag editors not access my encrypted home directory?
I've tried EasyTAG, puddletag, and MP3 Diags...
It seems to be a permission issue, but Banshee can play/edit my music files no problem.

ls -ld / /home $HOME
drwxr-xr-x  25 root root  4096 Aug 22 12:23 /
drwxr-x--x   4 root root  4096 Sep 12  2012 /home
drwxr-x--x 102 matt matt 36864 Sep  1 11:47 /home/matt

And
script some.log
easytag
exit

Shows:
Script started on Mon 02 Sep 2013 16:14:58 EDT
]0;matt@Latitude: ~matt@Latitude:~$ easytag
]0;matt@Latitude: ~matt@Latitude:~$ exit
exit

Script done on Mon 02 Sep 2013 16:15:33 EDT

Comment: Can you show us EasyTag, puddletag or MP3 Diags failing? Try "script some.log" followed by the EasyTag, puddletag or MP3 Diags commands failing, then "exit" and examine "some.log", and post parts of it. I'm not sure why you think these unknown (to us) failures are related to your encrypted home directory. It doesn't look encrypted when you're logged in.
Comment: I've added some screen shots, but I couldn't get the log to capture any events: 'script some.log easytag' didn't open EasyTAG
Comment: Mattarn, try launching easytag from the terminal. First make sure that easytag is closed. Then, go to the terminal, and type in easytag.
Comment: Doesn't work, but 'sudo easytag' let's me open my home directory without errors...
Comment: Sounds like an ownership problem try "ls -ld / /home $HOME". root should own the first two, you should own the third. Did you have "script some.log" and "easytag" on two separate lines? And "exit" on a third?
Comment: Yes, I own the third:
drwxr-xr-x  25 root root  4096 Aug 22 12:23 /
drwxr-x--x   4 root root  4096 Sep 12  2012 /home
drwxr-x--x 102 matt matt 36864 Sep  1 11:47 /home/matt

And script output is:
Script started on Mon 02 Sep 2013 16:14:58 EDT
]0;matt@Latitude: ~matt@Latitude:~$ easytag
]0;matt@Latitude: ~matt@Latitude:~$ exit
exit

Script done on Mon 02 Sep 2013 16:15:33 EDT
Comment: Added outputs to original question as above comment is not formatted...
Comment: I'd do something like (wrapped in `script someother.log...;exit)", this command "sudo strace -e trace=file easytag" and look at all the files the UID==0 easytag successfully opens. Then, do it without the "sudo". Compare and find where the UID==matt easytag fails.
Answer: It looks like a permissions problem to me. On my system,
walt@squid:~(0)$ ls -ld / /home /home/walt
drwxr-xr-x 27 root root  4096 Dec 11 15:13 /
drwxr-xr-x  6 root root  4096 Feb 16  2013 /home
drwx------ 86 walt walt 24576 Dec 11 16:52 /home/walt

while yours is:
ls -ld / /home $HOME

drwxr-xr-x  25 root root  4096 Aug 22 12:23 /
drwxr-x--x   4 root root  4096 Sep 12  2012 /home
drwxr-x--x 102 matt matt 36864 Sep  1 11:47 /home/matt

I would fix this by  sudo chmod o+r /home
I'd like to point out that your "encrypted home directory" looks encrypted only when you're logged off. When you log in, it's overlaid (through mount magic) with the decrypted version. "Encrypted home directory" would be part of this problem if you want some other user to process your files while you were logged off.


CSS font differences between browsers

Question: I am trying to display some text exactly the same in all browsers.
I'm using helvetica, which they all support.
I've found (the hard way) that each browser styles text it's own way, so I'm wondering, what properties do I have to customize in order to get the text 100% same on all major browsers?
The properties I've already set are:
font-family, font-size, font-weight, line-height, text-decoration and letter-spacing, but looking at my text in ff and chrome, I see a difference in the width of a given text. I think height is the same.
Comment: Short answer: it's not possible. There are many different versions of Helvetica and even if there wasn't, as others have noted, the font rendering (smoothing) methods vary among browsers and OSes - not to mention users can override your styles. If your design can't accommodate small differences, there's something wrong with the design.
Comment: @steveax the answer "it is not possible" is a good, valid answer. I was just kicking my self trying to find which CSS property was different between each browser so I could customize it.
Answer: Even with identical CSS rules and identical font files you will never have exactly identical rendering:

modern font formats are composed of layers of overlapping instructions, where the "new better" way does not replace previous iterations, but is present in addition to those. The advantage is that old software can still read the old-style instructions and work as before. The disadvantage is that the same property is described in many different ways and they do not give the same results (you'd think the newest layer would give the best results but the font designer may have only extensively tested and debugged an older one)
to add insult to injury some are system-specific (Windows, OS∕2, OSX…) so even the same generation of software won't read the same instructions depending on the target system
lastly even if a font only contained a single instruction layer, and all your browsers read it completely, they would have some leeway in interpreting it. On an ideal retina screen with high pixel density they'll all use the same shapes and coordinates, but actual screens have too low pixel densities to display small complex text shapes accurately. So the text engines have a choice between displaying sharp but jaded lines (distorting the glyph shapes so they snap to a monochrome pixel grid) or smooth but blurry lines (approximating ideal shapes by playing on pixel grayness level or even subpixel colors). Those adjustments will move text pixels around.
Depending on the system text rendering conventions are not identical. OSX will lean towards smooth blurry rendering, Windows towards sharp jaded rendering, and the Linuxes cover all the choices in-between.
And of course, even on the same system the same software won't make the same choices depending on the quality (pixel density) of the hardware available.

For some insight on all the possible rendering strategies a text engine can choose see
https://docs.google.com/document/d/1wpzgGMqXgit6FBVaO76epnnFC_rQPdVKswrDQWyqO1M
You can not usually control the text rendering compromise chosen by the browser from your web site. Even if you could forcing windows-style rendering on osx (or the reverse) would only annoy uses that want your web site to behave like all the other text they see on their screen. And in fact, the more tolerant your web site will be to browser's font rendering choices, the better it will be. A web site is dynamic. A web site can reflow. Pixel-perfect is not a user ideal. If you want pixel-perfect, serve them a bitmap image, and you'll quickly see how much it is appreciated.
Therefore, only use @font-face for specific design effects, and not to try to force a specific text pixel placement on your site. The first will work beautifully. The second, not at all. If you use @font-face do remember fonts are covered by copyright so sharing any font requires legal permission.
PS. Helvetica is an old font design. It has been derived so many times requesting 'Helvetica' on different systems will yield a plethora of results. So this is a font that can not be used on the web without @font-face.
fonts opentype text-rendering
Answer: You can start with the reset script from Yahoo http://yuilibrary.com/yui/docs/cssreset/
Answer: As Pleun mentioned, there are several reset style sheets that give you a good start. But as hard as you try, you won't get the 100% same look. This is because of the different font rendering strategies browsers and OS use.
Some browsers allow you to control the font-rendering technique. For webkit browsers have a look here http://maxvoltar.com/archive/-webkit-font-smoothing
Answer: all browsers "support" helvetica? which browsers do you speak of? there are a plethora of browsers listed here http://blog.mhurrell.co.uk/post/2946358183/updating-the-helvetica-font-stack that don't or at least cannot utilize helvetica. unless you are serving up a licensed version of helvetica to them. i'm assuming that you aren't.
that link is about building a better font-stack for cross-browser/platform helvetica...although that's a mighty big stack and you may not need it all. you can find others, read more:
http://css-tricks.com/snippets/css/better-helvetica/
http://www.awayback.com/revised-font-stack/
http://unitinteractive.com/blog/2008/06/26/better-css-font-stacks/
Comment: That is good to know, though helvetica came up on my search for web safe fonts so I jumped to the conclusion that major browsers would be ok with it.

CSS font differences between browsers


Torus construction

Question: I understand the usual way to construct a torus. i.e., pasting opposite
edges of a rectangle.
But I don't know the construction by saying take a zero cell and attach
a two one cell and then attaching a two cell.
Also construction of a orientable surfaces of genus 2g from a polygon with
4g sides.
I am not able to imagine. Could you please help me to imagine this?
Thanks in advance.
Answer: Fortunately, the one you understand can be readily seen in the cell-complex construction.
So, take a rectangle, identify opposite sides. Now, draw a picture of a torus, and draw the rectangle on it. This is very important that you can do this. What does the rectangle look like on the torus? It likes like a sort of figure-8 (sort of). All four corners are the same point. Two pairs of opposite sides are associated, so we get only 2 edges, not 4. Good.
This is how the cell-structure comes, too. Take one point (0-cell). Take 2 1-cells (each loop in the figure 8). And take 1 2-cell. But how do we attach our 2 cell? Well, a 2-cell is just a square. So on the original rectangle that you drew and understood, why don't you just take that to be your 2-cell? Then the attaching maps are precisely those implied by your drawing.
So the cell-structure and the rectangle are, in fact, the exact same.  In fact, when I give cell structures for genus-g surfaces, I give them in that fashion.
It all comes down to (in my opinion) finding that figure 8 on the torus itself, to understand what that rectangle is. If this doesn't make sense, comment, and I'll upload an image.

Here, we see the figure 8 and the two loops. All four corners are the same point. Their intersection is the 0-cell, the red and the blue are each 1-cells, and the surface is a single 2-cell is attached with the following attaching map (where a is the red side, b is the blue)
Comment: Thanks mixedmath. Please upload the image. That will be help me.
Comment: @Kannan: done! ${}{}{}{}{}$
Answer: Take a sheet of paper, and curl the far end over to make a cylinder.  The place where the edges of the paper meet is one of your one cells.  Now fold the ends of the cylinder over to touch each other and make a torus.  The circle where these ends meet is another one cell.  The place where your circles intersect is a 0 cell.  Clearly, the paper itself is the two cell.
Its not really all that different from the pasting-opposite-edges-of-rectangle approach.

Torus construction


How to avoid duplicate random number and select another one in android?

Question: I have an Arraylist and an Array of integer like this,
ArrayList<Integer> ar= new ArrayList<Integer>();
    int[] number= {0,1,2,3,4,5};

Now I want to toast the integers from this array evertime I click a button with out any repeatation. After toasting every number from this array I want to toast 'Finished', my logic in onclick listener is here:
Random r = new Random();

            int i1=r.nextInt(number.length-0) + 0;
            if(!ar.contains(i1)){
            Toast.makeText(getApplicationContext(), ""+i1, Toast.LENGTH_LONG).show();
            ar.add(i1);
            }else{

                Toast.makeText(getApplicationContext(), "Finished", Toast.LENGTH_LONG).show();
            }

but this didnt come to my way, It doesnt repeat any number but if it gets a duplicate number in the second click then it is toasting finished, but I want to toast it after every number from the integer array are toasted, wat should be my modified logic?
Comment: If you want 'Finished' to appear every time, don't put it in a conditional block(aka 'else')
Answer: ArrayList<Integer> ar= new ArrayList<Integer>();
int[] number= {0,1,2,3,4,5};
for (int i : number) {
    ar.add(i);
}

Random r = new Random();

// repeat this part and you will never have duplicate numbers
int select = r.nextInt(ar.size());
int random = ar.get(select);
ar.remove(select);

Comment: It works, but after 2 or 3 button click this is causinf force close with index out of bound exception in ar.remove(random)
Comment: Updated: Should be ar.remove(select) and not ar.remove(random) due to API conflict when passing in an int value
Answer: LinkedList<Integer> ar = new LinkedList<Integer>();
    int[] number = { 0, 1, 2, 3, 4, 5 };
    for (int i : number)
        ar.add(i);
    Collections.shuffle(ar);

    //every time you click:
    if (ar.isEmpty()) {
        //toast finished
    } else {
        Integer pop = ar.pop();
        //toast pop
    }

Comment: There is no method called pop here, please correct your answer, i think it will work
Comment: @Reyjohn List doesn't have a pop method, but LinkedList does.
Comment: LinkedList implements Queue. By the way that was only an example, you just need to shuffle the list and take the elements one at a time


Is there a way to specify File Name= in UMMM (Unattended Make My Manifest) creation of Program.exe.manifest?

Question: Is there a way to adjust the UMMM.ini file and / or the UMMM.bat file to specify in the <File Name=... > the \Dependencies subdirectory when it creates the Program.exe.manifest?
Re: vb6 "regfreecom" autocreate manifest for ocx file
Re: VB6 RegFreeCom SideBySide SxS Manifest Test for TABCTL32.ocx
Using a UMMM.ini file like:
Identity zTABCTL32.exe zTABCTL32.exe "TABCTL32 Test program 1.0"
File C:\WINDOWS\system32\TABCTL32.ocx

and a UMMM.bat file like:
UMMM.exe zUMMMTabCtl32.ini .\manifest\zTABCTL32.exe.manifest

pause done?

Then editing the resultant .exe manifest file:
From: <file name="..\..\..\..\WINDOWS\system32\TABCTL32.ocx">
To: <file name="Dependencies\TABCTL32.ocx">

YES the discussion in https://github.com/wqweto/UMMM/issues/16 is in the same ballpark.
I DID tweak the UMMM.vbp to redirect from SysWOW64 to System32.
But that is as far as I want to go. Maybe if I am patient, they will work out a solution.
Here is the final Program.exe.manifest that works fine:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
    <assemblyIdentity name="zTABCTL32.exe" processorArchitecture="X86" type="win32" version="220.127.116.11" />
    <description>TABCTL32 Test program 1.0</description>
    <file name="Dependencies\TABCTL32.ocx">
        <typelib tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" version="1.1" flags="control,hasdiskimage" helpdir="" />
        <comClass clsid="{BDC217C5-ED16-11CD-956C-0000C04E4C0A}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" progid="TabDlg.SSTab.1" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst">
            <progid>TabDlg.SSTab</progid>
        </comClass>
        <comClass clsid="{942085FD-8AEE-465F-ADD7-5E7AA28F8C14}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst" />
    </file>
</assembly>

My efforts are on a tiny scale, not production.

wqw, thank you for all of your efforts.
I am embarrassed to say I did not, at first, take your instructions literally enough.
Here is the .ini file (That Works!):
Identity zTABCTL32.exe zTABCTL32.exe "TABCTL32 Test program 1.0"

File C:\WINDOWS\system32\TABCTL32.ocx "" "" Dependencies\TABCTL32.ocx

And here is the .bat file:
C:\Devlpmnt\LANG\VB6\UMMM-master_1_0_14\UMMM.exe zUMMMTabCtl32.ini .\manifest\zTABCTL32.exe.manifest

pause done?

Here is the resulting manifest file in its appropriate folder:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
    <assemblyIdentity name="zTABCTL32.exe" processorArchitecture="X86" type="win32" version="188.8.131.52" />
    <description>TABCTL32 Test program 1.0</description>
    <file name="Dependencies\TABCTL32.ocx">
        <typelib tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" version="1.1" flags="control,hasdiskimage" helpdir="" />
        <comClass clsid="{BDC217C5-ED16-11CD-956C-0000C04E4C0A}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" progid="TabDlg.SSTab.1" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst">
            <progid>TabDlg.SSTab</progid>
        </comClass>
        <comClass clsid="{942085FD-8AEE-465F-ADD7-5E7AA28F8C14}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst" />
    </file>
</assembly>

This does it all! Thank you.
Comment: Can you add what you would LIKE the INI to look like, just as an example? Its a little hard to follow your question.
Answer: @wqw provided the solution:

I just added support for surrogate value for name attribute in commit
77c7e07. Use something like
File UcsFP20.dll "" ""
Dependency\UcsFP20.dll

to supply explicit value of Dependency\UcsFP20.dll for name
attribute in final manifest. Version 1.0.14 can be downloaded from
repo's Releases tab.

– wqw Jun 24 '20 at 16:52
This was also referred to in https://github.com/wqweto/UMMM/issues/16 which lead up to that commit.
Again, thank you.


Insert Query doesnt work sometimes

Question: The PHP code to insert into the DB. The code sometimes doesn't work. Most of the time it does work.
<?php
    include 'connection.php';
    if (isset($_POST['docsignup']))
     {

        // prepare and bind
        $stmt = $link->prepare("INSERT INTO doctor_details(firstname, lastname, license_num, zip_code, city, state, email, password, speciality) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssissssss", $docfname, $doclname, $docid, $doczipcode, $city, $state, $docemail, $hash, $speciality);

        // set parameters and execute
        $docfname = $_POST['docfname'];
        $doclname = $_POST['doclname'];
        $docemail = $_POST['docemail'];
        $docloginpassword = $_POST['docloginpassword'];
        $docid = $_POST['docId'];
        $speciality = $_POST['speciality'];
        $city = $_POST['city'];
        $state = $_POST['state'];
        $doczipcode = $_POST['doczipcode'];

        // A higher "cost" is more secure but consumes more processing power
        $cost = 10;

        // Create a random salt
        $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');

        // Prefix information about the hash so PHP knows how to verify it later.
        // "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
        $salt = sprintf("$2a$%02d$", $cost) . $salt;

        // Value:
        // $2a$10$eImiTXuWVxfM37uY4JANjQ==

        // Hash the password with the salt
        $hash = crypt($docloginpassword, $salt);

        $stmt->execute();

        echo "New records created successfully";

        $stmt->close();
        $link->close();

     }
    ?>

connection.php
<?php
$link = mysqli_connect("localhost","root","","cl10-doctor");
?>

I have noticed the code doesnt work when i use Upper case in password field.
Am i doing it wrong?
Comment: username and password are case sensitive.
Comment: @MarcoMura That comment doesn't help.. Why doesnt it insert into the DB when the password contains an uppercase letter.
Comment: store your password in lowercase or uppercase.
Comment: Can't we mix uppercase and lowercase?
Comment: dont make it case sensitive.Let the user type what ever he/she wants but at background you convert it in either uppercase or lowercase.
Comment: any help on how to achieve it.. Sorry i'm a beginner
Comment: the password is stored in database in unreadable format so it doesn't make any sens whether it is in uppercase or in lowercase
Comment: 1 step :- convert the password in lowercase using php strtolower() and stored it in your database.  2 step :- at the time of sign repeat step 1
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/66315/discussion-between-vaibhav-and-user3765203).
Answer: Don't make it case sensitive.Let the user type what ever he/she wants but at background you convert it in either uppercase or lowercase.
The password is stored in database in unreadable format so it doesn't make any sens whether it is in uppercase or in lowercase.
Convert the password in lowercase using php strtolower() and stored it in your database
at the time of sign in repeat do the same as above.

Insert Query doesnt work sometimes


Show that for Fibonacci numbers, if $m|n$ then $F_n | F_m$?

Question: I've been trying to solve this problem, I realized the following: For example, for $3|6$ we have:
$$F_6=F_5+F_4=(F_4+F_3)+F_4=2F_4 + F_3$$
I realized that doing this, for $m,n$ and $m|n$ we will always get an expression such as:
$$F_n=xF_m+yF_{m+1}$$
The value of $x$ doesn't seems to matter. But if $y=F_m$ which I strongly suspect it is, then we are done because:
$$F_n=F_m(x+F_{m+1})$$
Until now, I've been unable to show that $y=F_m$ or find another way to prove this. I've been stuck for a while, can you help?
Comment: Nice observation! Yes, a result of this form is true and you can prove it by induction. If you know some modular arithmetic you can think about computing the Fibonacci sequence mod a Fibonacci number.
Comment: Read up this post : https://math.stackexchange.com/questions/11477/fibonacci-addition-law-f-nm-f-n-1f-m-f-n-f-m1?rq=1 , and see if the pattern you are referring to is reflected or not. Some of the answers there present generalizations that you might enjoy as well, including a combinatorial proof, and a proof via matrices.
Comment: Also: https://math.stackexchange.com/q/378116/42969.
Answer: Hint: At the bottom of the wikipedia article on the  matrix form of the Fibonacci sequence are reported the relations
\begin{align}
 {F_m}{F_n} + {F_{m-1}}{F_{n-1}} &= F_{m+n-1},\\
 F_{m} F_{n+1} + F_{m-1} F_n &= F_{m+n}  .
\end{align}
In particular, with $m=n$,
\begin{align}
 F_{2n-1} &= F_n^2 + F_{n-1}^2\\
 F_{2n}   &= (F_{n-1}+F_{n+1})F_n\\
          &= (2F_{n-1}+F_n)F_n  .
\end{align}
Using these with $m=k\cdot n$ so that $m+n=(k+1)n$ and induction will lead you to the result.

Full proof:
We want to show that if $m\mid n$ then $F_m\mid F_n$.
Now, $m\mid n$ is equivalent to showing that $n=km\ \ k\in\mathbb{N}$. The induction will be over $k$.
Obviously $k=1$ ($m=n$) is true.
Now let's assume the statement is true for $1\leq k\leq K-1$, let's show it is true for $n=mK$ as well. By the second equality, choosing $n=(K-1)m$ we obtain
\begin{align*}
F_{n}=F_{Km}=F_{m+(K-1)m}&=F_{m}F_{(K-1)m+1}+F_{m-1}F_{(K-1)m}.
\end{align*}
But now by induction hypothesis $F_{(K-1)m}$ is divisible by $F_m$ thus $F_{(K-1)m}=F_m\cdot d$ and hence
\begin{align*}
F_{n}=F_{m}F_{(K-1)m+1}+F_{m-1}F_m\cdot d=F_m\cdot (F_{(K-1)m+1}+F_{m-1}d).
\end{align*}
which shows that $F_m\mid F_n$
Comment: I proved it using Binet's formula. But can you show me how you did it? I spent a bit of time trying to figure out how to do with that formula but couldn't do it.
Comment: Hi @BillyRubina. I've added the full proof.


What is terminal command line that tells me where system has assigned TMPDIR?

Question: I want to type a command in an Ubuntu 15.10 terminal,
that will tell me what folder is being used as the "temporary" folder.
Is there one?
Tx for any comments.
Answer: The closest I can imagine to "where system has assigned TMPDIR" is the directory that is used when programs invoke the mktemp command.
As explained in the mktemp manual page, this is determined by the environment variable $TMPDIR, falling back to /tmp if the variable is unset
-p DIR, --tmpdir[=DIR]
       interpret TEMPLATE relative to DIR; if DIR is not specified, use
       $TMPDIR  if set, else /tmp.  With this option, TEMPLATE must not
       be an absolute  name;  unlike  with  -t,  TEMPLATE  may  contain
       slashes, but mktemp creates only the final component

You can check to see if $TMPDIR is set on your system using echo $TMPDIR - or more directly, you could run the mktemp command with -u or --dry-run to see what directory it would use
-u, --dry-run
       do not create anything; merely print a name (unsafe)

e.g.
$ mktemp -u
/tmp/tmp.sP1jgc38gg

which confirms that in this case it is using /tmp.
Comment: I tried "echo $TMPDIR", and it returned blank, so I guess TMPDIR is not set.
Comment: I did "mktemp -u", and it showed like yours, /tmp/tmp.K7WLTtKU8Y.
Comment: @OldGrampa so that all sounds normal for Ubuntu
Comment: Thank you Steeldriver, you gave me the info I was seeking.
Answer: The temporary folder, can have two meanings in my mind. You can either have the /tmp folder on disk for Ubuntu to use or the swap space.
The swap space is a partition on your disk, acting as extra RAM.
The /tmp folder is for programs to store data temporarily until the next reboot.


Odoo - How can i switch workflow based on a field condition?

Question: I have two 'state' fields to apply to two different workflows of the same model and I would like to switch between them based on a field value.
Can I achieve that?
Thanks in advance.
[EDIT]
file .py
branch1 = fields.Selection([
     ('state1', 'State 1'),
     ('state2', 'State 2'),
     ]
)

branch2 = fields.Selection([
     ('b2_state1', 'State 1'),
     ('b2_state2', 'State 2'),
     ]
)

wkf.xml
I use same states and transitions methodology for both branches, obviously with appropriate field names which I modified here to post.
DEFINITION
<record model="workflow" id="wkf_branch1">
    <field name="name">Branch 1</field>
    <field name="osv">model.name</field>
    <field name="on_create">True</field>
</record>

<record model="workflow" id="wkf_branch2">
    <field name="name">Branch 2</field>
    <field name="osv">model.name</field>
    <field name="on_create">True</field>
</record>

STATES
<record model="ir.actions.server" id="set_model_to_state2">
    <field name="name">Set Model to State2</field>
    <field name="model_id" ref="model_name"/>
    <field name="code">
            model.search([('id', 'in', context['active_ids'])]).function()
    </field>
</record>
<record model="workflow.activity" id="state1">
    <field name="name">State 1</field>
    <field name="wkf_id" ref="wkf_branch1"/>
    <field name="flow_start" eval="True"/>
    <field name="kind">dummy</field>
    <field name="action"></field>
    <field name="action_id" ref="set_model_to_state2"/>
</record>

....
and so for branch2
TRANSITIONS
<record model="workflow.transition" id="model_state1_to_state2">
    <field name="act_from" ref="state1"/>
    <field name="act_to" ref="state2"/>
    <field name="signal">state2</field>
</record>

....
and so for branch2

view.xml

    <button name="state1" type="workflow"
            string="Reset to state1"
            states="state2"/>
    <button name="state2" type="workflow"
            string="State 2" states="state1"/>

    <button name="b2_state1" type="workflow"
            string="Reset to State1"
            states="b2_state2"/>
    <button name="b2_state2" type="workflow"
            string="State 2"
            states="state1"/>

    <field name="branch1" widget="statusbar"
           attrs="{'invisible': [('type', '=', 'certain_type')]}"/>
    <field name="branch2" widget="statusbar"
           attrs="{'invisible': [('type', 'in', ['other_type1', 'other_type2'])]}"/>

So the problems are:

I can hide the statusbar of the 'branch1' in the view.xml based on the condition in the 'attrs' attribute, but it doesn't work for the buttons (not present in the code here, but i attempt with both 'attrs' and 'invisible' attributes).
I can not show the statusbar of the 'branch2' and not even the buttons.
I don't know how to tell to Odoo to diversify the two workflows, since they belong to the same model.
I don't think the subflow solution will be fine for my case, since I would to use a flow if the model is of one type and the other otherwise.

Thanks again.
Comment: Please edit your question and add: 1. Your code/your attempts 2. Your input, current output and expected output
Answer: Fixed.
I putted both branches inside the same workflow and splitted them up with the 'split_mode' and conditional transitions.
Still remain a problem, but it's secondary.
I would like to show in the statusbar only the states of one branch.
I don't know if it is possible or not.
[EDIT]
Solved that too.
I am showing only the current state with 'statusbar_visible=" "'


Couldn't find Spree::Page Error how to solve this Issue

Question: I have integrated spree static pages gem in my existing spree app.And I created one new page in admin side but the page link is displayed this following error.
Couldn't find Spree::Page
Couldn't find Spree::Page with [WHERE "spree_pages"."visible" = $1 AND (spree_pages_stores.store_id = 1) AND "spree_pages"."slug" = $2]
Answer: Just noticed it seems to be unchecking my store check box on every save in admin side.


Using a method to call individual strings from an array (looping)

Question: This is the question from my assignment that I am unsure of:
The class is to contain a public method nextWord(). When a new line is read, use the String method .split("\s+") to create an array of the words that are on the line. Each call to the nextWord() method is to return the next word in the array. When all of the words in the array have been processed, read the next line in the file. The nextWord()method returns the value null when the end of the file is reached.
I have read the file, and stored each individual string in an array called tokenz.
I'm not sure how I can have a method called "nextWord" which returns each individual word from tokenz one at a time. Maybe I don't understand the question?
The last part of the question is:
In your main class, write a method named processWords() which instantiates the MyReader class (using the String "A2Q2in.txt"). Then write a loop that obtains one word at a time from the MyReader class using the nextWord() method and prints each word on a new line.
I've thought of ways to do this but I'm not sure how to return each word from the nextWord method i'm supposed to write. I can't increase a count because after the String is returned, anything after the return statement cannot be reached because the method is done processing.
Any help would be appreciated, maybe I'm going about this the wrong way?
Can't use array lists or anything like that.
Here is my code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class A2Q2
{

  public static void main (String [] args)
  {
    processWords();
  }

  public static void processWords()
  {
    MyReader reader = new MyReader("A2Q2.txt");

    String[] words = new String[174];

    words[0] = reader.nextWord();
    System.out.println(words[0]);

  }

}

class MyReader
{
  static String name;
  static BufferedReader fileIn;
  static String inputLine;
  static int tokensLength = 0;
  static String[] tokens;
  static int counter = 0;

  // constructor.
  public MyReader(String name)
  {
    this.name = name;
  }

  public static String[] readFile()
  {

    String[] tokenz = new String[174];
    int tokensLength = 0;

    try
    {
      fileIn = new BufferedReader (new FileReader(name));
      inputLine = fileIn.readLine();

      while(inputLine !=null)
      {
        tokens = inputLine.split("\\s+");

        for (int i = 0 ; i < tokens.length; i++)
        {
          int j = i + tokensLength;
          tokenz[j] = tokens[i];
        }
        tokensLength = tokensLength + tokens.length;
        inputLine = fileIn.readLine();
      }

      fileIn.close();

    }

    catch (IOException ioe)
    {
      System.out.println(ioe.getMessage());
      ioe.printStackTrace();
    }

    //FULL ARRAY OF STRINGS IN TOKENZ

    return tokenz;

  }

  public static String nextWord()
  {
    String[] tokenzz = readFile();
    //????
    return tokenzz[0];
  }

}

Answer: Here's a conceptual model for you.
Keep track of your MyReader's state to know which value to return next.
the following example uses tokenIndex to decide where to read at next.
class MyReader
{
  String[] tokens;

  int tokenIndex = 0;

  public String nextWord()
  {
    if(tokens == null || tokens.length <= tokenIndex)
    {
        // feel free to replace this line with whatever logic you want to
        // use to fill in a new line.
        tokens = readNextLine();
        tokenIndex = 0;
    }
    String retVal = tokens[tokenIndex];
    tokenIndex++;

    return retval;
  }
}

Mind you, this isn't a complete solution(it doesn't check for the end of file for instance), only a demonstration of the concept.  You might have to elaborate a bit.
Comment: Notice that the tokenIndex variable above is keeping track of your state, which index you are processing.  You really only need to read one line at a time, and read another new line when your nextWord method exhausts words in the current array (tokenIndex>tokens.length).
Comment: Thank you for your comment, but once I call nextWord, don't all variables reset? (Won't  tokenIndex be 0 when called for a second time?).

EDIT: Realized I needed to initialize outside of the method. Thank you guys very much for the much needed different way of thinking.
Answer: Use a loop and process each element in the array, printing them one at a time?


mysql update query doesn't work

Question: I have this php file for store the logout time. Using insert query I store the login time first. Then I store the logout time using this logout script. The error I'm getting is the one I mentioned in my code which is failed to insert logout time. the $lgotime and $lrec are echoing correctly. Below is my code:
<?php

session_start();

$lgotime = date("Y-m-d H:i:s");

$lrec = $_SESSION['lreclast'];

echo $lgotime;

echo "
";

echo $lrec;

mysql_query("UPDATE tbl_login_record SET logoff_time='$lgotime' WHERE id = '$lrec'") or die("failed to insert logout time");

session_destroy();
header("Location:../login.php");
?>

the $lrec variable is coming from mysql_insert_id() from the script that has the insert query. Help will be really appreciated.
Comment: hey where is the connection string here...
Comment: what.. you are trying to insert or update?
Comment: I'm trying to update.
Answer: if your mysql query dosent work you can change your code like this:
mysql_query("UPDATE tbl_login_record SET logoff_time='".$lgotime."' WHERE id = '".$lrec."'") or die("failed to insert logout time");

it always works for me!
Answer: The problem is that your query is not sending the data, its sending strings
mysql_query("UPDATE tbl_login_record SET logoff_time='$lgotime' WHERE id = '$lrec'") or die("failed to insert logout time");

Should be,
mysql_query("UPDATE tbl_login_record SET logoff_time='{$lgotime}' WHERE id = {$lrec}") or die("failed to insert logout time");

To be honest I would not suggest this either and would use parametrized queries instead.
Comment: you are in php , not java or javascript ; concat using dot
Comment: Even so, the ID is going to be an integer presumably so id='$lrec' will still be incorrect.
Comment: @DavidHirst: MySQL ignores quotes around numerics when being set to numeric fields.
Answer: Please give it a try.
  You are not using session_start() on top of this page and change query as
<?php
 session_start();
 $lgotime = date("Y-m-d H:i:s");

$lrec = $_SESSION['lreclast'];

echo $lgotime;

echo "
";

echo $lrec;

mysql_query("UPDATE tbl_login_record SET logoff_time='".$lgotime."' WHERE id = '".$lrec."'") or die("failed to insert logout time");

session_destroy();
header("Location:../login.php");

Answer: Change the query into the below format and try,
mysql_query("UPDATE tbl_login_record SET logoff_time='".$lgotime."' WHERE id = '".$lrec."'") or die("failed to insert logout time");

Answer: Just remove single quotes from the id in your query because it is integer not String
mysql_query("UPDATE tbl_login_record SET logoff_time='$lgotime' WHERE id = $lrec") or die("failed to insert logout time");

mysql update query doesn't work


How do you fix a shower handle bar

Question: After pulling too hard on this bar, the plastic fitting/washer-type thingy broke off. The right side still has it (picture #2). The bar is now very loose and will come all the way out.
Shower repair kits on Amazon seem to have nothing to offer in this area. And I don't even know how to locate a model number or brand on a shower.
I'd be fine if it looked crappy. I just want it not to leak water into that hole. Ideally I could fix it like new, but if I just had to plug up both sides that would be acceptable. I just don't know how to go about any of that.
Comment: that looks like a shaver, not a shower handle bar
Answer: Take the measurements of the internal and external diameters and turn 2 up on a lathe, if you don't have one or access to one then any local machinist can do it.
They can make them with "ears" or tabs so they will clip into place.
Comment: If you can take out the good one, just take that to a machinist and have them replicate a pair. I recommend replacing both because if one broke, the other probably isn't that much better.
Answer: If one is unable to locate a shop that will fabricate a set of sleeves, another option is to locate a makerspace or a maker who will fabricate via 3D printing. Same suggestion as Solar Mike, a split design that snaps together will make things easier.
Answer: More than likely will look poor, though looking better than poor is an option - caulk it in place with silicone or polyurethane caulk. DIY "rubber rings," once cured.

How do you fix a shower handle bar