Two GFCI outlets on the same circuit, just for code?

Question: I have a condo that hasn't been updated in probably decades, and I am looking to sell it in the near future. As part of my updates, I am installing GFCI outlets in the bathrooms and in the kitchen countertop areas.
However, there is perhaps a situation with my bathrooms. The first floor half-bath and the second-floor full bathroom outlets are on the same circuit. The lights and fans of both bathrooms are on another circuit entirely. This line appears to run just up the wall and power the both bathroom outlets only.
This NEC set of rules says that all bathroom outlets must be GFCI. However, I'm looking at some questions on this site, and it appears that having two on the same circuit might cause some inconvenient, if not unexpected, behavior. This answer seems to indicate that two on the same circuit will cause one to not function properly if the second trips, while this answer says that finding which outlet tripped is an annoyance, when you're not expecting two on the same circuit.
In any case, it seems that one GFCI outlet on the circuit is all that is necessary, strictly speaking, to provide adequate protection.
However, in terms of salability, I would like any potential buyers to look at the bathrooms, see GFCI outlets in both, and not give it a second thought. If they see a regular outlet in the bathroom, they may balk, or have concerns about the property, even if the circuit is adequately wired and protected. I don't want the realtor to say "Don't worry, the owner assures me this is perfectly fine"-- I want it to be a non-issue.
Is there a way to wire two GFCIs on the same circuit, and not have any issue in functionality? It seems like this would be addressed, either in code, or in the hardware itself-- I can't be the only person who has a legitimate, code-driven need for two GFCIs on the same circuit, can I?
Answer: Just connect the cable from the second outlet to the "line" side of the first GFCI (or wire-nut and pigtail the first GFCI. Then install the 2nd GFCI normally.
Alternatively, most GFCI outlets come with little stickers to put on the cover plates of downstream protected outlets.   If you choose that route, you would wire the cable to the 2nd outlet to the "load" side of the first outlet.
Comment: I agree, Ed. I just finished up wiring my son's house and he decided on dual function (AFCI & GFCI) breakers in the panel. I did warn him that nuisance trips would mean a trip to the panel and I suggested AFCI breakers for kitchen and bath with GFCI outlets installed locally.  Given the OP's  situation with a bath on 2 stories, I also think 2 GFCIs would best.  You don't want to take a trip downstairs to the lower bath room to reset a GFCI.  (Esp. if it's "occupied", LOL)
Comment: I think this is better than a GFCI breaker because you can reset the device right there for each bathroom and won't create the nuisance trips.+
Answer: Option 1, fit one GFCI recep, put sticker on the other.
Option 2, fit two GFCI receps, and use only the LINE terminals.
GFCI rules

This NEC set of rules says that all bathroom outlets must be GFCI.

Not at all. Plain outlets are fine if they're downline from a GFCI device.  However...

However, in terms of salability, I would like any potential buyers to look at the bathrooms, see GFCI outlets in both, and not give it a second thought. If they see a regular outlet in the bathroom...

But they should not.  They should see this.

src: The Family Handyman
That's a Code requirement.  If they don't see that, then you're absolutely correct: they should doubt this installation.   Of course, 99% of the time, the stickers are never applied or the homeowners tear them off.
Two GFCIs on same circuit, that don't act weird

Is there a way to wire two GFCIs on the same circuit, and not have any issue in functionality?

Yes. Most GFCI receptacles ship with a warning sticker on the "Load" terminals, intending they not be used carelessly. That is because downline parts of the circuit attached to the "Load" terminals are also protected by that GFCI device.
Putting another GFCI receptacle inside that protected zone is not unsafe, but creates bizarre and annoying problems if they trip.
So, if you want mutual GFCI devices on a circuit without the nuisance of entangled trip effects, simply do not use the LOAD wires on the first GFCI receptacle, so that the second receptacle is not in its protected zone, and the second receptacle acts independently.  Easy peasy.
Read the GFCI instructions for how to attach 2 wires under one screw.

Honestly, I prefer people stick to the "don't remove the warning tape" strategy unless they understand GFCI downline protection and have a specific downline in mind that they want to protect.
Now some people say "Oh, but if we can trick novices into accidentally protecting the downline, that's bettah". I don't think so, because I've supported those people as they go in dervishes trying to understand why their house wiring doesn't work.  Many just give up and unfurl extension cords, and now they have no GFCI protection in their bathroom at all.  Also remember, the stickers are mandatory, so protecting a mystery downline is a code violation.
There is one exception where it's vital to stop and learn how to competently wield the LOAD terminals: When the wiring needs protecting too, because it traverses a danger area like a water feature, dockside etc.  That's where you make heavy use of LOAD on a GFCI device well out of the danger area. But then, of course, you need stickers.
Comment: @user151841 The sticker is fine on the outlet itself if there's room. There isn't, unless you're using Decora style outlets.  I don't see a problem with sticker on the plate.  You can also use a plate with the words molded or laser etched into it, and it doesn't need to be blue.  I prefer making the sticker on a P-touch labelmaker with white tape, and then using a white plate.  I also prefer to state where the reset is. GFCI Protected / reset in other bathroom.  The classier you make it, the less likely goobers are to peel it off.
Comment: @user151841 Yeah, I know... but that's a huge vulnerability of the system at large.  There's no keying, there's *barely* any color coding.  We daily see the fiascos done by *well meaning* people who simply fail to realize they needed to do more research.  Imagine what a genuine fool could do!  My best hope is to get fools to not use LOAD *at all*, which takes the label issue off the table.
Comment: The sticker goes on the plate and not the outlet itself? Whatever... I didn't make the rules : P
Comment: Well, idk, looking at this with my programmer glasses, my concern would be that if average home owners can't be trusted to wire GCFI outlets correctly, they can't be trusted to manage these labels correctly... it's easy to move one plate to another outlet, and then it appears to be that that outlet is GCFI protected, when it isn't!
Answer: There's a difference between "daisy-chaining" (sequential GFCI) and having multiple on different branches of the same circuit. I haven't heard of the latter being troublesome. You won't get around potential nuisance trips with the former.
If that's not your scenario, Just put one in and use the stickers to label the downstream outlets. That's standard procedure and allays any buyer concerns nicely, I'd think. If anyone is really that worried you can demonstrate protection by tripping the unit in the other bathroom.
Comment: I've often thought GFCI-protected stickers should indicate where to find the GFCI outlet.  I suppose trying to have preprinted stickers for every possible location might be impractical, but having some common ones like "Other bathroom", "In this room", "Other side of wall", etc. would seem useful.
Comment: That would certainly be a good additional place to have the information since stickers can get lost, but if an outlet goes dead, being able to look at it and know where to go would seem helpful.  BTW, I've also thought it would be helpful to have a kitchen use beige outlets for one circuit and white for the other, so as to make it clear what someone would need to do if they want to use a water boiler and toaster simultaneously, though what would be even nicer would be if one could have boxes fed from a common 40A or 50A circuit each contain a duplex receptacle and two 20A circuit breakers.
Comment: @supercat if you put your toaster on a 40A breaker, it (or the wiring to it) would catch on fire _long_ before the breaker tripped. That would be a `Bad Thing™`.
Comment: @FreeMan: I said *and two 20A breakers*, so the box would act as a combination of a subpanel and a pair of outlets.  I've seen some electrical boxes with individual breakers in them in things like music practice rooms (wired, interestingly enough, as a light switch that controlled both the room light and the outlet), but I've not seen them in residential settings.  I would think it should be possible and useful have a four-wide box with two breakers and two duplex outlets--one fed by each breaker.
Comment: @FreeMan: Putting the 20A breakers near the outlets would mean reduce the total length of individual 20A wires would make tripping of breakers less common than in places with two separate 20A circuits, and also make resetting the breakers more convenient than in places where they would be located in the main panel.


Selecting a entry in my drop down and trying to add the data to the particular entry

Question: `    <SFX:DropDownListEx ID="GNRType" runat="server" CssClass="gen_field_text" AutoPostBack="true" OnChange="SetValue()" OnChangeSource="OnChangeType"> </SFX:DropDownListEx> <asp:RequiredFieldValidator ID="reqGNRType" runat="server" ValidationGroup="AddConfig"SetFocusOnError="true
Stored Procedure
SELECT 'GNRType','gvConfigList','' SELECT '--SELECT--' AS description, '' AS Code UNION ALL SELECT distinct GNR_Type as description,GNR_Type as code FROM EFT_Config END ELSE BEGIN SELECT 'gvConfigList','' END SELECT GNR_EntityId AS EntityID, GNR_Slno AS Slno, GNR_Type AS [GNRType], GNR_ParentCode AS ParentCode,GNR_Code AS Code, GNR_Description AS [Description], GNR_CreatedBy, GNR_ModifiedBy, GNR_ApprovedBy, GNR_CreatedOn, GNR_ModifiedOn, GNR_ApprovedOn FROM EFT_Config WHERE GNR_Type = @GNRType ORDER BY [GNRType],Slno
Selecting a entry in my drop down and trying to add the data to the particular entry which i have selected from the drop down the entry is creating a empty entry in drop down

and the newly added values coming in the empty drop down entry
Comment: welcome to StackOverflow mate, sorry but you forgot to ask a question. please post the code that you have written and describe the problem that you have with this code.
Comment: Hi bro Thanks for replying.. What code do you want aspx page or stored procedures?? @MongZhu
Comment: @PrabhuKnightrider Please do not post pictures of the code. Rather put the actual code to get better responses.
Comment: @PrabhuKnightrider Can you please post this code on your question and not the comment section?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: well, you could consider just the add button, and then add the new row, and in that row, you would have the drop down, and they select it that way.
But, I suppose you can have that drop down - but you ALSO probably have/want that drop down in the row of data for editing also, right?
You also don't mention if you using a grid view, or a list view for the rows of data? So, it kind of hard to guess what control and how you filled that grid in the first place, and then that of adding rows to the grid, right?
So, we have to take a wild guess here - lets use a grid view.
Also, your dropdown list don't like like a regular asp.net one either. Are you using some 3rd party controls here? (again: a REALLY huge issue to leave out, right?).
Ok, So we have to make a few 100's of guess here, but we will assume a dropdown list for the combo box, and we will assume a grid view for the grid.
so, we have this markup:
        <asp:Label ID="Label1" runat="server" Text="Select City for Hotel to add" Font-Size="Large"></asp:Label>
        <asp:DropDownList ID="cboCity" runat="server" style="margin-left:15px"
            DataValueField="City"
            DataTextField="City" Height="20px" Width="216px" AutoPostBack="True"
            >
        </asp:DropDownList>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="ID" cssclass="table">
            <Columns>
                <asp:BoundField DataField="FirstName"   HeaderText="FirstName"  />
                <asp:BoundField DataField="LastName"    HeaderText="LastName"   />
                <asp:BoundField DataField="HotelName"   HeaderText="HotelName"  />
                <asp:BoundField DataField="City"        HeaderText="City"  />
                <asp:BoundField DataField="Description" HeaderText="Description" />
            </Columns>
        </asp:GridView>

So, we have a combo box (drop down list), and a grid view.
The code to load up the grid view is thus this:
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        LoadData()
    End If
End Sub

Sub LoadData()
    Using conn As New SqlConnection(My.Settings.TEST4)

        Using cmdSQL As New SqlCommand("SELECT City from City ORDER BY City", conn)

            conn.Open()
            Dim rstCity As New DataTable
            rstCity.Load(cmdSQL.ExecuteReader)
            cboCity.DataSource = rstCity
            cboCity.DataBind()
            cboCity.Items.Insert(0, New ListItem("--SELECT--", "--SELECT--"))

            ' Now load our grid data
            cmdSQL.CommandText = "SELECT * from tblHotels  ORDER BY HotelName"
            Dim rstGrid As New DataTable
            rstGrid.Load(cmdSQL.ExecuteReader)
            GridView1.DataSource = rstGrid
            GridView1.DataBind()

        End Using

    End Using

End Sub

And now we have this:

Now, lets write the code for the  combo box. We will select  value in this case city, and then add the new row to the data and the grid.
So, dropdown assumed to have auto post back, and then for the selected index change event, we have this code:
Protected Sub cboCity_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCity.SelectedIndexChanged

    ' User selected a city - lets add the data row

    If cboCity.SelectedItem.Text <> "--SELECT--" Then

        Dim strSQL = "INSERT INTO tblhotels (City, Active) VALUES (@City, True)"

        Using conn As New SqlConnection(My.Settings.TEST4)
            Using cmdSQL As New SqlCommand(strSQL, conn)
                cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = cboCity.SelectedItem.Text
                conn.Open()
                cmdSQL.ExecuteNonQuery()
            End Using
        End Using

        ' reload grid to show new row added
        LoadData()
    End If

End Sub

So, now I can select a value from the combo box, and the new row will now be added to the grid. We would thus say see this:

The code will add the new data row, load grid, and now we have this:


Changing a footer background color isn't working when I edit main.css

Question: I'm trying to change the background color of a Wordpress site's footer. I used Chrome to "Inspect" the element and I saw that it was the footer-top class. So I went to Bluehost->File Manager and found the file, then I found 2 instances of the footer-top class. For both of them, I changed the color part to #000000 (I want this color). But when I save the changes, the site doesn't update. Could someone help me troubleshoot?
Strange note: I found that the link to the main.css stylesheet is this:
<link rel='stylesheet' id='css-main-css'  href='http://www.thefashban.com/wp-content/themes/akay/css/main.css?ver=4.7.1' type='text/css' media='all' />

...but what is that ?ver=4.7.1 part? I have a main.css file, but not one that ends in ?ver=4.7.1. I see that the element is taking from a file with this at the end, but I can't find it.
Comment: Probably a browser cache issue. Clear browser cache and reload the page. Then check if it is updated.
Comment: That was it, thanks!
Answer: The ?ver=4.7.1 is use for caching. As long as that number does not change the browser will know your css has not been updated and will get it from cache instead of making a new request.
Here is a more complete answer : Why adding version number to CSS file path?
you could disable cache in your browser (in the network tab inside chrome developer tools for example) to make sure you are loading a fresh version of your file.


Sharing database connection with threads, instead of creating new ones

Question: I wanted to check into this before I attempt it. I am working on a couple threads which require fetching data from the database within the threads. Currently, based on all I've seen, I am creating a new database connection (TADOConnection) from within the threads. All works fine, except it would be great if I could obtain the connection object from somewhere outside the thread. Basically, I don't want to keep creating a new TADOConnection for each thread execution.
Is it possible to publish a TADOConnection property on the outside of the thread (thus assigning it when I create the thread) and then use that connection within the thread? All I would need to do then is create the TADODataSet inside the thread and assign its connection to this TADOConnection. I'm a little iffy about this, especially because I'm required to call CoInitialize and CoUninitialize when working with ADO in a thread.
Comment: possible duplicate of [Is Delphi's TADOConnection thread-safe?](http://stackoverflow.com/questions/1241844/is-delphis-tadoconnection-thread-safe) Also, you *always* have to call `CoInitialize/CoUnitialize` in every individual thread that uses COM, as COM is thread context specific.
Comment: Pool your threads and make them reentrant so you can reuse threads instead of freeing them after each task.
Comment: Well, would it matter if the threads/s just created a TADOConnection and, well, just hung on to it for the duration of the app run?  Do you need to continually create/destroy these threads?
Comment: Already have my answer - the thing is I am creating these threads on an as-needed basis, which could mean 10 threads at once, or 1 thread every half hour. They do free themselves, they don't stay active, once it completes I have no use in it anymore. I just wanted to see if I could avoid creating it many times.
Comment: I am actually doing 2-layer threading. I have one main thread, which yes, it's continuing in a loop. But the other ones are only created on demand, and are never specifically for one subject. Basically it's sending single requests to the server, waiting for a response, then triggering an event when the response is received. Once I get that response, I don't need it anymore. Each of these requests are sent to the server from its own thread. For example, if I need 3 numbers, each takes a long time to calculate, I send 3 requests at the same time, thus spawning 3 threads.
Comment: It's a reporting tool for an inventory/point-of-sale software - it may have to get the total amounts of sales in 2011, 2010, and 2009, so it creates a thread to get the totals for each year. Once all 3 numbers are received, I can then put those results on a chart, or do whatever else I need with them. There's a wide variety of possible numbers that could be generated with this, for example, amount of money refunded in the past 3 months.
Comment: The overall goal is to be able to crunch numbers 5 times faster by calling 5 threads at once, each getting a particular number. The current model has to wait for all those numbers to be calculated before it can respond.
Answer: The answer looks like no. Because the TADOConnection (and other ADO components) are COM based, they cannot be passed across threads. So in this case, I have no choice but to create a new TADOConnection from within each thread. The threads which continue running make use of this connection each time it loops, but the single-run threads make use of it just once.


php error when uploading at the same time

Question: I have a very simple upload function that receives data (a picture) form a $FILES - it works fine when uploading from times to times. However, if I increase the charge and send quickly a lot of files, it crashes (I don't even get error msg...)
Obviously, it's not a problem of uploading multiples files here - files may be uploaded by different users...
in the index.php, I have :
switch ($_POST['command']) {
case "testWrite":
testWrite($_FILES['picture']);
break;

Then the function is:
function testWrite($data){
    $filename=....;
    if ($data['error']==0) {
        if (move_uploaded_file($data['tmp_name'], $filename)) {

        } else {

        };
    }
}

What am I missing?
Answer: You might check and raise the php.ini settings for max_file_uploads and memory_limit.
The last setting is not so obvious but also affects file uploading.
Enable error reporting:
error_reporting(E_ALL);
ini_set('display_errors', 1);

In your else section you might dump the error:
else {
    echo 'File upload error: ' . $_FILES[0]['error'];
    // or maybe var_dump($_FILES); to see it all
}

Comment: I have checked the ['error'] and it's empty - what's weird is that when I send 10 files/sec (files with 1ko size), the ['tmp_name'] is even empty! (whereas normally that's the real tmp file name...)
Comment: I have tested with the var_dump. If I try to upload 10 files very quickly, the first 9 files fail and don't even return a var_dump !!! I have double checked with a sanity check, and I can normally see the var_dump of a $_FILE...
Comment: Hmm, tricky. Please check `post_max_size` and `upload_max_filesize` - just to be sure, these values are set and are higher than the file size. Folder permissions (writeable) for tmp folder and target folder?
Comment: I have double checked with the hosting service - it's like 10mo and 20mo... compared to the 1ko of the file...
Comment: FYI - the hosting is site ground, and it's a shared hosted account. Not sure if it's related here
Comment: Maybe they have some kind of "upload throttling"? I think we discussed every possible error: ini-settings, correct folder names, permissions, error displaying. 1 thing left: "multipart encoding" set on the form?
Comment: not sure for the throttling... Yes it's a multipart encoding form (at least an object that looks like it in objective C...). Is there something particular I should be careful with in that case?
Comment: `enctype="multipart/form-data"` must be set on the form, but i guess it is, because single file upload works. I'm out of ideas.


Codeigniter seperate front-end and back-end

Question: I'm currently learning myself the Codeigniter framework. I want to create a project that will have a front-end (which will be used by users) and a back-end (which would be used by administrators).
I have looked through different articles, all of them suggest using HMVC to separate the public and admin controllers/views. I have also considered to create two separate projects, one for the public and one for the admin, both using the same database.
I have tried to do research on which one of the methods mentioned above would be the best solution for a potentially large project, but could not come up with any sustainable answer.
Is it possible that two separate CodeIgniter projects can access and use the same database simultaneously?
Edit:
The client project would mostly just query the database for results, whereas the admin project would be full CRUD.
If indeed creating multiple projects would be the recommended way to go, the admin project would be running on a sub-domain i.e admin.example.com whilst the client project would be running on example.com
Answer: It is valid to use any of the approaches you mention. It is a matter of personal preference (read: opinion). I have used each singly and in combination with more or less the same outcome. I have settled on using none of the above. Instead, I use a single project, no HMVC, no subdomains, standard CI file structure. I feel keeping it simple ultimately makes it easier to build and maintain. YMMV.
What separates the public-users from admin-users is authentication and authorization (A&A). Nobody gets into an admin controller without the proper login credentials and permissions. You're going to need A&A anyway to keep the public from accidentally discovering the admin area. IMO, a "special" file structure and subdomains actually make implementing A&A harder.
Depending on your deadline for this project you might want to look at using CodeIgniter Version 4. It's a thoroughly modern revamp of the framework. It is still in beta test mode, but I've found it to be quite stable. They are working hard to get to the release version. There is no published release date yet, but all indications are it will be sooner rather than later.
Answer: The answer as to how to configure CI is really dependent on your needs and what you feel is best. There is no right answer or "acceptable" way of doing things in this regard.
When I first started with Codeigniter, I had just a sub-folder for backend controllers called admin as well as an Admin base/core controller that all admin classes extended rather than CI_Controller. Models/views can be similarly organized in to sub-folders. This was a perfectly acceptable solution in my opinion for small-scale applications.
I moved in to HMVC and found that it really isn't that much different in terms of keeping them both separate. Although you can easily drag-and-drop modules from different projects so long as they are decoupled, you'll still have to jump through hoops to get front/back ends separate. I believe I used this is a starting point: https://github.com/jmtolibas/HMVC-CI3-with-Separate-Backend-and-Frontend
In terms of what you mentioned, having 2 separate projects wouldn't necessarily be a bad idea. You could even share the same system folder with a modification in index.php regarding the system path. Multiple database connections shouldn't be an issue.
So basically, all 3 approach will work, it is up to you to determine which one you like working with the most.
If you want my opinion, I would use Laravel or Lumen on any new project, and separation of front/back end is rather easy with packages, namespacing, .etc.


VB - progress bar not incrementing correct amounts?

Question: I've got a program that's got some variables. I'm trying to interact the variables and make them show a visual perspective of time by using them to increment the progress bar.
A rendition of the code:
Dim count As Integer = ListBox1.Items.Count
Dim _toProgress As Integer = 100 / count
ProgressBar1.Increment(_toProgress)

I've got this all in a loop, so "_toProgress" is added on after a process (in a loop) has been completed...
That's basically the code I have simplified.
The problem is that when I increment the progress bar, it finished before it's supposed to.
e.g:
I've got a loop completing 175 process:
100 / 175 = 0.5714285714285714
So, _toProgress should equal '0.5714285714285714'.
Once one of the processes has been completed, it adds '_toProgress' to the incrementation (ProgressBar1.Increment(_toProgress)).
I know the '_toProgress' integer is correct, because '0.5714285714285714' * 175 = 100.
So I have no clue why the progress bar completes before it's supposed to, any clues?
Comment: Its probably because _toProgress is an Integer instead of a double.  Integer will always be a whole number.
Comment: As @Andrew said change declration of _toProgress to double.
Comment: That makes so much sense now. Thank you Andrew.
Comment: There's more than one flaw here.  If you progressed just a little and only added *one* item to the listbox then you increment by 100.  The simple way is ProgressBar1.Value = 100 * count / 175.  There's nothing special about the Increment() method, it doesn't make it "better".
Answer: You can only increment a ProgressBar in Integer increments.
The easiest solution is to change the Maximum property of the ProgressBar to the number of processes that you have and then increment by 1.
For example:
ProgressBar1.Maximum = ListBox1.Items.Count
ProgressBar1.Increment(1)

Comment: @user3102516: Well, the problem is that you can only increment in integer chunks, so you will have many cases where the progressbar doesn't actually update when something happens. By incrementing by 1, the progressbar will update smoothly and accurately for each item in the count. I think that this approach will actually look much more natural and elegant than the original proposal.
Comment: I was thinking of doing this, I thought it would be more elegant and look more realistic to increment it the way I proposed at first. Thank you.
Comment: you're right. It's still incrementing by the same amount whether it's by 1 or 100/listbox.items.count. So either way it's going to look the same, thanks a lot :)


Do i need DNS if i just plan to use my api server with ip address

Question: I am planning to use my api server without domain name.
I am just planning to use http://ip_address/user/ , http://ip_address/user/update/1232
Do i need DNS?
Do i need any special config file in apache?
Additionally how do i test apache benchmark for this ip_address?
ab -n 1000 -c 10 http://ip_address is not working

Comment: With or without the trailing slash after the IP?
Comment: Did you create at least the default virtual host listening on all IPs on port 80?
Comment: when i enter the ip address, i can see the api output in json format
Comment: What is the output of `ab -n 1000 -c 10 http://ip_address/`?
Comment: it shows all the possible options to use ab. ab: invalid URL
Usage: ab [options] [http[s]://]hostname[:port]/path
Comment: Awesome. After adding a trailing slash, it is working. Is there any problem using an api server without any domain name? You asked me about virtual host. Do i need to create a default virtual host?
Comment: I cannot see there being any problem with using the API without a domain, as you will not need your users to remember the server / its name, because it will only be accessed by your program.
Answer: No, you do not need DNS or a valid domain name pointing to your server.
You will be able to use the API without any problems, even without it.
Apart from a very basic apache configuration (a vhost listening on all IPs on port 80 / 443 for SSL) you will not need any special config.
Your ab command is not working because you are missing the trailing slash, so instead of
ab -n 1000 -c 10 http://ip_address
use
ab -n 1000 -c 10 http://ip_address/


Measurable for all Rationals

Question:
Suppose the function $f$ is defined on a measurable set $E$ and has the property that $\{x \in E ~|~ f(x) > c \}$ is measurable for each rational number $c$. Is $f$ necessarily measurable?

I suspect the answer is affirmative, but I am having trouble proving the theorem. Let $c \in \Bbb{R}$ be irrational. My thought was to try and write $f^{-1}(E \cap (c,\infty))$ as some countable union of sets of the form $\{x \in E ~|~ f(x) > c \}$, but I couldn't see how to do it. The best I could come up with is by noting that there exists a $q \in \Bbb{Q}$ such that $q < c$, and then
$$f^{-1} ( E \cap (c, \infty)) = f^{-1} (E \cap ((q,\infty) - (q,c])) = f^{-1}(E \cap (q,\infty)) - f^{-1}(E \cap (q,c])$$
I know that $f^{-1}(E \cap (q,\infty))$ is measurable, but I don't there being any necessity to $f^{-1}(E \cap (q,c])$ being measurable. I could use a hint.
Answer: Hint: Let $r$ be a real number and let $c_i\downarrow r$. Then we have
$$
\{ x\in E:f(x)>r\} =\bigcup_{i\in \mathbb{N}}\{ x\in E:f(x)>c_i\}
$$
where the right hand side is a union of Borel sets and thus a Borel set.
I leave it up to you to prove that the sets are in fact equal.
Comment: What does "$c_i\downarrow r$" denote?
Comment: A sequence decreasing to r

Measurable for all Rationals


How to make a cursor faster

Question: I have wrote this cursor for commission report. What happens is commission comes in one table, the records are another table. I match two based on certain critera (there is not exact match available). The problem is there are duplicates where records exist. When I match commission with the records table, it can result picking up these duplicates. Thus the rep gets paid more. On the other hand, there are duplicates in commission table also but those are valid beause they simple mean an account got paid for 2 months.
I wrote this query but it takes 5+ minutes to run. I have 50,000 records in records table and 100,000 in commission table. Is there any way I an improve this cursor?
/* just preparation of cursor, this is not time consuming */
CREATE TABLE #result
  (
     repid         INT,
     AccountNo     VARCHAR(100),
     supplier      VARCHAR(15),
     CompanyName   VARCHAR(200),
     StartDate     DATETIME,
     EndDate       DATETIME,
     Product       VARCHAR(25),
     commodity     VARCHAR(25),
     ContractEnd   DATETIME,
     EstUsage      INT,
     EnrollStatus  VARCHAR(10),
     EnrollDate    DATETIME,
     ActualEndDate DATETIME,
     MeterStart    DATETIME,
     MeterEnd      DATETIME,
     ActualUsage   INT
  )

DECLARE @AccountNo VARCHAR(100)
DECLARE @supplier VARCHAR(10)
DECLARE @commodity VARCHAR(15)
DECLARE @meterstart DATETIME
DECLARE @meterEnd DATETIME
DECLARE @volume FLOAT
DECLARE @RepID INT
DECLARE @Month INT
DECLARE @Year INT

SET @repID = 80
SET @Month = 1
SET @year = 2012

/* the actual cursor */
DECLARE commission_cursor CURSOR FOR
  SELECT AccountNo,
         supplier,
         commodity,
         meterStart,
         MeterEnd,
         Volume
  FROM   commission
  WHERE  Datepart(m, PaymentDate) = @Month
         AND Datepart(YYYY, PaymentDate) = @Year

OPEN commission_cursor

FETCH next FROM commission_cursor INTO @AccountNo, @supplier, @commodity, @MeterStart, @MeterEnd, @Volume;

WHILE @@fetch_status = 0
  BEGIN
      IF EXISTS (SELECT id
                 FROM   Records
                 WHERE  AccountNo = @AccountNo
                        AND supplier = @supplier
                        AND Commodity = @commodity
                        AND RepID = @repID)
        INSERT INTO #result
        SELECT TOP 1 RepID,
                     AccountNo,
                     Supplier,
                     CompanyName,
                     [Supplier Start Date],
                     [Supplier End Date],
                     Product,
                     Commodity,
                     [customer end date],
                     [Expected Usage],
                     EnrollStatus,
                     ActualStartDate,
                     ActualEndDate,
                     @meterstart,
                     @MeterEnd,
                     @volume
        FROM   Records
        WHERE  AccountNo = @AccountNo
               AND supplier = @supplier
               AND Commodity = @commodity
               AND RepID = @repID
               AND @MeterStart >= Dateadd(dd, -7, ActualStartDate)
               AND @meterEnd <= Isnull(Dateadd(dd, 30, ActualEndDate), '2015-12-31')

      FETCH next FROM commission_cursor INTO @AccountNo, @supplier, @commodity, @MeterStart, @MeterEnd, @Volume;
  END

SELECT *
FROM   #result

/* clean up */
CLOSE commission_cursor

DEALLOCATE commission_cursor

DROP TABLE #result

I have read answer to How to make a T-SQL Cursor faster?, for that what I get is rewrite this query in table form. But I do have another query which uses join and is lightening fast. The problem is, it can not differentiate between the dups in my records table.
Is there anything I can do to make is faster. This is primary question. If not, do you have any alternative way to do it.
I specifically need help with

Will using Views or store procedure help
I there a way I can use cache in Cursor to make it faster
Any other option in syntax
Comment: The main problem with cursor performance is when the default options are used (global, dynamic, read/write, scrollable). Please read this article: https://sqlblog.org/blogs/aaron_bertrand/archive/2012/01/26/the-fallacy-that-a-while-loop-isn-t-a-cursor.aspx That doesn't mean that adding `LOCAL STATIC READ_ONLY FORWARD_ONLY` is the *only* way to improve efficiency here (it is quite likely you can do this without a loop at all), but it's a good start.
Comment: Have you noticed that the cursor in the linked question was declared with the `FAST_FORWARD` option?
Comment: I would get rid of the cursor all together and write a query that gives you single record you want for your commision and then use it as a sub query or dump it in a temp table. you should be able to get that many records in seconds, not minutes
Comment: Also can you explain `TOP 1` without `ORDER BY`? Do you really not care which matching row in `Records` you get?
Comment: I did which I dont know what that means. Coz he was using cursor in a cursor which probably does not apply here.
Comment: @AaronBertrand, I did not use `order by` not to further overload the cursor. Ideally yes I want it there. But I am already filtering the Records based on if meter start and end date fall in that record then choose only those. If there are more than 1 such record, then it is ok which ever one it is.
Comment: So what do you want the resulting order to be? Right now it is undefined. Even your `select * from result` doesn't seem to care about order.
Comment: What indexes are on the two tables?
Comment: @MartinSmith, dont know about indexes. It they only have 1 primary keys. Aaron, my result table has only result in it so I dont need to apply order or filter there. I will check your updated query.
Comment: why -2 votes within 10 min of each after 8 days of asking the question?
Answer: The very first option is to set the least resource intensive options for your cursor:
declare commission_cursor cursor
local static read_only forward_only
for

Next is to investigate whether you need a cursor at all. In this case I think you can do the same with a single pass and no loops:
;WITH x AS
(
  SELECT
    rn = ROW_NUMBER() OVER (PARTITION BY r.AccountNo, r.Supplier, r.Commodity, r.RepID
      ORDER BY r.ActualEndDate DESC),
    r.RepID,
    r.AccountNo,
    r.Supplier,
    r.CompanyName,
    StartDate = r.[Supplier Start Date],
    EndDate = r.[Supplier End Date],
    r.Product,
    r.Commodity,
    ContractEnd = r.[customer end date],
    EstUsage = r.[Expected Usage],
    r.EnrollStatus,
    EnrollDate = r.ActualStartDate,
    r.ActualEndDate,
    c.MeterStart,
    c.MeterEnd,
    ActualUsage = c.Volume
  FROM dbo.commission AS c
  INNER JOIN dbo.Records AS r
    ON c.AccountNo = r.AccountNo
    AND c.Supplier = r.Supplier
    AND c.Commodity = r.Commodity
    AND c.RepID = r.RepID
  WHERE
    c.PaymentDate >= DATEADD(MONTH, @Month-1, CONVERT(CHAR(4), @Year) + '0101')
    AND c.PaymentDate < DATEADD(MONTH, 1, CONVERT(CHAR(4), @Year) + '0101')
    AND r.RepID = @RepID
)
SELECT RepID, AccountNo, Supplier, CompanyName, StartDate, EndDate,
  Product, Commodity, ContractEnd, EstUsage, EnrollStatus, EnrollDate,
  ActualEndDate, MeterStart, MeterEnd, ActualUsage
FROM x
WHERE rn = 1 --ORDER BY something;

If this is still slow, then the cursor probably wasn't the problem - the next step will be investigating what indexes might be implemented to make this query more efficient.
Comment: +1 [Cursors are the devil](https://www.google.com/search?hl=en&q=devil+cursors&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&biw=1920&bih=956&wrapid=tlif133978342923310&um=1&ie=UTF-8&tbm=isch&source=og&sa=N&tab=wi&ei=DHnbT5LKJ4Ks2gWGoJDMCA#um=1&hl=en&tbm=isch&sa=1&q=devil+icons&oq=devil+icons&aq=f&aqi=g2g-m3g-S4g-msS1&aql=&gs_l=img.3..0l2j0i5l3j0i24l4j0i5i10i24.9679.12090.0.12126.96.36.199.0.0.2.130.1039.4j6.10.0...0.0.PzsA8FZMrBI&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=36f0bd954406024d&biw=1920&bih=956), there is very high likelihood it can be with a regular sql statement.
Comment: This query runs fast, almost instantly but returns 9,000 records where it would return only 400. Need to work on this.
Comment: Sorry, I simply missed the @RepID variable in the where clause inside the cursor (I think it was lost in the formatting before Martin fixed it). Please try my updated code. Your first attempt at a query should never be a cursor, though I do feel a little less strongly about whether they should never be used - they do have their place (e.g. running totals).
Answer: Temp tables are your friend
The way I solved my problem, merging data from two tables, removed duplicates in complex fashion and everything extremely fast was to use temporary table. This is what I did
Create a #temp table, fetch the merged data from both the tables. Make sure you include ID fields in both tables even if you do not required it. This will help remove duplicates.
Now you can do all sort of calculation on this table. Remove duplicates from table B, just remove duplicate table B IDs. Remove duplicates from table A, just remove duplicate table A Ids. There is more complexity to the problem but at least this is probably the best way to solve your problem and make it considerably faster if cursors are too expensive and takes considerable time to calculate. In my case it was taking +5 min. The #temp table query about about 5 sec, which had a lot more calculations in it.

While applying Aaron solution, the cursor did not get any faster. The second query was faster but it did not give me the correct answer, so finally I used temp tables. This is my own answer.

How to make a cursor faster


In JSColor, how do I get the hex of the color?

Question: Using JSColor, after the user picks a color, how do I get the "hex"?
<code>$("input#colorpicker").css('background-color') => this returns background-color: rgb(107, 132, 255);
</code>
But not a hex.
Comment: @dfsq no it doesn't. val() returns nothing.
Comment: Doesn't JSColor put the color HEX value into corrsponding input as a value? I mean `$("input#colorpicker").val()`.
Comment: PLEASE share how you output this. I have the colorpicker running but I can't output the values
Answer: I assume that jQuery.css returns the value that was set.
Try the following function to convert RGB to HEX:
<code>function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);

    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

colorToHex('rgb(120, 120, 240)')
</code>
Answer: Actually upto an extent this depends on browser that it returns in rgb or hex, anyway check out this threads there are nice discussions about it and there are many solutions as well.
Background-color hex to JavaScript variable
and
How to get hex color value rather than RGB value?
and
Can I force jQuery.css("backgroundColor") returns on hexadecimal format?
and
jquery css color value returns RGB?
Answer: There is onchange event available:
<code>$("input#colorpicker").change(function() {
    console.log(this.color);
});
</code>


Stuck on drawing a set of data points (x,y)

Question: Edited with CMilbys suggestion, However i'm getting an error when adding "replayData to the frame.
Here is the replayData class + paint method
public class ReplayData extends JPanel {
/**
 *
 */
private static final long serialVersionUID = 1L;
private ArrayList<Point> points;

// Create new list of points when ready then call Redraw()
public void ReplaceData() {
    points = new ArrayList<Point>();
}

public void addPoint(Point point) {
    points.add(point);
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    for (Point p : points)
        g.fillRect(p.x, p.y, 2, 2);
}

public void draw() {
    repaint();
   }
}

And here is where I try to call it to print all of the records that have been retrieved from the csv
    JButton button_KMeans = new JButton("View K-Means");
    button_KMeans.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            kMeans.initialize();
            kMeans.kMeanCluster();

            //for (Point p : kMeans.getPoints() )
            // Will this be very slow? Data sets are going to be large
            Point temp = new Point();
            for (int i = 0; i < kMeans.TOTAL_DATA; i++)
            {
                temp.x = (int)TrackerData.getRecordNumber(i).getEyeX();
                temp.y = (int)TrackerData.getRecordNumber(i).getEyeY();
                replayData.addPoint(temp); // Add points to JPanel
            }
            replayData.draw();
            // How could I make it so this data shows over like 5 seconds, or over 30 etc?
        }
    });

I'm getting errors when adding the instance of ReplayData to the frame
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
 private ReplayData replayData;

 private void initialize() {

    frame = new JFrame();
    frame.setBounds(100, 100, 1920, 1080);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    frame.add(replayData);  // if I comment this line the program starts fine

Comment: Start by making your graph component transparent using setOpaque and make sure you call super.paintComponent. You should also override getPreferredSize to allow the layout manager to do a better job
Answer: In your paintComponent method you should call super.paintComponent. That was correct so uncomment that.
Secondly, your ReplayData class extends JPanel. Because of this you need to use JFrame's add method and add an instance of the class to the JFrame. This will only allow you to have 1 point though. So I recommend you re-structure your class to have an array of points and not two integer variables which it what it appears to be. So for example
class ReplayDate extends JPanel {
    private List<Point> points;

    public ReplaceData() {
        points = new ArrayList<Point>();
    }

    public void addPoint(Point point) {
        points.add(point);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        for (Point p : points)
            g.fillRect(point.x, point.y, 2, 2);
    }

    public void draw() {
        repaint();
    }
}

// In your Main class
private ReplayData replayData;

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 1920, 1080);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    frame.add(replayData); // Add replay data to jframe
    JButton button_KMeans = new JButton("View K-Means");
    button_KMeans.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        kMeans.initialize();
        kMeans.kMeanCluster();
        for (Point p : kMeans.getPoints()
            replayData.addPoint(p); // Add points to JPanel
        replayData.draw();
    }
}

This will allow you to add any number of points and draw them all. I hope this answered your question. If you are still confused just leave a comment and I will try to explain a little more.
EDIT: To help with a few more problems...
First: When setting the size of a JFrame, yours seems to work since you said nothing about it, however, I've never actually used that method. For future reference it can also be done like this.
jframe.getContentPane().setPreferredSize(new Dimension(width, height));

As for when you add a ReplayData instance to your JFrame, I'm not sure about that one... I copied your code into a compiler and it worked fine for me. Post more code or send me your project and I can take a deeper look.
Lastly, you're worried about speed. How large are your datasets? This also depends on your computer. My computer has a 2.4 GHz Intel Core i5. Since 1 hertz is '1/second', assuming I did this math right, and in an ideal world it could do 2.4 billion operations per second. This obviously isn't the actual case but my point is even with datasets of ~10,000, you will probably notice a small delay, but it will only be seconds.
Comment: Thanks for the reply and useful code! has been very helpful for me. I've updated the main post as I still have some problems with adding replayData to the frame
Comment: I've started a new topic which has link to the latest project + some more specifics on the problem I have at the minute, Thanks for your time!

http://stackoverflow.com/questions/29402995/error-using-method-from-another-class


Change Item Height of ComboBox

Question: How to set combobox item height? My combobox.size=new size(320,40) and I had set combobox.itemheight=18 but it didn't work. I want my itemheight or text height to be 18, and fixed size for the combobox which is 320x40. I used also drawmode property but nothing is happening.
Comment: Change `DrawMode` to *OwnerDrawFixed* and then set `ItemHeight` to the value you want; however, you have to draw the items manually.
Answer: Try changing Font Size of your combo box
Comment: i tried ComboBox.ItemHeight = 18 but didnt work either
Comment: Change its font size instead of itemheight
Comment: ComboBox.Font = new Font("Tahoma",18, FontStyle.Bold); it changed the font height but the combobox height is also changing which is become shorter
Answer: Well, in order to prevent combobox resizing to its default height, you can declare it being manually drawing:
myComboBox.DrawMode = DrawMode.OwnerDrawFixed; // or DrawMode.OwnerDrawVariable;
myComboBox.Height = 18; // <- what ever you want

Then you have to implement DrawItem event:
private void myComboBox_DrawItem(object sender, DrawItemEventArgs e) {
  ComboBox box = sender as ComboBox;

  if (Object.ReferenceEquals(null, box))
    return;

  e.DrawBackground();

  if (e.Index >= 0) {
    Graphics g = e.Graphics;

    using (Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                          ? new SolidBrush(SystemColors.Highlight)
                          : new SolidBrush(e.BackColor)) {
      using (Brush textBrush = new SolidBrush(e.ForeColor)) {
        g.FillRectangle(brush, e.Bounds);

        g.DrawString(box.Items[e.Index].ToString(),
                     e.Font,
                     textBrush,
                     e.Bounds,
                     StringFormat.GenericDefault);
      }
    }
  }

  e.DrawFocusRectangle();
}

Edit: to have the combobox stretched, but not its dropdown list
   myComboBox.DrawMode = DrawMode.OwnerDrawVariable;
   myComboBox.Height = 18; // Combobox itself is 18 pixels in height

   ...

   private void myComboBox_MeasureItem(object sender, MeasureItemEventArgs e) {
     e.ItemHeight = 17; // while item is 17 pixels high only
   }

Comment: @XXX: since its `OwnerDraw` it's your task to get a appropriate font (or at least size); you've insisted on height which is more than recommended one, so the immediate effect is that spacing are large; the other possibility is `OwnerDrawVariable` mode and `MeasureItem` event; see my edit

Change Item Height of ComboBox


The "python.exe" program raises an error when I call "sess.run()"

Question: When I run the following line:
_, loss_value = sess.run([train_op, loss])

Python stops working but when I run the other example (down below), Python and Tensorflow don't raise any errors.
I've tried changing the generation to 1, and the batch_size to 1 but that didn't work either.
Here is my (Python) code:
# More Advanced CNN Model: CIFAR-10
#---------------------------------------
#
# In this example, we will download the CIFAR-10 images
# and build a CNN model with dropout and regularization
#
# CIFAR is composed ot 50k train and 10k test
# images that are 32x32.

import os
import sys
import tarfile
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from six.moves import urllib
from tensorflow.python.framework import ops
ops.reset_default_graph()

# Change Directory
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

# Start a graph session
sess = tf.Session()

# Set model parameters
batch_size = 128
data_dir = 'temp'
output_every = 50
generations = 20000
eval_every = 500
image_height = 32
image_width = 32
crop_height = 24
crop_width = 24
num_channels = 3
num_targets = 10
extract_folder = 'cifar-10-batches-bin'

# Exponential Learning Rate Decay Params
learning_rate = 0.1
lr_decay = 0.1
num_gens_to_wait = 250.

# Extract model parameters
image_vec_length = image_height * image_width * num_channels
record_length = 1 + image_vec_length # ( + 1 for the 0-9 label)

# Load data
data_dir = 'temp'
if not os.path.exists(data_dir):
    os.makedirs(data_dir)
cifar10_url = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'

# Check if file exists, otherwise download it
data_file = os.path.join(data_dir, 'cifar-10-binary.tar.gz')
if os.path.isfile(data_file):
    pass
else:
    # Download file
    def progress(block_num, block_size, total_size):
        progress_info = [cifar10_url, float(block_num * block_size) / float(total_size) * 100.0]
        print('\r Downloading {} - {:.2f}%'.format(*progress_info), end="")
    filepath, _ = urllib.request.urlretrieve(cifar10_url, data_file, progress)
    # Extract file
    tarfile.open(filepath, 'r:gz').extractall(data_dir)

# Define CIFAR reader
def read_cifar_files(filename_queue, distort_images = True):
    reader = tf.FixedLengthRecordReader(record_bytes=record_length)
    key, record_string = reader.read(filename_queue)
    record_bytes = tf.decode_raw(record_string, tf.uint8)
    image_label = tf.cast(tf.slice(record_bytes, [0], [1]), tf.int32)

    # Extract image
    image_extracted = tf.reshape(tf.slice(record_bytes, [1], [image_vec_length]),
                                 [num_channels, image_height, image_width])

    # Reshape image
    image_uint8image = tf.transpose(image_extracted, [1, 2, 0])
    reshaped_image = tf.cast(image_uint8image, tf.float32)
    # Randomly Crop image
    final_image = tf.image.resize_image_with_crop_or_pad(reshaped_image, crop_width, crop_height)

    if distort_images:
        # Randomly flip the image horizontally, change the brightness and contrast
        final_image = tf.image.random_flip_left_right(final_image)
        final_image = tf.image.random_brightness(final_image,max_delta=63)
        final_image = tf.image.random_contrast(final_image,lower=0.2, upper=1.8)

    # Normalize whitening
    final_image = tf.image.per_image_whitening(final_image)
    return(final_image, image_label)

# Create a CIFAR image pipeline from reader
def input_pipeline(batch_size, train_logical=True):
    if train_logical:
        files = [os.path.join(data_dir, extract_folder, 'data_batch_{}.bin'.format(i)) for i in range(1,6)]
    else:
        files = [os.path.join(data_dir, extract_folder, 'test_batch.bin')]
    filename_queue = tf.train.string_input_producer(files)
    image, label = read_cifar_files(filename_queue)

    # min_after_dequeue defines how big a buffer we will randomly sample
    #   from -- bigger means better shuffling but slower start up and more
    #   memory used.
    # capacity must be larger than min_after_dequeue and the amount larger
    #   determines the maximum we will prefetch.  Recommendation:
    #   min_after_dequeue + (num_threads + a small safety margin) * batch_size
    min_after_dequeue = 5000
    capacity = min_after_dequeue + 3 * batch_size
    example_batch, label_batch = tf.train.shuffle_batch([image, label],
                                                        batch_size=batch_size,
                                                        capacity=capacity,
                                                        min_after_dequeue=min_after_dequeue)

    return(example_batch, label_batch)

# Define the model architecture, this will return logits from images
def cifar_cnn_model(input_images, batch_size, train_logical=True):
    def truncated_normal_var(name, shape, dtype):
        return(tf.get_variable(name=name, shape=shape, dtype=dtype, initializer=tf.truncated_normal_initializer(stddev=0.05)))
    def zero_var(name, shape, dtype):
        return(tf.get_variable(name=name, shape=shape, dtype=dtype, initializer=tf.constant_initializer(0.0)))

    # First Convolutional Layer
    with tf.variable_scope('conv1') as scope:
        # Conv_kernel is 5x5 for all 3 colors and we will create 64 features
        conv1_kernel = truncated_normal_var(name='conv_kernel1', shape=[5, 5, 3, 64], dtype=tf.float32)
        # We convolve across the image with a stride size of 1
        conv1 = tf.nn.conv2d(input_images, conv1_kernel, [1, 1, 1, 1], padding='SAME')
        # Initialize and add the bias term
        conv1_bias = zero_var(name='conv_bias1', shape=[64], dtype=tf.float32)
        conv1_add_bias = tf.nn.bias_add(conv1, conv1_bias)
        # ReLU element wise
        relu_conv1 = tf.nn.relu(conv1_add_bias)

    # Max Pooling
    pool1 = tf.nn.max_pool(relu_conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],padding='SAME', name='pool_layer1')

    # Local Response Normalization (parameters from paper)
    # paper: http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks
    norm1 = tf.nn.lrn(pool1, depth_radius=5, bias=2.0, alpha=1e-3, beta=0.75, name='norm1')

    # Second Convolutional Layer
    with tf.variable_scope('conv2') as scope:
        # Conv kernel is 5x5, across all prior 64 features and we create 64 more features
        conv2_kernel = truncated_normal_var(name='conv_kernel2', shape=[5, 5, 64, 64], dtype=tf.float32)
        # Convolve filter across prior output with stride size of 1
        conv2 = tf.nn.conv2d(norm1, conv2_kernel, [1, 1, 1, 1], padding='SAME')
        # Initialize and add the bias
        conv2_bias = zero_var(name='conv_bias2', shape=[64], dtype=tf.float32)
        conv2_add_bias = tf.nn.bias_add(conv2, conv2_bias)
        # ReLU element wise
        relu_conv2 = tf.nn.relu(conv2_add_bias)

    # Max Pooling
    pool2 = tf.nn.max_pool(relu_conv2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool_layer2')

     # Local Response Normalization (parameters from paper)
    norm2 = tf.nn.lrn(pool2, depth_radius=5, bias=2.0, alpha=1e-3, beta=0.75, name='norm2')

    # Reshape output into a single matrix for multiplication for the fully connected layers
    reshaped_output = tf.reshape(norm2, [batch_size, -1])
    reshaped_dim = reshaped_output.get_shape()[1].value

    # First Fully Connected Layer
    with tf.variable_scope('full1') as scope:
        # Fully connected layer will have 384 outputs.
        full_weight1 = truncated_normal_var(name='full_mult1', shape=[reshaped_dim, 384], dtype=tf.float32)
        full_bias1 = zero_var(name='full_bias1', shape=[384], dtype=tf.float32)
        full_layer1 = tf.nn.relu(tf.add(tf.matmul(reshaped_output, full_weight1), full_bias1))

    # Second Fully Connected Layer
    with tf.variable_scope('full2') as scope:
        # Second fully connected layer has 192 outputs.
        full_weight2 = truncated_normal_var(name='full_mult2', shape=[384, 192], dtype=tf.float32)
        full_bias2 = zero_var(name='full_bias2', shape=[192], dtype=tf.float32)
        full_layer2 = tf.nn.relu(tf.add(tf.matmul(full_layer1, full_weight2), full_bias2))

    # Final Fully Connected Layer -> 10 categories for output (num_targets)
    with tf.variable_scope('full3') as scope:
        # Final fully connected layer has 10 (num_targets) outputs.
        full_weight3 = truncated_normal_var(name='full_mult3', shape=[192, num_targets], dtype=tf.float32)
        full_bias3 =  zero_var(name='full_bias3', shape=[num_targets], dtype=tf.float32)
        final_output = tf.add(tf.matmul(full_layer2, full_weight3), full_bias3)

    return(final_output)

# Loss function
def cifar_loss(logits, targets):
    # Get rid of extra dimensions and cast targets into integers
    targets = tf.squeeze(tf.cast(targets, tf.int32))
    # Calculate cross entropy from logits and targets
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, targets)
    # Take the average loss across batch size
    cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
    return(cross_entropy_mean)

# Train step
def train_step(loss_value, generation_num):
    # Our learning rate is an exponential decay after we wait a fair number of generations
    model_learning_rate = tf.train.exponential_decay(learning_rate, generation_num,
                                                     num_gens_to_wait, lr_decay, staircase=True)
    # Create optimizer
    my_optimizer = tf.train.GradientDescentOptimizer(model_learning_rate)
    # Initialize train step
    train_step = my_optimizer.minimize(loss_value)
    return(train_step)

# Accuracy function
def accuracy_of_batch(logits, targets):
    # Make sure targets are integers and drop extra dimensions
    targets = tf.squeeze(tf.cast(targets, tf.int32))
    # Get predicted values by finding which logit is the greatest
    batch_predictions = tf.cast(tf.argmax(logits, 1), tf.int32)
    # Check if they are equal across the batch
    predicted_correctly = tf.equal(batch_predictions, targets)
    # Average the 1's and 0's (True's and False's) across the batch size
    accuracy = tf.reduce_mean(tf.cast(predicted_correctly, tf.float32))
    return(accuracy)

# Get data
print('Getting/Transforming Data.')
# Initialize the data pipeline
images, targets = input_pipeline(batch_size, train_logical=True)
# Get batch test images and targets from pipline
test_images, test_targets = input_pipeline(batch_size, train_logical=False)

# Declare Model
print('Creating the CIFAR10 Model.')
with tf.variable_scope('model_definition') as scope:
    # Declare the training network model
    model_output = cifar_cnn_model(images, batch_size)
    # This is very important!!!  We must set the scope to REUSE the variables,
    #  otherwise, when we set the test network model, it will create new random
    #  variables.  Otherwise we get random evaluations on the test batches.
    scope.reuse_variables()
    test_output = cifar_cnn_model(test_images, batch_size)

# Declare loss function
print('Declare Loss Function.')
loss = cifar_loss(model_output, targets)

# Create accuracy function
accuracy = accuracy_of_batch(test_output, test_targets)

# Create training operations
print('Creating the Training Operation.')
generation_num = tf.Variable(0, trainable=False)
train_op = train_step(loss, generation_num)

# Initialize Variables
print('Initializing the Variables.')
init = tf.initialize_all_variables()
sess.run(init)

# Initialize queue (This queue will feed into the model, so no placeholders necessary)
tf.train.start_queue_runners(sess=sess)

# Train CIFAR Model
print('Starting Training')
train_loss = []
test_accuracy = []
for i in range(generations):
    _, loss_value = sess.run([train_op, loss])

    if (i+1) % output_every == 0:
        train_loss.append(loss_value)
        output = 'Generation {}: Loss = {:.5f}'.format((i+1), loss_value)
        print(output)

    if (i+1) % eval_every == 0:
        [temp_accuracy] = sess.run([accuracy])
        test_accuracy.append(temp_accuracy)
        acc_output = ' --- Test Accuracy = {:.2f}%.'.format(100.*temp_accuracy)
        print(acc_output)

# Print loss and accuracy
# Matlotlib code to plot the loss and accuracies
eval_indices = range(0, generations, eval_every)
output_indices = range(0, generations, output_every)

# Plot loss over time
plt.plot(output_indices, train_loss, 'k-')
plt.title('Softmax Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('Softmax Loss')
plt.show()

# Plot accuracy over time
plt.plot(eval_indices, test_accuracy, 'k-')
plt.title('Test Accuracy')
plt.xlabel('Generation')
plt.ylabel('Accuracy')
plt.show()

This is the error log:
2019-05-07 15:26:48.809018: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2019-05-07 15:26:49.083235: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1432] Found device 0 with properties:
name: GeForce GTX 1080 major: 6 minor: 1 memoryClockRate(GHz): 1.873
pciBusID: 0000:01:00.0
totalMemory: 8.00GiB freeMemory: 6.59GiB
2019-05-07 15:26:49.090110: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0
2019-05-07 15:26:49.872151: I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-07 15:26:49.876033: I tensorflow/core/common_runtime/gpu/gpu_device.cc:988]      0
2019-05-07 15:26:49.878186: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1001] 0:   N
2019-05-07 15:26:49.880459: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 6353 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0, compute capability: 6.1)
WARNING:tensorflow:From 8.3-cnn_cifar10.py:88: string_input_producer (from tensorflow.python.training.input) is deprecated and will be removed in a future version.
Instructions for updating:
Queue-based input pipelines have been replaced by `tf.data`. Use `tf.data.Dataset.from_tensor_slices(string_tensor).shuffle(tf.shape(input_tensor, out_type=tf.int64)[0]).repeat(num_epochs)`. If `shuffle=False`, omit the `.shuffle(...)`.
WARNING:tensorflow:From F:\study\machinelearning\ENV\lib\site-packages\tensorflow\python\training\input.py:276: input_producer (from tensorflow.python.training.input) is deprecated and will be removed in a future version.
Instructions for updating:
Queue-based input pipelines have been replaced by `tf.data`. Use `tf.data.Dataset.from_tensor_slices(input_tensor).shuffle(tf.shape(input_tensor, out_type=tf.int64)[0]).repeat(num_epochs)`. If `shuffle=False`, omit the `.shuffle(...)`.
WARNING:tensorflow:From F:\study\machinelearning\ENV\lib\site-packages\tensorflow\python\training\input.py:188: limit_epochs (from tensorflow.python.training.input) is deprecated and will be removed in a future version.
Instructions for updating:
Queue-based input pipelines have been replaced by `tf.data`. Use `tf.data.Dataset.from_tensors(tensor).repeat(num_epochs)`.
WARNING:tensorflow:From F:\study\machinelearning\ENV\lib\site-packages\tensorflow\python\training\input.py:197: QueueRunner.__init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.
Instructions for updating:
To construct input pipelines, use the `tf.data` module.
WARNING:tensorflow:From F:\study\machinelearning\ENV\lib\site-packages\tensorflow\python\training\input.py:197: add_queue_runner (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.
Instructions for updating:
To construct input pipelines, use the `tf.data` module.
WARNING:tensorflow:From 8.3-cnn_cifar10.py:59: FixedLengthRecordReader.__init__ (from tensorflow.python.ops.io_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Queue-based input pipelines have been replaced by `tf.data`. Use `tf.data.FixedLengthRecordDataset`.
WARNING:tensorflow:From 8.3-cnn_cifar10.py:93: shuffle_batch (from tensorflow.python.training.input) is deprecated and will be removed in a future version.
Instructions for updating:
Queue-based input pipelines have been replaced by `tf.data`. Use `tf.data.Dataset.shuffle(min_after_dequeue).batch(batch_size)`.
Tensor("shuffle_batch:0", shape=(32, 24, 24, 3), dtype=float32)
cifar_loss---------------------0
cifar_loss---------------------1
train_step--------------------------0
train_step--------------------------1
train_step--------------------------2
train_step--------------------------3
WARNING:tensorflow:From 8.3-cnn_cifar10.py:195: start_queue_runners (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.
Instructions for updating:
To construct input pipelines, use the `tf.data` module.

INFO: I'm currently using Windows 10 (x64), Tensorflow 1.12, Python 3 and cudn-9.0
Comment: Hello, can you print out your error message?
Comment: I add the log to the end.Thanks @sslloo
Comment: I don't see any error, just a bunch of deprecation warnings.
Comment: Yes, but the python has stoped working.@xdurch0
Answer: That example is probably written for an older version of TensorFlow. Try downgrading to, say, TF 1.9.
Comment: yes, the code is weitten for old version of tensorflow.but i want to use it in the new version.And  other examples are ok.And the log only show warnings, so i want to get some tips to solve the problem in the new version
Answer: I replace the code reading data by the code below:
def _get_images_labels(batch_size, split, distords=False):
    """Returns Dataset for given split."""
    dataset = tfds.load(name='cifar10', split=split)
    print("load successed.")
    print(dataset)
    scope = 'data_augmentation' if distords else 'input'
    with tf.name_scope(scope):
        dataset = dataset.map(DataPreprocessor(distords), num_parallel_calls=10)
    # Dataset is small enough to be fully loaded on memory:
    dataset = dataset.prefetch(-1)
    dataset = dataset.repeat().batch(batch_size)
    iterator = dataset.make_one_shot_iterator()
    images_labels = iterator.get_next()
    images, labels = images_labels['input'], images_labels['target']
    tf.summary.image('images', images)
    return images, labels

class DataPreprocessor(object):
    """Applies transformations to dataset record."""

    def __init__(self, distords):
        self._distords = distords

    def __call__(self, record):
        """Process img for training or eval."""
        img = record['image']
        img = tf.cast(img, tf.float32)
        if self._distords:  # training
            # Randomly crop a [height, width] section of the image.
            img = tf.random_crop(img, [image_width, image_height, 3])
            # Randomly flip the image horizontally.
            img = tf.image.random_flip_left_right(img)
            # Because these operations are not commutative, consider randomizing
            # the order their operation.
            # NOTE: since per_image_standardization zeros the mean and makes
            # the stddev unit, this likely has no effect see tensorflow#1458.
            img = tf.image.random_brightness(img, max_delta=63)
            img = tf.image.random_contrast(img, lower=0.2, upper=1.8)
        else:  # Image processing for evaluation.
            # Crop the central [height, width] of the image.
            img = tf.image.resize_image_with_crop_or_pad(img, image_width, image_height)
        # Subtract off the mean and divide by the variance of the pixels.
        img = tf.image.per_image_standardization(img)
        return dict(input=img, target=record['label'])

And then the problem solved.I hope it can be userful to others.Thanks~


Replace coaxial cords with ethernet

Question: I recently just bought a home that had coaxial cords wired throughout the house.
I would like to use Ethernet instead but I don't want to have to rip the walls out.
I have a feeling that there is a device which exists which can follow the existing cable and snake the Ethernet cable along the same path as the coax.
Is it possible to do so, or what would be the easiest way to wire Ethernet while leveraging the existing wiring?
Comment: @dandavis -- eh, wifi will always be limited by the infelicities of a radio physical layer...
Comment: @dandavis I can hack your WiFi from outside your house (it may take a while, but it's possible). The only way I can hack your cabled network is to get inside your house and plug into it. First rule of security: once they have physical access they own the device. ;) Speed wise, things may be leaning toward wireless, but physical cables will beat radio waves for security every time.
Comment: @dandavis -- its less bandwidth and more latency, jitter, and signal interference constraints
Comment: Wired internet will always be more secure and faster than WIFI. Just a couple of years ago, when my wife got ROKU, she connected with wifi (she wanted to do it herself). It was terrible and we had a good WIFI router.  I said, why don't we just connect it to the hard wired RJ45 jack next to the TV.  We did that and now it's trouble free.

Next:  MoCA is Media over Coax.   It re-purposes existing COAX for network/internet purposes.   Great solution for older homes that haven't been wired with cat-5 or cat-6.
Comment: @FreeMan   Totally agree with you. Wired will be beat out wifi every time for security and speed.   And lets be real, it doesn't have to be one or the other, I have both wired and wifi in my house for convenience. My phone and laptop use WIFI and my desktop PC uses the hard wired cat-5.  I'm in a remote area so I'm not worried about people hacking into my wifi.
Comment: Why don't you use the coax as a MoCA network?
Comment: ethernet is dying, most everything is wifi by default these days, which now offers comparable performance to ethernet and better security. you could get a bridge to use IP over coax, but the speed is lacking and you'll need converters for each access spot; in that case, modern wifi is WAY faster. If you have a several year old router, I can understand reluctance, but they are not the same as they used to be...
Comment: pssst... @dandavis... go look up "brute force hacking". Note, I didn't say it was fast or efficient, but that it _could be done_. ;) Anyway, we've wandered more than far enough off topic...
Comment: @dandavis Wifi is never going to be as reliable or fast as a cable connection. Yes, the latest wi-fi is faster than last decade's cable, and both are plenty fast, but some nerds are wiring their houses for 25-gigabit fiber now and you just can't get that ridiculous speed on wireless. Of course, you also can't move around the house with a cable connection, so they've both got pros and cons.
Comment: Sometimes, coax will have been added after construction, and might not be stapled in place.  If thats the case, you can use the coax to pull cat6.
Comment: @JPhi1618 good call
Comment: @Gunner what's moCa network
Comment: @ThreePhaseEel if i had a quarter for every time i heard "cell phones won't ever replace landlines because ___ ___ ____", I'd have a few bucks ;). Fact is wifi is getting faster faster than copper. Cheap wifi beats out GBE these days, and expensive wifi can give what some call 10GBE a run for the money. Wifi's plenty fast for most applications which is why jacks are disappearing; the future is clear.
Comment: @FreeMan if you can hack my wifi, why are you wasting time on stack instead of saving or stealing the world? If wifi's AES is broken, so to is https' AES, in which case you can tap my coax outside my house. The first rule of encryption is that your enemy _can_ physically see everything, yet it must remain secure.
Comment: Audiophiles insisted optical toslink is better than copper because you know (unconvincing hand-waving), jitter. Now sparkys are saying electrons are actually better than photons because, you know, jitter. I just go by facts and see that most wifi criticism while applicable at some point is outmoded.
Answer: There is no such "snaking" device. There are devices that can be put at each end of a coax cable to permit internet signals. There are 2 units, A and B, that work with only one length of cable. They are usually used to allow a network camera to run on a coax line. If you run new ethernet cable, the first step is to map the existing cables and make a drawing. Then decide where you will run new cables, maybe eliminating some existing runs. You could plan for one or more wireless access points. They look like ceiling mounted routers.
Comment: If the coax in the walls is not secured, could it not be used as a fish tape, pulling cat6 or whatever through the wall?
Answer: In fact, Ethernet originally ran on coax cables -- but also originally ran as a switchless system where the protocol had to deal much more frequently with recovering from collisions between senders. Today's higher speeds do assume twisted-pair, and at higher speeds multiple-twisted-pair, connections to a central switch which manages data routing.
As others have noted, MoCA (Multimedia over Coax) can be used to route fairly high speed data over a coax cable. It's often used by cable companies that provide internet services; a MoCA modem, or a router with MoCA built in, is used to connect their cable to your Ethernet wiring. You could use MoCA more generally inside the house; interface boxes can be purchased.
Another workaround is Ethernet Over Power (as opposed to Power Over Ethernet). There are devices which will use your house wiring as a shared antenna, letting you just plug them into an outlet wherever you want an Ethernet jack. There may or may not be issues if you want to use an outlet that's on a different phase of AC. I've used these on occasion, when I needed a temporary Ethernet drop somewhere and didn't want to use WiFi or run wires; they generally won't give you the fastest possible connection, but most folks don't need the fastest possible connection most of the time.
WiFi is certainly an alternative, with WiFi boosters or "mesh" routers to reach farther places as a series of WiFi hops. Again, performance of WiFi isn't as good as wired, but for most purposes it's good enough. Since this is radio, and visible outside the house, you do want to watch your network configuration to make sure it's as secure as your hardware will let you be. On the other hand, I like being able to connect from the far corner of my back yard sometimes, and I have a lot of home automation that talks WiFi (or other radio protocols, Z-wave and Zigbee, but those need yet another kind of hardware).
So... Yeah, you can use the coax. It'll take some investment, and may not give you as good a result as if you run proper CAT5/CAT6 cables and Ethernet jacks, but it can be made to work.
Comment: Note that if you have access to the rooms from basement/crawlspace, attic, or (in the case of a 2-story building) both plus a place you can oull wires between those, running Ethernet cables is not hard. The _plugs_ are hard to attach reliably to a cable, but most jacks use simple punch-down connections and you can then use commercially manufactured jumper cables from those jacks to your router on one end and the downstream device on the other

Replace coaxial cords with ethernet


Why isn't Ubuntu 14.04 shutting down?

Question: I have freshly installed Ubuntu 14.04 onto an Asus X554S laptop. When I click the restart of shutdown button, it starts shutting down, but after a bit of loading (showing that purple loading screen) it just simply stops and never finishes shutting down. I have to manually turn the computer off, after which if I want to turn it on again, it doesn't reboot, only if I repeat the process (turn off then on) once more.
I have tried the following:

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi=force" (no result)
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi=off" (no result)
removed the quiet splash part so I could see what's happening (I'm not sure if I did that right), but the plymouth screen still appeared (before anyone asks, I did update-grub after each attempt)
blacklist wistron_btns (no result)
sudo poweroff (yields the same result; well, more bulbs light up on the plymouth screen, but I don't think that's progress)
Cairo Dock is not installed (I remember it used to cause similar problems for some people)
connects to wireless network perfectly and has internet access (so my guess is it's not a network issue, although I could be wrong)
I have had no graphic issues until I removed "quiet splash" from GRUB, then upon booting it showed text, but the numbers and letters were unintelligible (maybe an issue with the Nvidia driver?)

What else can I do?
EDIT: In the process, for reasons beyond my comprehension, the touchpad stopped working. Now neither xinput --list nor cat /proc/bus/input/devices shows any signs of it. I did install a pack of updates recommended by the system, though (which might have solved my initial problem without my knowing, see below).
Nevertheless, I did update my nvidia driver using sudo apt install nvidia-340 -y, after which it did shut down properly. Restarting the machine, however, proved troublesome, as bbswitch found no discrete VGA device. Not even my mouse was usable. So, I used sudo apt purge nvidia*, after which my computer did reboot. I tried nvidia-352 just to see what happens, but the results were the same: successful shutdown, no discrete VGA device. So I purged that as well.
Now the situation is rather peculiar as I find no graphical errors, the system shuts down and powers off properly, yet my touchpad is still undetected. I guess that deserves a question of its own. I'll still leave this one unsolved for now until I'm absolutely sure the problem doesn't creep back in somehow.
Comment: I had the same problem with 16.04.  Try installing Nvidia driver. It solved my problem.
Comment: Tried that; edited post with results.
Comment: I cannot find your laptop in Asus website, but if it is new (or even it is not), maybe there is a problem with BIOS. Try update it and set it to default. In addition why don't you try installing 16.04 and see what happens?
Answer: That's very odd. I've heard about this issue before, but assumed it was fixed in the newer versions of Ubuntu.
Can you give the following command a shot and let me know what happens?
sudo init 0

Why isn't Ubuntu 14.04 shutting down?


How do I add the library to link the OpenGL framework in iPhone SDK?

Question: I am trying to study OpenGL and I have the framework added, but I am getting linker errors.  I believe the issue is adding the library to the project for linking and EVERY time I try to add a library, I hunt around for the configuration setting forever.  Someone, please give me the simple click-n-go answer!
Comment: I thought I provided a screen shot in my original post ... try this

[IMG]http://i47.tinypic.com/2004eoz.jpg[/IMG]
Answer: The linker cannot find the CAEAGLLayer framework to link against.
Add the QuartzCore.framework and the linker will be able to find the missing framework.
To do this right-click on the Frameworks the choose:
Add > Existing Frameworks > QuartzCore.framework.
alt text http://img19.imageshack.us/img19/223/screenshot20091206at544.png
Comment: Thanks Brock - that is what I needed :)  I did find the list of libraries, but that is too indirect since the choices don't have names that one can be certain are related to the imported header files.  When I used your suggestion, that takes care of 'both' sides.


Where do you buy Elite Dangerous for Mac?

Question: In the Frontier Store, https://www.frontierstore.net/games/elite-dangerous-cat.html, I can see Elite for Mac, but no other version for Mac. There's Elite Dangerous and Elite Dangerous Deluxe, but none of those list Mac as supported.
How do I get Elite Dangerous for Mac?
Answer: Elite Dangerous is Mac supported, however some other titles such as Elite Dangerous: Horizons / Arena are not.    The Elite Dangerous Deluxe package available from the Frontier website includes Horizons, and so is not Mac supported.
The official Frontier site states that this is because the necessary shaders / OpenGL support are not available yet on the Mac.
https://support.frontier.co.uk/kb/faq.php?id=228

Sadly, neither the OS X OpenGL nor Apple's Metal API support the required compute shaders and the other possibilities that we have explored simply don't allow us the performance that Elite Dangerous: Horizons requires.
Answer: Steam store has Elite Dangerous aswell, and Horizons. They can be played on the Mac, not sure about the elitedangerous website, but if steam sells it for mac, you should get it over there too.
Comment: They can't both be played on a Mac though.  It even shows on Steam that ED is supported on Mac, ED:H isn't.
Comment: My apologies, I thought they would both work on a Mac.


C# images, object in use elsewhere error

Question: i am extremely new to C# so excuse me if i don't explain this well.
i'm retrieving images from my computer camera, and along with displaying them in a PictureBox, i'm encoding them to jpegs and sending them to a shared dictionary. here's my code:
void CurrentCamera_OnImageCaptured(object sender, CameraEventArgs e)
        {
            this.pictureBoxMe.Image = e.Image;

            if (myName != "" && Form1.PicSent)
            {
                SendPic sendP = new SendPic((Image)e.Image.Clone());
                new System.Threading.Thread(new System.Threading.ThreadStart(sendP.send)).Start();
            }

        }

 public class SendPic
        {
            Image im;
            public SendPic (Image im)
            {
                this.im = im;
            }
            public void send(){

                Form1.PicSent = false;
                var memoryStream = new MemoryStream();

                im.Save(memoryStream, ImageFormat.Jpeg);

                var byteArray = memoryStream.ToArray();

                Form1.sd["/" + myName + "/video"] = byteArray;

                memoryStream.Close();
                Form1.PicSent = true;

            }
        }

the problem is that i'm getting the "Object is currently in use elsewhere." error on the line: SendPic sendP = new SendPic((Image)e.Image.Clone());
based on other forum posts i've found, i already changed it so that the image is passed to the thread, and so that it's a clone. however i'm still getting the same error (though it lasts longer before crashing now).
i read something about locking? how do i implement that in this case? or is there something else i need to do?
thanks.
Answer: It behaves as though the OnImageCaptured method runs on a thread.  Which isn't unlikely for camera interfaces.  Set a breakpoint and use the debugger's Debug + Windows + Threads window to see what thread is running this code.
The failure mode is then that the UI thread is accessing the image to paint the picture box, simultaneously with this worker thread calling Clone().  GDI+ does not permit two threads accessing the same image object at the same time.  It would indeed be flaky, no telling at what exact moment in the time the UI thread starts painting.  PicSent is another accident waiting to happen.
Comment: yes, i think this is a threading problem like you say. how do i fix it? i just tried adding a lock "lock(myLock){}" around both "this.pictureBoxMe.Image = e.Image;" and "SendPic sendP = new SendPic((Image)e.Image.Clone());". however the problem is still occurring. oh, and PicSent was another lame attempt at solving this problem, but it's not working so i'll get rid of it.
Comment: Locking doesn't work, you can't lock the PictureBox' paint code.  Clone the image twice, one for the picture box, another for processing.  I imagine you can skip the second clone.
Comment: Btw, not sure Clone() is good enough.  Use the Bitmap(Image, Size) constructor.
Comment: adding the second clone appears to be working.. it's been running for a couple minutes without crashing. i'll look into Bitmap(..) as well. thanks!
Answer: One thing that catches my eye is that the SendPic class accesses your dictionary asynchronously (the line: Form1.sd["/" + myName + "/video"] = byteArray;).
However, dictionaries and hashtables are not guaranteed to be thread-safe for write operations. You should be safe if you make the code accessing the dictionary to be thread-safe. A simple lock would be a way to start.
Sort of like this:
public class SendPic
{
    private object lockobj = new object();
    // .... whatever other code ...

    public void send()
    {
       // .... whatever previous code ...

       lock(lockobj)
       {
          // assuming that the sd dictionary already has the relevant key
          // otherwise you'd need to do a Form1.sd.Add(key, byteArray)
          Form1.sd["/" + myName + "/video"] = byteArray;
       }

       // .... whatever following code ...
    }
}

Quote from MSDN:

Thread Safety A Dictionary<(Of <(TKey, TValue>)>) can support
  multiple readers concurrently, as long
  as the collection is not modified.
  Even so, enumerating through a
  collection is intrinsically not a
  thread-safe procedure. In the rare
  case where an enumeration contends
  with write accesses, the collection
  must be locked during the entire
  enumeration. To allow the collection
  to be accessed by multiple threads for
  reading and writing, you must
  implement your own synchronization.
Comment: thanks for the suggestion. i tried it, but i'm still getting the error in the same spot. also tried adding locks in 2 other spots (see my other comment), but it still doesn't work.


How to add a custom marker in Android systrace?

Question: I am using systrace to dig into the performance issue in my app, I am wondering if there's a way to add a tag / marker when certain event happens in the systrace result? The specific event I am looking for is input event, but it's hard to tell from systrace which input event is which. I am on Android 4.2.2
Cheers,
Johnny
Answer: You can, using android.os.Trace, but the feature wasn't added until Android 4.3 (API 18).  You can find an example here.


One line if statement in PHP

Question: I'd like to to some thing similar to JavaScript's
var foo = true;
foo && doSometing();

but this doesn't seem to work in PHP.
I'm trying to add a class to a label if a condition is met and I'd prefer to keep the embedded PHP down to a minimum for the sake of readability.
So far I've got:
<?php $redText='redtext ';?>
<label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*
<input name="_name" value="<?php echo $requestVars->_name; ?>"/>

but even then the IDE is complaining that I have an if statement without braces.
Answer: use the ternary operator ?:
change this
<?php if ($requestVars->_name == '') echo $redText; ?>

with
<?php echo ($requestVars->_name == '') ? $redText : ''; ?>

In short
// (Condition)?(thing's to do if condition true):(thing's to do if condition false);

Comment: I did think of using a ternary if, but dismissed it as i didn't have an else condition. using `''` as the else is a good idea.
Comment: isn't this counter intuitive to have the `echo` on the left (condition) side and not in the command?
Answer: You can use Ternary operator logic
Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e
/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

Comment: +1 for the name of the operator, as it helps who doens't know how to call it (like myself) for future references...
Answer: Something like this?
($var > 2 ? echo "greater" : echo "smaller")

Comment: why duplicate echo 2 times?
Answer: Sample Usage
Here are a couple more uses of ternary operators, ranging from simple to advanced:
Basic Usage:
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');

Short hand Usage:
$message = 'Hello '.($user->get('first_name') ?: 'Guest');

Echo Inline
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');

A bit Tougher
$score = 10;
$age = 20;
echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? 'behind' : 'above average') : ($score < 50 ? 'behind' : 'above average')); // returns 'You are behind'

complicated level
 $days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31)); //returns days in the given month

To learn more about ternary operators and usage, visit PHP.net Comparison Operators or here.
Answer: I like to use the minimalist PHP text output syntax:
HTML stuff <?= $some_string ?> HTML stuff

(This works the same as using an <?php echo $some_string; ?>)
You can also use the ternary operator:
//(condition) ? (do_something_when_true) : (do_something_when_false);
($my_var == true) ? "It's true" : "It's false ;

Ending up like this:
<?= ($requestVars->_name=='') ? $redText : '' ?>

Answer: Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis

But in this case you can't use shorter reversed version because it will return bool(true) in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case

Answer: Ill provide with an other answer since the original question specifies the use of if() in html
<?= (pll_current_language() == 'en') ? 'About us' : 'Om oss' ?>

Answer: The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well
function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();

One line if statement in PHP


Avoiding the timeout exception while connecting to a https url to send request to a web-service

Question: In a dotNet mvc application, while trying to send requests to a http url, my application is working as expected. However, when I try to send requests to a https url, I get the following error ( upon publishing the app in IIS and running it in a web browser) :
<code>Server Error in '/dotnetstage' Application.
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.63.64.146:443
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.63.64.146:
</code>
I understand that it has got something to do with the SSL certificates, so I found that there's a way to ignore certificate validation:
<code> WebRequest webRequest = WebRequest.Create(reqURL);
            ServicePointManager.ServerCertificateValidationCallback += delegate { return true; }; //this line works for the certificate validation ignoring
</code>
Even then, I am getting the same error. I have two queries:

Am I adding the ServicePointManager line at the proper place? If not
what is the correct location where you add this in your code?
Is there anything else I need to take care of ?

Any help or at least a pointer towards the right approach will be higly appreciated. Stack Overflow helped me a lot with learning to code in c# mvc apps and build complex caller applications in a matter of 4 weeks and I look forward to getting a quick solution to this as well. Thanks. :)
Comment: Whats the point of using certificates if you just ignore their authenticity? That ServerCertificateValidationCallback hack should not be used in production.
Comment: @scheien Good question. Well currently , we are not concerned with the authenticity of the certificates else we would have created a certificate store in the code and processed the same. We just want to demonstrate other functionalities of the code which are not dependent on the SSL certificate(s).
Answer: The ServerCertificateValidationCallback  should be defined first before making the web request. But in your case the issue is totally different it could be that the web server side code crashed before it could send a response back.


Route mouse-event to underlying control

Question: I have a usercontrol with a grid whith just one row and one column. To this column I add a combobox which fills the whole space of the column. Now I want to put a canvas-element over the combobox in the left corner. Until here everything works fine.
The code:
<Grid>
<ComboBox Style="{StaticResource Flat}" SelectionChanged="ColorSelectionChanged" BorderThickness="0" ItemsSource="{Binding ItemCol, UpdateSourceTrigger}"\>
<Canvas Margin="5,5,0,5" Width="25"  HorizontalAlignment="Left" Background="{Binding SelectedColor, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

If I move the mouse over this conrtrol I only get the selection of the combobox if I'm not over the canvas. How can I route the mouse-events from the canvas to the combobox?
Comment: Try to set the property IsHitTest = false on your canvas or was it IsHitTestVisible = false. Something like that.
Answer: If the canvas is just for show, you can turn off hit testing IsHitTestVisible="false" on the canvas
http://msdn.microsoft.com/en-us/library/system.windows.uielement.ishittestvisible.aspx

Route mouse-event to underlying control


IOS- how to pick multiple images in UIImagePickerController

Question: how to pick multiple images in UIImagePickerController in uiimageview.
Answer: You can use the github code link..GitHub Link
In this link you got all the solutions of the problem