text:
Q: Need multi select checkbox drop-down, when option selected textbox should be displayed beside option in same drop-down Something like this:-

Need multi-select checkbox drop-down, when option selected textbox should be displayed beside option in the same drop-down
I coded it, but the textbox appears down.
My code:

$(".hidden-textbox").hide();
$("select#specialHandling").change(function() {
  var selected = [];
  for (var option of document.getElementById('specialHandling').options) {
    if (option.selected) {
      selected.push(option.value);
      console.log("Selected Value:-" + option.value);
    }
  }
  if (selected.indexOf("FLEXWARE") > -1 || selected.indexOf("Service Migration Order") > -1) {
    $(".hidden-textbox").show();
  } else {
    $(".hidden-textbox").hide();
  }
});
.select-checkbox {
  background: url(images/select-arrow-down.png) no-repeat;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-position: right 15px center;
  width: 100%;
  padding: 9px 40px 9px 9px;
  font-size: 16px;
  font-weight: normal;
  line-height: 1;
  -webkit-appearance: none;
  -moz-appearance: none;
  /*overflow: hidden;*/
  overflow-y: hidden;
  cursor: pointer;
  appearance: none;
  text-overflow: '';
  word-wrap: normal;
  margin-left: 30px;
}

.select-checkbox option::before {
  content: "\2610";
  text-align: left;
  display: inline-block;
  -webkit-appearance: menulist;
}

.select-checkbox option:checked::before {
  content: "\2611";
}

.hidden-textbox {
  display: inline-block;
}

Special Handling

    <input id="specialHandling" name="specialHandling" multiple>
    <option value="IPFLEX TN MOVE">IPFLEX TN MOVE</option>
    <option value="FLEXWARE">FLEXWARE </option>
    <option value="SD-WAN">SD-WAN</option>
    <option value="US Onshore Delivery">US Onshore De`enter code here`livery</option>
    <option value="US Citizen Delivery">US Citizen Delivery</option>
    <option value="Custom Order with DLP">Custom Order with DLP</option>
    <option value="Service Migration Order">Service Migration Order</option>

    </select>
    <input type="text" class="hidden-textbox" name="Reference Designator" id="referenceDesignator" />

Please advise me how can I resolve this.


text:
Q: Rails 3.1: Intermittent 500 Internal Server Error when serving uncompressed assets I'm upgrading an app to Rails 3.1. Quote often, Firebug will complain about some assets. Here are some errors pasted from Firebug:
"NetworkError: 500 Internal Server Error - http://unstilted.dev/assets/jquery-ui.js?body=1"
jquery...?body=1
"NetworkError: 500 Internal Server Error - http://unstilted.dev/assets/admin/pages/file_attachments.js"
file_a...ents.js
"NetworkError: 500 Internal Server Error - http://unstilted.dev/assets/admin/file_attachments/sortable.js?body=1"
sortab...?body=1
"NetworkError: 500 Internal Server Error - http://unstilted.dev/assets/jquery.js?body=1"

Refreshing the page would yield different assets showing the same error. When I copy and paste the URL I see the files just fine.
I'm using:

*

*Ubuntu 11.04

*Apache+Passenger 3.0.9

How do I fix this?
UPDATE: Log file
In this particular instance, jquery-ui.js was showing an error in Firebug.  My log file looked like this:
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at Tue Sep 06 22:24:39 +0800 2011
Served asset /jquery.js - 304 Not Modified (0ms)

Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at Tue Sep 06 22:24:39 +0800 2011

Started GET "/admin/site/sites/storage.js" for 127.0.0.1 at Tue Sep 06 22:24:39 +0800 2011
Served asset /jquery_ujs.js - 304 Not Modified (0ms)

Started GET "/assets/application.js?body=1" for 127.0.0.1 at Tue Sep 06 22:24:39 +0800 2011
  Processing by Admin::Site::SitesController#storage as JS
Served asset /application.js - 304 Not Modified (3ms)
  ...
Rendered admin/site/sites/storage.js.erb (0.1ms)
Completed 200 OK in 58ms (Views: 5.1ms | ActiveRecord: 21.1ms)

Started GET "/assets/admin/logo.png" for 127.0.0.1 at Tue Sep 06 22:24:39 +0800 2011
Served asset /admin/logo.png - 304 Not Modified (0ms)

It seems to have skipped jquery-ui.js!
UPDATE Oct 1, 2011:
I tried it out with the standalone passenger (passenger start) as it seems to give a more descriptive error. This is what happens when I try to load just the jquery.js file and press CTRL-R repeatedly to refresh my browser and load that asset repeatedly.
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2011-10-01 21:40:18 +0800
[ pid=29485 thr=3066030960 file=ext/nginx/HelperAgent.cpp:931 time=2011-10-01 21:40:18.691 ]: Uncaught exception in PassengerServer client thread:
   exception: Cannot read response from backend process: Connection reset by peer (104)
   backtrace:
     in 'void Client::forwardResponse(Passenger::SessionPtr&, Passenger::FileDescriptor&, const Passenger::AnalyticsLogPtr&)' (HelperAgent.cpp:603)
     in 'void Client::handleRequest(Passenger::FileDescriptor&)' (HelperAgent.cpp:857)
     in 'void Client::threadMain()' (HelperAgent.cpp:950)

2011/10/01 21:40:18 [error] 29522#0: *16 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /assets/jquery.js?body=1 HTTP/1.1", upstream: "passenger:unix:/passenger_helper_server:", host: "get.unstilted.dev:3000"
[ pid=29674 thr=78131090 file=utils.rb:176 time=2011-10-01 21:40:18.699 ]: *** Exception PGError in application (server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
) (process 29674, thread #<Thread:0x9505f24>):
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:276:in `exec'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:276:in `block in clear_cache!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:275:in `each_value'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:275:in `clear_cache!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:303:in `disconnect!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:202:in `block in disconnect!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:201:in `each'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:201:in `disconnect!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activesupport-3.1.0/lib/active_support/core_ext/module/synchronization.rb:35:in `block in disconnect_with_synchronization!'
        from /home/ramon/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activesupport-3.1.0/lib/active_support/core_ext/module/synchronization.rb:34:in `disconnect_with_synchronization!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:395:in `block in clear_all_connections!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:395:in `each_value'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:395:in `clear_all_connections!'
        from /home/ramon/.rvm/gems/ruby-1.9.2-p290@unstilted/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_specification.rb:123:in `clear_all_connections!'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/utils.rb:398:in `before_handling_requests'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/rack/application_spawner.rb:204:in `start_request_handler'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/rack/application_spawner.rb:170:in `block in handle_spawn_application'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/utils.rb:479:in `safe_fork'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/rack/application_spawner.rb:165:in `handle_spawn_application'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server.rb:180:in `start'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/rack/application_spawner.rb:128:in `start'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/spawn_manager.rb:253:in `block (2 levels) in spawn_rack_application'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server_collection.rb:132:in `lookup_or_add'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/spawn_manager.rb:246:in `block in spawn_rack_application'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server_collection.rb:82:in `block in synchronize'
        from <internal:prelude>:10:in `synchronize'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server_collection.rb:79:in `synchronize'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/spawn_manager.rb:244:in `spawn_rack_application'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/spawn_manager.rb:137:in `spawn_application'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/spawn_manager.rb:275:in `handle_spawn_application'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
        from /home/ramon/.passenger/standalone/3.0.9-x86-ruby1.9.2-linux-gcc4.5.2-1002/support/helper-scripts/passenger-spawn-server:99:in `<main>'
Served asset /jquery.js - 304 Not Modified (0ms)
cache: [GET /assets/jquery.js?body=1] stale, valid, store
[ pid=29485 thr=3064224624 file=ext/nginx/HelperAgent.cpp:921 time=2011-10-01 21:40:18.734 ]: Couldn't forward the HTTP response back to the HTTP client: It seems the user clicked on the 'Stop' button in his browser.

A: The problem is in the middle of Passenger and Rails 3.1 PostgreSQL adapter.
According to this issue https://github.com/rails/rails/issues/1339
Rails 3.1.1.rc1 should have this issue fixed.
Also stop using PassengerSpawnMethod conservative because it makes Passenger & eventually REE performance optimizations useless - it spawns separate Rails instances - no sharing of common code.

A: I had the same issue. For me I think it was some cached assets or something.
I ran
rake assets:clean

and then requested the page again. This generated real error messages I could use to debug.
It turned out that one of my JS files still had the old require syntax with <>s.
Hope this solves your problem too, I know it was frustrating!

A: The quick fix is to tell passenger to use the 'conservative' spawn method.
in your apache2.conf
PassengerSpawnMethod conservative

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple Screen Size/Density support I am creating an application for Android phones and have been using an emulator to test. I have created a SurfaceView and overwritten the onDraw function to draw bitmaps on the canvas.
I also have some text that I am drawing onto this screen using the canvas.drawText function. I defined the text size as 21 using a paint.setTextSize.
The problem I am facing is that on different emulators with different resolutions and screen sizes the text can range from looking too large to too small. Is there some way to fix this using the AndroidManifest file or modifying the .xml files? Thanks!

A: Did you try this in your android manifest?
<supports-screens android:resizeable=["true" | "false"]
                  android:smallScreens=["true" | "false"]
                  android:normalScreens=["true" | "false"]
                  android:largeScreens=["true" | "false"]
                  android:xlargeScreens=["true" | "false"]
                  android:anyDensity=["true" | "false"] />


text:
Q: Why does asp.net display table name instead of table field im working on a project and im combining 3 tables the tables are already associated in the dbml but my problem is when i use the data list it diaplays my table names not the correct fields this is a college assignment but i have tried everything i know to do.
I've tried to combine them seperatly in sql manager in vs but im just not understanding why it isn't showing the correct thing
 <form id="form1" runat="server">

            <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="assign_6_final.DataClasses1DataContext" EntityTypeName="" Select="new (CustomerID, Name)" TableName="Customers">
            </asp:LinqDataSource>
            <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="LinqDataSource1" DataTextField="Name" DataValueField="CustomerID" OnSelectedIndexChanged="Page_Load">
            </asp:DropDownList>
            <asp:DataList ID="DataList1" runat="server" DataSourceID="LinqDataSource2" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" OnDataBinding="DataList1_SelectedIndexChanged">
                <ItemTemplate>
                    IncidentID:
                    <asp:Label ID="IncidentIDLabel" runat="server" Text='<%# Eval("IncidentID") %>' />

                    DateOpened:
                    <asp:Label ID="DateOpenedLabel" runat="server" Text='<%# Eval("DateOpened") %>' />

                    DateClosed:
                    <asp:Label ID="DateClosedLabel" runat="server" Text='<%# Eval("DateClosed") %>' />

                    Title:
                    <asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />

                    Description:
                    <asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />

                    CustomerID:
                    <asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>' />

                    Technician:
                    <asp:Label ID="TechnicianLabel" runat="server" Text='<%# Eval("Technician") %>' />

                    Product:
                    <asp:Label ID="ProductLabel" runat="server" Text='<%#  Eval("Product") %>' />

                </ItemTemplate>
            </asp:DataList>

        <asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="assign_6_final.DataClasses1DataContext" EntityTypeName="" Select="new (IncidentID, DateOpened, DateClosed, Title, Description, CustomerID, Technician, Product)"  TableName="Incidents" Where="CustomerID = @CustomerID">
            <WhereParameters>
                <asp:ControlParameter ControlID="DropDownList1" Name="CustomerID" PropertyName="SelectedValue" Type="Int32" />
            </WhereParameters>
        </asp:LinqDataSource>

        <asp:EntityDataSource ID="EntityDataSource1" runat="server">
        </asp:EntityDataSource>

    </form>

the outcome i expected was that the last 2 items the product and technician would output correctly but they haven't and im kind of lost my teacher said this is a common problem in asp but ive never seen it

A: Try using the following and so forth:
 <%# DataBinder.Eval(Container.DataItem,"CustomerID") %>


text:
Q: Why does my DataGridview refuse to refresh? I'm updating a row in a table. A subset of the table is shown in a DataGridView. When I update the row, the change is not reflected in the DataGridView. Even though I'm calling
DataGridView.Invalidate() and DataGridView.Refresh() after committing the change, I have to shut down the app, restart, and re-run the query before the change can be seen.
The pertinent code is:
private void buttonUpdate_Click(object sender, EventArgs e)
{
    const int TICKETID_COLUMN = 0;

    String _ticketID = dataGridView1.CurrentRow.Cells[SOME_COLUMN].Value.ToString();

    UpdateRecord(_ticketID, textBoxTicketSource.Text,
                textBoxAboutSomeID.Text, textBoxCategoryID.Text, textBoxContactEmail.Text);
}

private void UpdateRecord(string ATicketID, string ATicketSource, string
    AAboutSomeID, string ACategoryID, string AContactID)
{
    oracleConnection1.Open();
    OracleCommand ocmd = new OracleCommand();
    OracleTransaction ot;
    // Start a local transaction
    ot = oracleConnection1.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
    // Assign transaction object for a pending local transaction
    ocmd.Transaction = ot;
    ocmd.Connection = oracleConnection1;
    try
    {
        ocmd.CommandText = @"UPDATE ABC.CONCERTTICKETS
                                     SET TICKETSOURCE = :p_TICKETSOURCE,
                                     ABOUTSOMEID = :p_ABOUTSOMEID,
                                     CATEGORYID = :p_CATEGORYID,
                                     CONTACTEMAIL = :p_CONTACTEMAIL
                                     WHERE TICKETID = :p_TICKETID";
        ocmd.Parameters.Add("p_TICKETSOURCE", ATicketSource);
        ocmd.Parameters.Add("p_ABOUTSOMEID", Convert.ToInt32(AAboutSOMEID));
        ocmd.Parameters.Add("p_CATEGORYID", Convert.ToInt32(ACategoryID));
        ocmd.Parameters.Add("p_CONTACTEMAIL", AContactID);
        ocmd.Parameters.Add("p_TICKETID", ATicketID);
        ocmd.ExecuteNonQuery();
        ot.Commit();

        Popul8TheGrid();

        dataGridView1.Invalidate();
        dataGridView1.Refresh();
    }
    catch (Exception e)
    {
        ot.Rollback();
        throw;
    }
    finally
    {
        oracleConnection1.Close();
    }
}

private void Popul8TheGrid()
{
    int iFromYear = dateTimePickerFrom.Value.Year;
    int iFromMonth = dateTimePickerFrom.Value.Month;
    int iFromDay = dateTimePickerFrom.Value.Day;
    int iToYear = dateTimePickerTo.Value.Year;
    int iToMonth = dateTimePickerTo.Value.Month;
    int iToDay = dateTimePickerTo.Value.Day;

    oracleCommand1.Parameters.Clear();
    oracleCommand1.Parameters.Add("iStartDate", new DateTime(iFromYear, iFromMonth,
        iFromDay));
    oracleCommand1.Parameters.Add("iEndDate", new DateTime(iToYear, iToMonth,
        iToDay));
    oracleCommand1.Parameters.Add("iCATEGORYID", 114);
    // OracleRef is apparently like OracleDbType.RefCursor;
    OracleRef or = new OracleRef("_or");
    oracleCommand1.Parameters.Add("cref", or);

    oracleConnection1.Open();

    oracleDataAdapter1.SelectCommand = oracleCommand1;
    oracleDataAdapter1.GetFillParameters();
    oracleDataAdapter1.Fill(oracleDataTable1);
    dataGridView1.DataSource = oracleDataTable1;

    oracleConnection1.Close();
}

Updated:
Based on Hall's suggestion (I tried to respond with a Comment, but it seems to be hung):
OK, I've got this now:
        oracleDataAdapter1.SelectCommand = oracleCommand1;
        oracleDataAdapter1.GetFillParameters();
        oracleDataAdapter1.Fill(oracleDataTable1);
        // I don't see a "Clear" method or some such...
        dataGridView1.DataSource = null;
        //dataGridView1.DataSource = oracleDataTable1;

        BindingSource b = new BindingSource();
        b.DataSource = oracleDataTable1;
        dataGridView1.DataSource = b;
        b.ResetBindings(false);

        oracleConnection1.Close();

...and it still works the same - updates, but the DataGridView doesn't know it until I restart the app.

A: The reason Invalidate() and Refresh() don't requery the data source is that they are intended to only work with the graphical side of things - they both invalidate the client area of the control and force a repaint but the problem is that the underlying control thinks that nothing has changed in its data source since it relies upon the data source to tell it when that happens.
What you need is your DataSource to be something which will tell the DataGridView what is going on such as the BindingList<T> or a BindingSource, both of which have the ListChanged event which the DataGridView subscribes to.
I had thought the DataTable also informed the grid when it changed but I was either mistaken or the OracleDataTable is different.
What should fix the problem is introducing a BindingSource and making this the data source for the DataGridView. Then make your OracleDataTable the data source of the binding source. If this doesn't work you can then call the ResetBindings() method on the binding source.
BindingSource b = new BindingSource();
b.DataSource = oracleDataTable1;
dataGridView1.DataSource = b;

A: Try doing:
dataGridView1.DataSource = null;
dataGridView1.DataSource = oracleDataTable1;

A: dataGridView1.DataSource = null;
dataGridView1.DataBind();
dataGridView1.DataSource = oracleDataTable1;
dataGridView1.DataBind();


text:
Q: How do I grab specific posts (by post id) and display the title, featured image, and excerpt? I'm trying to help a friend get his site in order and he wants me to swap out the "services" posts on the front page with 4 specific posts. Thing is, I don't know the right way to do this dynamically. How do I call up the content of just the post id, the featured-image (with the right dimensions) and a short excerpt from the beginning of the post?
Any suggestions would be greatly appreciated; thanks.

A: I have not tested this but based on your question, this should get you on track:
<?php

$id = 4; // The Page or post ID
$page_data = get_post( $id );
$title = $page_data->post_title;
$content = $page_data->post_content;
$excerpt = substr($content, 0, 155);
$featured_image = wp_get_attachment_url( get_post_thumbnail_id($id, 'thumbnail') );

?>

<?php echo $title; ?>

<img src="<?php echo $featured_image; ?>" />

<?php echo $excerpt; ?>

<?php echo $content; ?>


text:
Q: Use of \G boundary matcher in Java I've been learning regex with java.
I wanted to know if it makes sense to use \G while using java's matcher.
I couldn't find any example of \G used with java :(
Doing something like this would not have the same output as using \G?
String a = "Pruebaprueba";
Matcher matcher = Pattern.compile("(\\w)").matcher(a);
while ( matcher.find() ) {
    // Do something with each letter
}

Thanks for reading!

A: Directly from http://java.sun.com/docs/books/tutorial/essential/regex/index.html

To require the match to occur only at
  the end of the previous match, use \G:
Enter your regex: dog
Enter input string to search: dog dog
I found the text "dog" starting at index 0 and ending at index 3.
I found the text "dog" starting at index 4 and ending at index 7.

Enter your regex: \Gdog
Enter input string to search: dog dog
I found the text "dog" starting at index 0 and ending at index 3.

Here the second example finds only one
  match, because the second occurrence
  of "dog" does not start at the end of
  the previous match.

So no, it would not do exactly the same as your example. I do think if you'd change the regex to "(.)" you'd get the same effect as "\G." in this contrived example. But "(\w)" would go on searching after a whitespace while "\G\w" would fail at that point.


text:
Q: Use a variable from __construct() in other methods I defined a new variable in __construct() and I want to use it in another function of this class.
But my variable is empty in the other function!
this is my code:
class testObject{
     function __construct() {
           global $c;
           $data = array("name"=>$c['name'],
                         "family"=>$c['family']);
     }

     function showInfo() {
           global $data;
           print_r($data);
     }

}

A: You can do this way. Instead of declaring $data as global variable declare as public or private or protected variable inside the class depending on your use. Then set the data inside _construct.
Using global inside a class is not a good method. You can use class properties.
class testObject{
    public $data;

    function __construct() {
        global $c;
        $this->data = array("name"=>$c['name'],
                        "family"=>$c['family']);
    }

    function showInfo() {
        print_r($this->data);
    }

}

A: Declare variable $data as global inside the constructor:
 function __construct() {
       global $c;
       global $data;
       $data = array("name"=>$c['name'],
                     "family"=>$c['family']);
 }

Then, it will be visible in other function as well.
Note that extensive usage of global variables is strongly discouraged, consider redesigning your class to use class variables with getters+setters.
A more proper way would be to use
class testObject
{
     private $data;

     function __construct(array $c)
     {
         $this->data = array(
             "name"=>$c['name'],
             "family"=>$c['family']
         );
     }

     function showInfo()
     {
         print_r($this->data);
     }

     // getter: if you need to access data from outside this class
     function getData()
     {
         return $this->data;
     }
}

Also, consider separating data fields into separate class variables, as follows. Then you have a typical, clean data class.
class testObject
{
     private $name;
     private $family;

     function __construct($name, $family)
     {
         $this->name = $name;
         $this->family = $family;
     }

     function showInfo()
     {
         print("name: " . $this->name . ", family: " . $this->family);
     }

     // getters
     function getName()
     {
         return $this->name;
     }

     function getFamily()
     {
         return $this->family;
     }

}

And you can even construct this object with data from you global variable $c until you elimitate it from your code:
new testObject($c['name'], $c['family'])


text:
Q: Postgres Show Time Availability I'd like to ask if there is a built-in query to fetch date time availability in PostgreSQL.
Below are my table:

Room Name
Book Start Date
Book End Date

Room A
09-May-2022 09:00
09-May-2022 11:00

Room A
09-May-2022 12:30
09-May-2022 13:00

Room A
09-May-2022 15:00
09-May-2022 16:00

Room B
09-May-2022 09:00
09-May-2022 11:00

Room B
09-May-2022 11:30
09-May-2022 12:00

Room B
09-May-2022 15:30
09-May-2022 16:00

The requirement is to show the availability of each room from time range 06:00 - 18:00 to be like:

Room Name
Available From
Available To

Room A
09-May-2022 06:00
09-May-2022 09:00

Room A
09-May-2022 11:00
09-May-2022 12:30

Room A
09-May-2022 13:00
09-May-2022 15:00

Room A
09-May-2022 16:00
09-May-2022 18:00

Room B
09-May-2022 06:00
09-May-2022 09:00

Room B
09-May-2022 11:00
09-May-2022 11:30

Room B
09-May-2022 12:00
09-May-2022 15:30

Room B
09-May-2022 16:00
09-May-2022 18:00

I was just thinking if this is possible to do this by using only one query instead of writing additional code in the backend.
Thank you!

A: That can be done easily and conveniently with the multirange types new in PostgreSQL v14. You construct a tsrange from the end points of each row using the tsrange() function, aggregate them into a tsmultirange using the range_agg aggregate function and subtract the result from the range of your choice. Finally, you can use unnest to turn the resulting multirange into a table of ranges.


text:
Q: write a batch file to get a directory of text files/ search for a specific token and insert a line after that I need to read a bunch of text files from a folder. find a specific token such as "Corolla" for each text file and insert a new line after the token.
Suppose the text file is like:

first line
second line
a part of third line, Corolla, third line remaining
INSERT THE NEW LINE HERE
the rest of file.

I am very new to batch files and it is challenging for me.
Thanks
Partial Answer:
I could use the following code, but this code only finds the token if the whole line has that token. I also needs to find the token if it is between some sentences as well (substring)!
@echo off
set SrcFolder=C:\Input
set DstFolder=C:\Output
for %%a in ("%SrcFolder%\*.txt") do (
  (for /f "usebackq delims=" %%h in ("%%a") do (
    echo.%%h
    if "%%h" equ "Corolla" (
      echo THE NEW LINE
    )
  ))>"%DstFolder%\%%~nxa"
)

A: In place of
     "%%h" equ "Corolla" (

(which should yield an error anyway)
put
 echo %%h|findstr "Corolla" >nul&if not errorlevel 1 (

which looks for the literal "Corolla" in each line, setting errorlevel to 0 if found. Do not try if errorlevel 0 because findstr will always set errorlevel to a positive integer and the if errorlevel test tests for errorlevel being n or greater than n


text:
Q: Sum of range in Javascript in function local variable I have range function and output functions they works correct,now I want create sum function for using as callbac function in range function,but when some function executed local variable let us say total or sum initialize 0(zero),how can solve this problem?
    function range(start,end,callback,step) {
        // body...
        step=step || 1;
        for(i=start;i<=end;i=i+step){
            callback(i);
        }
    }
    function output(a) {
        // body...
        console.log(a);
    }
    function sum(m){
       var total=0;
       // some code
}
    range(1,5,output);
    range(1,5,sum);

A:  function range(start,end,callback,step) {
        // body...
        var aggregate;
        step=step || 1;
        for(i=start;i<=end;i=i+step){
            aggregate = callback(i, aggregate);
        }
    }
    function output(a) {
        // body...
        console.log(a);
    }
    function sum(m, aggregate){
       return m + aggregate;
    }
    range(1,5,output);
    range(1,5,sum);

This way you could even do cool stuff like
function conc(m, aggregate) {
    return aggregate + m.toString();
}

range(1,5,conc,2); //prints 135

A: Continuition style code, like you've started it with range(), can get really weird and cumbersome.
And please, please, mind defining your local variables. like i

function range(start,end,callback,step) {
  step=step || 1;
  for(var i=start; i<=end; i=i+step)
    callback(i);
}

function output(...label) {
  return function(...args){
    console.log(...label, ...args);
  }
}

function sum(callback){
  var total = 0;
  return function(value){
    //will log ever intermediate total, because sum() has no way to tell when the sequence is over.
    callback(total += +value || 0);
  }
}

range(1,5,output('range:'));
range(1,5,sum(output('sum:')));

In this case, I'd prefer using a generator instead, although the higher order functions get obsolete.

function *range(start,end,step) {
  step = +step || (end < start? -1: 1);
  for(var value = start, count = (end - start) / step; count-- >= 0; value += step)
    yield value
}

function sum(iterator){
  var total = 0, v;
  for(v of iterator) total += +v || 0;
  return total;
}

console.log("range:", ...range(1,5))
console.log("sum of range:", sum(range(1,5)))

//just to show that this works with your regular array as well
console.log("sum of array:", sum([1,2,3,4,5]));

//and some candy, as requested by Bergi ;)
//I like to stay with the interfaces as close as possible to the native ones
//in this case Array#reduce
var fold = (iterator, callback, start = undefined) => {
  var initialized = start !== undefined,
    acc = start,
    index = 0,
    value;

  for(value of iterator){
    acc = initialized?
      callback(acc, value, index):
      (initialized=true, value);
    ++index;
  }
  if(!initialized){
    throw new TypeError("fold of empty sequence with no initial value");
  }
  return acc;
}
//and the ability to compose utility-functions
fold.map = (callback, start = undefined) => iterator => fold(iterator, callback, start);

console.log(" ");

var add = (a,b) => a + b; //a little helper
console.log('using fold:', fold(range(1,5), add, 0));

//a composed utility-function
var sum2 = fold.map(add, 0);

console.log('sum2:', sum2( range(1,5) ));

A: Clearly a range function should not take a callback but be a generator function in modern JavaScript, however you were asking how to write such a callback.
You've already tagged your questions with closures, and they are indeed the way to go here. By initialising a new total within each call of the outer function, you don't need to worry about how to reset a global counter.
function makeSum() {
    var total=0;
    return function(m) {
        total += m;
        return total; // so that we can access the result
    }
}

var sum = makeSum();
range(1, 5, sum);
output(sum(0));

A: Won't simply calling the callback on the range array suffice if the callback is not undefined? Like this:
> function range(n, callback) {
    const r = [...Array(n).keys()]
    if (callback) {
      return callback(r)
    }
    return r
  }

> function sum(arr) {
    return arr.reduce((a, b) => a + b, 0)
  }

> range(10)

> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

> range(10, sum)

> 45


text:
Q: Obtaining Probability for costs above a certain threshold: probability, cdf, distribution fitting I never sought for help on a forum since I feel that many times the answer for a problem can be found if one reads books and searches for long enough in publications. But I would be very grateful if some of you could provide some help with the following problem:
The issue at hand is the following:
 An organization wishes to analyze repair costs for different machines. There is literally no data available about the parts the organization will have to repair (age, hours of use, …) when the analysis is done so a regression seems impossible to me since the characteristics of the part to repair are not know.
However, the history of reparation costs for such parts is known. So the average costs to repair this kind of part are known as well as the individual expenses for each repair.
For example:
 Name of part:

 The number of past repairs for a part varies from zero to more than 100.000; in the table I randomly put 4. Furthermore it is known which part of the total costs was spent for labor, for material etc.
How could one calculate the probability that the repair costs are higher than a certain value, e. g. for our example: "What is the probability that the repair costs more than 1000"? Would the best approach be to determine a cumulative distribution function based on the empirical data and thus predict the probability? This is not getting me the results I need since the ecdf is giving limited results when only few values from the past are available. In the example above the ecdf would give the same probability for costs lower than 704 as for 906 which does not make sense in my context.
Besides trying to fit a distribution to the value from the past, would be there another appropriate solution for the issue I described? What would be a good number of data points to switch from a parametric to a non-parametric analysis of the cdf? What is the ideal technique to fit a distribution to cost data?
Any help is appreciated,
Rashid


text:
Q: How to prove that (R*, x) is associative? I understand that (R*, x) (under multiplication) is a group, where R* is the real numbers excluding 0.
It has an identity element (1)
Has an inverse (1/x for all x in the group)
but I am unsure how to prove its associativity.


text:
Q: Не получается найти разделитель Есть файл txt, мне нужно читать его как датафрейм по колонкам, но никак не получается разделить на столбцы...
Ссылка на файл https://disk.yandex.ru/d/-e-XklG_SBXxHg
Помогите, пожалуйста..

A: In [1]: import pandas as pd
In [2]: df = pd.read_csv('CH1980BST.txt', sep='\s+', header=None)
In [3]: df
Out[3]:
              0  1    2     3     4   5    6           7           8
0         66666  0   41     1     0   0  6.0  (nameless)  20110729.0
1    1980031718  1   85  1420  1008  12  NaN         NaN         NaN
2    1980031800  1   85  1410  1006  15  NaN         NaN         NaN
3    1980031806  1   85  1400  1005  15  NaN         NaN         NaN
4    1980031812  1   86  1393  1005  15  NaN         NaN         NaN
..          ... ..  ...   ...   ...  ..  ...         ...         ...
982  1980122112  1  118  1269  1004  12  NaN         NaN         NaN
983  1980122118  1  112  1268  1004  12  NaN         NaN         NaN
984  1980122200  1  105  1267  1004  12  NaN         NaN         NaN
985  1980122206  0  100  1265  1004  10  NaN         NaN         NaN
986  1980122212  0   95  1260  1006  10  NaN         NaN         NaN

[987 rows x 9 columns]


text:
Q: Derivation of Newtons second law of motion from the principle of conservation of energy Is newton's second law a consequence of the principle of conservation of energy? How can we arrive at

net force = rate of change of momentum

using only the law of conservation of energy?

A: Start with
$$\frac12 m \dot{x}^2 + V(x) = E$$
with $V$ your potential and $E$ a constant. Now take the time derivative:
$$m \dot{x} \ddot{x} + \frac{dV}{dx}\dot{x} = 0 \implies m\ddot{x} = - \frac{dV}{dx}$$
and there you have it, provided you identify the derivative of the potential with the force.
Do remember, though, that Newton's law is more general, because there exist nonconservative forces. This derivation only works for forces that come from a potential.

A: The connection is provided by the Hamiltonian formalism, if $F = -dV/dx$ is the net force acting on a particle of mass $m$, then the quantity
$$
H(x,p) = \frac{p^2}{2m} + V(x) = E
$$
satisfies the expression
$$
\frac{dp}{dt} = -\frac{\partial H}{\partial x} = -\frac{dV}{dx} = F
$$

A: It is true that Newton's 2nd law with conservative force $$m_i{\bf a}_i ~=~-\frac{\partial V}{\partial {\bf r}_i}, \qquad i~\in~\{1, \ldots, N\},\tag{1}$$
implies conservation of the mechanical energy
$$E=\sum_{i=1}^N \frac{m_i}{2}{\bf v}_i^2 + V({\bf r}_1, \ldots,{\bf r}_N).\tag{2}$$
But the opposite $(2)\Rightarrow (1)$ is not true in general. However, if there is only one particle $N=1$ and only one spatial dimension $d=1$, and the speed is non-zero, then the opposite $(2)\Rightarrow (1)$ is true.

A: Conservation of energy isn't strong enough to reproduce Newton's second law. As a counterexample, consider a situation with no potential energy, $U(\mathbf{x}) = 0$. There is no force, so according to Newton's laws, the particle should move with constant velocity, $\mathbf{x}(t) = \mathbf{v}t$. But conservation of energy tells us that the kinetic energy $\frac{1}{2}m\|\mathbf{v}\|^2$ remains constant, thus only constraining the magnitude of the velocity to be constant. This allows for nonphysical motions like $\mathbf{x}(t) = (\cos t, \sin t)$, whose velocity magnitude is constant but velocity is not.


text:
Q: Spark2 Dataset saveAsTable didn't update HIVE metadata I'm using spark 2.1.0, here's the simplest code:
public static void main(String[] args) {
    SparkSession spark = SparkSession.builder().enableHiveSupport().appName("Spark Test").getOrCreate();
    List<Employee> employees = ImmutableList.of(new Employee("a"), new Employee("b"), new Employee("c"));
    Dataset<Row> df = spark.createDataFrame(employees, Employee.class);
    df.write().saveAsTable("Employee_" + new Random().nextInt(100));
}

I submit it by spark-submit CLI:
spark-submit --class test.spark.Driver --master yarn --deploy-mode cluster

I can see the data is persisted on HDFS: /usr/hive/warehouse/Employee_23, but when I run spark.sql("select * from Employee_23"), got error:
Table or view not found

I can see in hive metastore database, there's no record in TBLS table.
But if I open spark-shell to execute similar code, it works.
Is this happening because of spark-submit? Please help.

A: I found out the reason, my hadoop and spark are deployed in different docker containers, I put hive-site.xml in spark container, so it works when I run spark-shell.
But when depoly mode is "cluster", driver is running on yarn, so this driver can't see hive-site.xml in spark container, the solution is put hive-site.xml into hadoop conf folder (etc/hadoop).


text:
Q: Android NDK: How to get a Context from inside NDK code Writing a C++ shared library to be called by code written by others. I need to make Java library calls that require a Context, and the question is how to get one, starting from scratch.
I don't know much about my caller's environment, but it probably isn't on the UI thread and in any case I can't require the caller to pass in an Activity or an Application.
I do have access to the OnLoad() so I have a JavaVM and from that I can get a JNIEnv and a working class loader. Somewhere out there is an ApplicationContext, but is there a way to find it?
There is this code, but this is not the answer.
android Flurry integration with NDK app
There are also answers based on ActivityManager, but big warnings saying don't do that.
Suggestions?


text:
Q: Notation on wreath product While reading some (relatively old) papers on group-theory I encountered the following notations whose meanings I cannot understand:
If $W= G \wr H$ is the (unrestricted) wreath product of $G$ and $H$, $f$ an element of the basis $G^H$ and $h$ an element of $H$, what do
$f^H$ and $h^W$ mean?
Just for the sake of completeness: the action of $h \in H$ on $f \in G^H$ is denoted by $f^h$

A: If the action is written in exponential notation, then $f^H = \{f^h \mid h\in H\}$. Similarly $W$ acts on itself by conjugation which is also frequently written in exponential notation so that $h^W = \{w^{-1}hw \mid w\in W\}$. It is maybe better not to use $G^H$ for the set of all set maps $H\to G$ in this situation and use something like $Map(H,G)$ instead.


text:
Q: GC Overhead limit exceeded in WSO2 EI 6.6 In WSO2 EI 6.6, proxy stopped working abruptly. upon analyzing observed an error in the wso2 carbon log "GC Overhead limit exceeded", after this error nothing happening in the EI.
Proxy logic is to get the data from Sql server table and form an xml and send it to an external API. Proxy runs every 5 mins interval and in every interval maximum of 5 records will be pushed to an API.
After restarting the wso2 carbon services, proxy are started working. currently we are restarting the services every 3 days to avoid this issue.
Need to know how to identify the potential issue and resolve this.

A: This mean the JVM has run out of allocated memory. There can be many reasons for this. For example, if you haven't allocated enough memory to the JVM you can easily run out of memory. If that's not the case you need to analyze a memory dump and see what's occupying the memory causing it to fill up.
Generally, when you see the mentioned error the JVM automatically creates a heap dump(heap-dump.hprof) in the <EI_HOME>/repository/logs directory. You can try analyzing the dump to find the root cause. If the server doesn't generate a memory dump, manually take a memory dump when it's occupied than the expected level and analyze it.


text:
Q: Как посмотреть версию Linux в терминале? Как посмотреть версию Linux в терминале?

A: Например следующим образом (может не работать в старых версиях):
lsb_release -a

A: Можно попробовать выполнить такую команду:
cat /etc/*-release

A: $ python -mplatform
Linux-4.2.0-36-generic-x86_64-with-Ubuntu-16.04-xenial

A: версию программы linux, которая запущена в данный момент, можно посмотреть, например, командой (приведён и пример вывода):
$ uname -r
3.13.0-57-generic

или даже:
$ cat /proc/version
Linux version 3.13.0-57-generic (buildd@brownie) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #95-Ubuntu SMP Fri Jun 19 09:28:15 UTC 2015

версию же дистрибутива можно посмотреть, например, командой (приведён и пример вывода):
$ lsb_release -r
Release:    14.04

больше информации — с опцией -a (приведён и пример вывода):
$ lsb_release -a
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.4 LTS
Release:    14.04
Codename:   trusty

это если установлена программа lsb_release. к сожалению, до сих пор не во всех дистрибутивах она устанавливается по умолчанию. тогда стоит воспользоваться командой (приведён и пример вывода):
$ cat /etc/*release*
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.4 LTS"
NAME="Ubuntu"
VERSION="14.04.4 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.4 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

A: Узнать, 32 или 64 bit:
uname -m

$ uname -m
x86_64

Еще варианты узнать версию linux:
cat /etc/issue

$ cat /etc/issue
Ubuntu 14.04.4 LTS \n \l

lsb_release -a

$ lsb_release -a
No LSB modules are available.
Distributor ID:   Ubuntu
Description:  Ubuntu 14.04.4 LTS
Release:  14.04
Codename: trusty

Посмотреть версию ядра linux:
uname -r

$ uname -r
3.13.0-87-generic

A: Есть ещё консольная утилита screenFetch:


text:
Q: least square solution of overdetermined system with additional unknown I was hoping somebody could tell me the best way to solve the following overdetermined system for the scalars $x_{1}$,$x_{2}$ and $x_{3}$, where the C $3 \times 1$ vectors are unknown, $A_{i}$ is a $3 \times 3$ matrix and $b_{i}$ is a $3 \times 1$ vector.
$ \left[ \begin{array}{cc}
A_{1} \\
A_{2} \\
A_{3} \\
\end{array}\right]
 \left[ \begin{array}{cc}
x_{1} \\
x_{2} \\
x_{3} \\
\end{array}\right]=
 \left[ \begin{array}{cc}
C \\
C \\
C \\
\end{array}\right]-
 \left[ \begin{array}{cc}
b_{1} \\
b_{2} \\
b_{3} \\
\end{array}\right]
$
in a longer format this is written as
$ \left[ \begin{array}{ccccc}
A_{1 \ 11} & \ldots &A_{1 \ 13} \\
\vdots & \ldots & \vdots \\
A_{1 \ 31} & \ldots &A_{1 \ 33} \\
A_{2 \ 11} & \ldots &A_{2 \ 13} \\
\vdots & \ldots & \vdots \\
A_{2 \ 31} & \ldots &A_{2 \ 33} \\
A_{3 \ 11} & \ldots &A_{3 \ 13} \\
\vdots & \ldots & \vdots \\
A_{3 \ 31} & \ldots &A_{3 \ 33} \\
\end{array}\right]
 \left[ \begin{array}{cc}
x_{1} \\
x_{2} \\
x_{3} \\
\end{array}\right]=
 \left[ \begin{array}{cc}
C_{1} \\
C_{2} \\
C_{3} \\
C_{1}\\
C_{2} \\
C_{3} \\
C_{1} \\
C_{2} \\
C_{3} \\
\end{array}\right]-
 \left[ \begin{array}{cc}
b_{11} \\
b_{12} \\
b_{13} \\
b_{21} \\
b_{22} \\
b_{23} \\
b_{31} \\
b_{32} \\
b_{33} \\
\end{array}\right]
$
I have attempted to solve the equation by eliminating the constants so I end up with an equation as follows:
$ \left[ \begin{array}{cc}
A_{1} - A_{3}\\
A_{2}-A_{3} \\
\end{array}\right]
 \left[ \begin{array}{cc}
x_{1} \\
x_{2} \\
x_{3} \\
\end{array}\right]=
 \left[ \begin{array}{cc}
b_{3}- b_{1} \\
b_{3}- b_{2} \\
\end{array}\right]
$
from which I find the least squares solution for $x_{1}$,$x_{2}$ and $x_{3}$. Can anybody tell me if this is the correct way to the solution which minimizes the error?
Kind regards


text:
Q: How to correctly name a uni assignment? Finishing my first in class assignment in an English uni, I struggle with the name (especially  with "the" and "of" words). I developed a website X and the document should describe the whole process.
I was thinking about:
The X site solution development report

X site development report

The development report of the X site

Which would be the best or what would you write? THanks

A: The report of X site development


text:
Q: Batch won't recognize an existing variable? I'm working on a little experiment, where I have a batch file output the contents of the environmental variables %DATE% and %TIME% into a text file. A visual basic script will then read the files, and pick out a specific part of the file text based off of a pattern, and output THAT into a separate text file. The batch file will then read THAT file and import it as a variable. Here's the code:
:load
@echo off
if exist date.txt DEL date.txt
if exist time.txt DEL time.txt
if exist dateextracted.txt DEL dateextracted.txt
title Testing
color 0a
goto start

:start
echo %DATE%> date.txt
echo %time%> time.txt
echo. > dateextracted.txt
START date.vbs
goto wait1

:wait1
if exist dateextracted.txt goto wait2
goto wait1

:wait2
for /f "Delims=" %%a in (dateextracted.txt) do (
set dateextracted=%%a
)
echo %dateextracted%
pause
exit

Now the problem is that the batch file just says "ECHO is off." This means that the batch file doesn't see anything in the variable %dateextracted%, even though the variable DOES exist, and there IS stuff in it. For example, as of posting this thread, the date is 12/27/2018. So, the variable should be filled with 12/27/2018. If I open up the text file that the visual basic script outputted, it says 12/27/2018. So there's no problem with the visual basic script, it's just the batch file. I don't know if I'm importing the contents of the text file incorrectly, or if it's just a syntax error.

A: This may seem surprising, but your batch script doesn't recognize the variable %dateextracted% because it actually does not exist.
echo. > dateextracted.txt already creates the file dateextracted.txt, so your :wait1..goto wait1 loop immediately skips to :wait2. However, since START date.vbs is running the VBScript asynchronously in the background that script most likely has not finished yet when your for loop is reading dateextracted.txt. In that situation the loop is reading an empty file and thus doesn't define the variable %dateextracted%. This in turn causes the subsequent echo command to display the echo status, because the command is invoked without an argument due to the undefined variable.
You can fix the issue by running date.vbs synchronously by using the cscript.exe interpreter instead of the default wscript.exe. Change this:
echo. > dateextracted.txt
START date.vbs
goto wait1

:wait1
if exist dateextracted.txt goto wait2
goto wait1

:wait2
for /f "Delims=" %%a in (dateextracted.txt) do (
set dateextracted=%%a
)

into this:
echo. > dateextracted.txt
cscript.exe //NoLogo date.vbs

for /f "Delims=" %%a in (dateextracted.txt) do (
    set "dateextracted=%%a"
)


text:
Q: NodeJS request works local, not on VPS In a NodeJS project, I send a request to get the html of a webpage. This works fine when I run the code on my MacBook, but the request times out when I run the same code on my VPS. I don't know a lot about servers, so I have no idea where to look.
This is the request I send:
request({
  uri: 'http://torrentz.eu/search?f=' + encodeURIComponent(data.query)
, headers: {
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2',
  }
}, console.dir);

Error:
{ [Error: connect ETIMEDOUT] code: 'ETIMEDOUT', errno: 'ETIMEDOUT', syscall: 'connect' }

Edit:
Other requests (like the one below) work fine.
request({
    uri: 'http://api.trakt.tv/account/test/' + config.trakt.apiKey
  , method: 'post'
  , form: {
        username: data.username
      , password: data.password
    }
}, function( err, resp, data ) {
  if( data.status === 'success' ) {
    User.set({
        trakt_username: data.username
      , trakt_password: data.password
    }).then(defer.resolve).catch(defer.reject);
  }
  else {
    defer.reject( data.error );
  }
});


text:
Q: Issue in splitting the routes file in play framework 2.2.6 java I want to Split my play routes files into two different file.
I have conf/routes and conf/admin.routes as two routes file in conf folder. In routes file I have specified   -> /admin  admin.Routes but Play is unable to resolve Routes.
Is there any other way to include other routes file in build.at or any other workaround which works for Play(Java).


text:
Q: Is there any way to handle websocket onmessage handler just like done method handlers attached to XHR deferred objects in jQuery I'm currently doing this hack to handle the websocket's onmessage.
$scope.wsCon.onMessage = function(result) {
    $scope.wsCon.trigger(result.handler, result.data);
};

Problem here is that, onmessage is handling all the incoming requests through websocket.
But I need something like this:
$scope.wsCon.
    .send(data)
    .done(data, function (result) {
        // Deal with the result here
    })
    .fail(data, function() {
        // Show the error message
    })
    .complete(data, function() {
        // Do this always
    });

I know this is not achievable in websocket on single connection. But still, is there any way to produce effect something like the way jQuery does?

A: WebSockets are not request/response based, so since there is no response required when you send a message, what do you expect to happen to finish that promise? the socket flushing the buffer? :) If the browser fails to send the message because the socket is dead, you will get an "onerror" message.
If you need confirmation of the message, or awaiting a response, you need to implement it yourself.
Please take a look at this answer : AngularJS and WebSockets beyond About this $connection service declared in this WebSocket based AngularJS application
Basically it is an example about creating a WebSocket service in AngularJS that can be used to request/response and publish/subscribe.
Basically you can listen for messages:
   $connection.listen(function (msg) { return msg.type == "CreatedTerminalEvent"; },
        function (msg) {
            addTerminal(msg);
            $scope.$$phase || $scope.$apply();
   });

Listen once (great for request/response):
$connection.listenOnce(function (data) {
    return data.correlationId && data.correlationId == crrId;
}).then(function (data) {
    $rootScope.addAlert({ msg: "Console " + data.terminalType + " created", type: "success" });
});

And send messages:
$connection.send({
    type: "TerminalInputRequest",
    input: cmd,
    terminalId: $scope.terminalId,
    correlationId: $connection.nextCorrelationId()
});


text:
Q: List of highest scores- how to differentiate your score in the list I am working on simple game.
When user view scores of all users I want his score to be in different color. How can I do it?
So far I have just list of all scores from highest score to lowest
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name ORDER BY score DESC;";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
?>

<HTML TABLE>

<?php
}

mysql_close();
?>

A: Test whether the player in the row is the current player, and set a class. Then use CSS to assign a color to that class.
while ($row = mysql_fetch_assoc($result)) {
    $class = $row['player'] == $current_player ? 'class="highlight"' : '';
    echo "<tr $class>";
    // code for rest of table row
    echo "</tr>";
}


text:
Q: weighted central tendency in python I have a list, like the one below:
    [1,1,1,1,1,1,1,1,1,10]

I want to calculate the list average, however, arithmetic mean would not be an answer. I want my result to be skewed toward 10 because it is assumed to have much more weight. Geometric mean is not also an option. I wanted to know if there are other measures of central tendency that can be calculated in python using predefined functions. I am preparing my data for a neural network and I shall use various weights to see which one performs better. That is why I am looking for predefined functions so I can change their parameters to create multiple databases for my Neural Network.
Thanks in advance
P.s. The priority is to find the measure. Applying it in python comes next.

A: From my deep learning practice I don't quite agree that a higher weight should be desired.
Yet regarding your particular question, you can solve it
with straightforward power. High values become much larger, lower values much lower. After computing mean of powered values, compute a respective root, to return to the old scale.
And make sure you use an odd value for power, so that negative numbers retain sign.
import numpy as np
x = np.array([1,1,1,1,1,1,1,1,1,10])
power = 15
powered_mean = np.mean(np.power(x, power))
central_tendency = np.power(powered_mean, 1/power) # root

8.576958985908947


text:
Q: Analogy: "as if" vs. "as though" This is something that confuses me from time to time. When making an analogy in literature, is it better to use the phrase "as if" or "as though", or is it completely a style thing?
E.g.

She looked frazzled, as if she had just gotten off of a roller coaster.

or

She looked frazzled, as though she had just gotten off of a roller coaster.

A: I thought about this for a bit (maybe too long) and started feeling that "as though" seems to work better when addressing a condition. "It looked as though it might rain."
And "as if" works better when concrete situations/options/determinations can be considered.  "It looked as if the game might be called off due to rain."
The difference is subtle, but it somehow gets clearer when you consider the effect of using "even if" or "even though" on similar phrases.
As though it really matters.  As if I really care.

A: Garner in Modern American Usage (p67) has an entry on this. First he claims:

Attempts to distinguish between these idioms have proved futile.
  Euphony should govern the choice of phrase.

He then goes on to state:

One plausible distinction is that as if often suggests the more
  hypothetical proposition when cast in the subjunctive <as if he were
  a god>. ... By contrast, as though suggests a more plausible
  suggestion <it looks as though it might rain>.

However, I see no distinction in suggestion or meaning between the OP's two sentences.

A: 'As if' is often used when talking about an imaginary situation that has no likelihood or probability of happening, e.g., 'He acts as if he were Superman', or '...as if he were God', or 'She walks as if she were floating.'
'As though,' on the other hand, is used when talking about a situation that may not be true but is possible or likely to happen, e.g., 'He looks as though he hadn't slept for days', or 'She sings as though she were a professional singer.'

A: It must have a lot to do with one's background, for I find myself always writing "as though," whereas my writer friend always writes "as if." Moreover, I see that Anita Brookner, of Hotel du Lac fame, a UK citizen, always writes "as if."

A: This is just my opinion, but I always recommend "as if" because it means what the words say -- the situation being described is as it would be if the condition were true.
"As though" is idiomatic, or perhaps archaic -- its meaning has little to do with the word "though".
It surprises me that this distinction is never mentioned in any explanation that I have seen of the two phrases.


text:
Q: Hello, I want to unpack a list of comments (ICollection) and show comments using data binding in c#. How can I access every comment of the list? <StackPanel Grid.Column="1">
        <ListView x:Name="lstvActiveIssues" ItemClick="lstvActiveIssues_ItemClick" IsItemClickEnabled="True" Height="500">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="models:Issue">
                    <StackPanel>

                        <StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="Title:"   Width="130" FontSize="10"/>
                                <TextBlock Text="{x:Bind Title}" Margin="10 10 0 0" />
                            </StackPanel>
                        </StackPanel>

                        <StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="Customer Name:"  Width="130" />
                                <TextBlock Text="{x:Bind Customer.FirstName}" Margin="10 5 0 0"  />
                                <TextBlock Text="{x:Bind Customer.LastName}" Margin="5 5 0 0"  />
                            </StackPanel>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <StackPanel DataContext="{Binding SelectedItem, ElementName=lstvActiveIssues}" >
            <TextBlock Text="Details of the selected Issue" />

            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Title:" Width="130" />
                <TextBlock Text="{Binding Title}" />
            </StackPanel>

            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Customer Name:" Width="130" />
                <TextBlock Text="{Binding Customer.FirstName}" />
            </StackPanel>

            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Comment:" Width="130" />
                <TextBlock Text="{Binding Comments}" />
            </StackPanel>
        </StackPanel>
    </StackPanel>

Issue class is here

public class Issue
{
    public Issue()
    {

    }

    public Issue(long id, long customerId, string title, string description, string status, DateTime created)
    {
        Id = id;
        CustomerId = customerId;
        Title = title;
        Description = description;
        Status = status;
        Created = created;
    }

    public long Id { get; set; }
    public long CustomerId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Status { get; set; }
    public DateTime Created { get; set; }

    public virtual Customer Customer { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

textblock show just System.Collection.Generic.List'1[DataAccessLibrary.Models.Comment]
How can I show every comment in the textblock.I want to unpack a list of comments (ICollection) and show comments using data binding in c#. How can I access every comment of the list?

A: I think your issue is that you are binding the ICollection Object directly to the Text Property of your Text Block.
If you just want to show the values in the text block directly, you could use a Value Converter to convert your list of comments into a string which would display in your text block.
However, based on your question I don't think this is your desired result.
My advice would be to use another listview to show the comments rather than a text block.
So something like this might be what you're looking for:
<ListView x:Name="issueCommentsList" ItemSource="{Binding SelectedItem.Comments, ElementName=lstvActiveIssues}" IsItemClickEnabled="True" Height="500">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="models:Comment">
                <StackPanel>
                    <TextBlock Text="{Binding Text}" FontSize="10"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

As you can see the ItemSource of the listview would have a data binding to the Selected Items comments. This would then allow you to create a custom UI for your comments.
I have just added a simple text block for the comment UI so you can change that accordingly
Hope this helps, Happy Coding :)


text:
Q: Angular's JQ Lite functions (triggerHandler method) not working in Internet Explorer 11 I have an Angular.js app that uses some calendar inputs to select date ranges. The calendar inputs use jQuery UI datepicker. I'm quite aware of the dangers that can arise from using jQuery modules in an Angular app and kindly ask that we avoid opening that discussion in this thread.
Regarding, Angular and jQuery UI compatibility I have several functions and extensions which make the datepicker work nicely in the Angular app.

*

*A custom datepicker directive

*an angular.element(el).triggerHandler('input') method to update the controller scope (otherwise only the UI changes - even though the scope is watched it is not digested if triggered from jQuery UI events)

The problem I'm having is that the triggerHandler() is updating the controller scope in every browser except IE 11. I can confirm that it works in IE Edge, Safari, Chrome, FireFox and Opera.
Here's my directive:
angular.module('trip.directives',[])
  .directive('ccDatePicker', function ($compile) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            $(element[0]).datepicker().on("change", function (e) {
                var date = element.val();
                scope.$apply( function () {
                    ngModelCtrl.$setViewValue(date);
                });
            });
        }
    };
})

Here's my directive being called in html:
<p class="field date black">
    <input type="text" id="newtrip-date-from" class="form-control date datepicker date-from" name="date-from" id="date-from" placeholder="dd.mm.yyyy" ng-model="startModal.dateFrom" cc-date-picker />
    <input type="text" id="newtrip-date-to" class="form-control date datepicker date-to" name="date-to" id="date-to" placeholder="dd.mm.yyyy" ng-model="startModal.dateTo" cc-date-picker />
</p>

And here's my javascript datepicker callback that uses angular.element(el).triggerHandler('input') to update my controller scope. This is the part that works in every browswer except IE 11:
    $('.datepicker').datepicker({
        minDate: 0,
        dateFormat: 'dd.mm.yy',
        onSelect: function(date) {
            var target = null;
            switch ( $(this).hasClass('date-from') ) {
                case true:
                    target = $(this).attr('id').split('from');
                    target = target[0] + "to";
                    $('#' + target).datepicker('option', 'minDate', date);
                    angular.element($(this)).triggerHandler('input');
                    break;
                case false:
                    target = $(this).attr('id').split('to');
                    target = target[0] + "from";
                    $('#' + target).datepicker('option', 'maxDate', date);
                    angular.element($(this)).triggerHandler('input');
                    break;
            }
        }
    });

If anyone knows a workaround for updating the scope for this event in IE 11 it would be really big help. Thanks!

A: So I was able to fix this issue. In case anyone stumbles upon this thread, here's how I solved the problem:
As I'd expected, the problem was with the datepicker not sending a change event. To fix that, I manually updated model by getting the element's scope using angular.element() and running an apply function:
/* this first part checks for IE 11 */
if ( !(window.ActiveXObject) && "ActiveXObject" in window === true) {
    /* now we assign the element's angular scope to a variable */
    var $scope = angular.element($('input[name="date-from"]')).scope();
    /* and use that scope var to run an apply cycle */
    $scope.$apply(function () {
        /* here we set the value on the target model
           using jQuery */
        $scope.startModal.dateFrom = $('input[name="date-from"]').val();
    });
}

Finally, the full integration into the datepicker's on select callback was like this:
    $('.datepicker').datepicker({
        minDate: 0,
        dateFormat: 'dd.mm.yy',
        onSelect: function(date) {
            var target = null;
            switch ( $(this).hasClass('date-from') ) {
                case true:
                    target = $(this).attr('id').split('from');
                    target = target[0] + "to";
                    $('#' + target).datepicker('option', 'minDate', date);
                    if ( !(window.ActiveXObject) && "ActiveXObject" in window === true) {  // <= targets IE 11
                        var $scope = angular.element($('input[name="date-from"]')).scope(); // assign the elements scope to a var
                        $scope.$apply(function () {
                            $scope.startModal.dateFrom = $('input[name="date-from"]').val(); // sets the correct model value
                        });
                    } else {
                        angular.element($(this)).triggerHandler('input');
                    }
                    break;
                case false:
                    target = $(this).attr('id').split('to');
                    target = target[0] + "from";
                    $('#' + target).datepicker('option', 'maxDate', date);
                    if ( !(window.ActiveXObject) && "ActiveXObject" in window === true) {
                        var $scope = angular.element($('input[name="date-to"]')).scope();
                        $scope.$apply(function () {
                            $scope.startModal.dateTo = $('input[name="date-to"]').val();
                        });
                    } else {
                        angular.element($(this)).triggerHandler('input');
                    }
                    break;
            }
        }
    });


text:
Q: getTestCaseList only for enabled test cases I would like to have a test case list containing only enabled test cases in the tear down script. I tried below code. however it return all the test cases including the disabled ones.
project.getTestSuiteList().each {
    it.getTestCaseList().each { tcList ->
        tcList.each {
log.info it.properties
}

A: project.getTestSuiteList().each {
    it.getTestCaseList().each { tcList ->
        tcList.each {
if(!it.isDisabled()){
/*do your stuff*/
}

}

A: your testCase, same as at testStep level, has a 'disabled' property
        tcList.each{
        log.info it.name
        log.info it.disabled
        ...
    }

Then you can set condition on it ...


text:
Q: Would you accept this proof for $(A^c)^c = A$? In my exercises I had the following question:
Prove that $(A^c)^c = A$.
My solution:
Let $A$ be a set where $A\subset X$. $A = \{x \in X, x \in A\}$ by definition.
$A^c = \{x \in X, x \notin A\}$
Let $P(x)$ be the proposition that $x \in X$ and $Q(x)$ be the proposition that $x \in A$. Therefore:
$A = P(x) \wedge  Q(x)$
$A^c = P(x) \wedge ¬Q(x)$
$(A^c)^c = P(x) \wedge ¬(P(x) \wedge ¬Q(x)) \iff P(x) \wedge (¬P(x) \vee Q(x)) \iff (P(x) \wedge ¬P(x)) \vee (P(x) \wedge Q(x)) \iff False \vee (P(x) \wedge Q(x)) \iff P(x) \wedge Q(x) = A$
Hence, $(A^c)^c = A$.
Is this a solid enough proof, or should I do a different approach?
Note: My actual written work contains references to De Morgan's Laws, and other propositions in the course that allow me to do the logical equivalences.

A: Why not directly by the definition? It is extremely simple:
$$x\in A\iff x\notin A^c\iff x\in(A^c)^c$$


text:
Q: Alpha conversion on a Haskell expression Given a Haskell expression, I'd like to perform alpha conversion, ie. rename some of the non free variables.
I've started implementing my own function for this, which works on a haskell-src-exts Exp tree, however it turns out to be surprisingly nontrivial, so I can't help wondering - is there an established easy-to-use library solution for this kind of source conversion? Ideally, it should integrate with haskell-src-exts.

A: This is one of the problems where the "Scrap Your Boilerplate" style generic libraries shine!
The one I'm most familiar with is the uniplate package, but I don't actually have it installed at the moment, so I'll use the (very similar) functionality found in the lens package. The idea here is that it uses Data.Data.Data (which is the best qualified name ever) and related classes to perform generic operations in a polymorphic way.
Here's the simplest possible example:
alphaConvert :: Module -> Module
alphaConvert = template %~ changeName

changeName :: Name -> Name
changeName (Ident n) = Ident $ n ++ "_conv"
changeName n = n

The (%~) operator is from lens and just means to to apply the function changeName to everything selected by the generic traversal template. So what this does is find every alphanumeric identifier and append _conv to it. Running this program on its own source produces this:
module AlphaConv where
import Language.Haskell.Exts
import Control.Lens
import Control.Lens.Plated
import Data.Data.Lens

instance Plated_conv Module_conv
main_conv
  = do ParseOk_conv md_conv <- parseFile_conv "AlphaConv.hs"
       putStrLn_conv $ prettyPrint_conv md_conv
       let md'_conv = alphaConvert_conv md_conv
       putStrLn_conv $ prettyPrint_conv md'_conv

alphaConvert_conv :: Module_conv -> Module_conv
alphaConvert_conv = template_conv %~ changeName_conv

changeName_conv :: Name_conv -> Name_conv
changeName_conv (Ident_conv n_conv)
  = Ident_conv $ n_conv ++ "_conv"
changeName_conv n_conv = n_conv

Not terribly useful since it doesn't distinguish between identifiers bound locally and those defined in an outside scope (such as being imported), but it demonstrates the basic idea.
lens may seem a bit intimidating (it has a lot more functionality than just this); you may find uniplate or another library more approachable.
The way you'd approach your actual problem would be a multi-part transformation that first selects the subexpressions you want to alpha-convert inside of, then uses a transformation on those to modify the names you want changed.


text:
Q: How to enter multiple checkbox entries with PHP into database single column I have an absolute beginner question here. I'm having trouble getting multiple checkbox entries into a single column in my database. I've tried a few different things with my php but can't seem to get anything to work properly. I've tried using serialize as well as looked into using implode/explode. Sorry I'm basically asking to be spoon-fed because I know its a simple fix, I just haven't been able to get anything to work yet. Any assistance would be appreciated. THANKS!!! Also The three checkboxes I have are system, comm, and other and I do have the brackets for my 3 inputs even though the php isn't setup to handle them yet, so for now my DB is still showing Array for these inputs.  Here is my php
    <?php
$con = mysql_connect("localhost","Andrew","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("mydb", $con);

$sql="INSERT INTO persons (firstname, lastname, modelid, system, department, comm,  other, shift, comments)
VALUES
  ('$_POST[firstname]','$_POST[lastname]','$_POST[modelid]','$_POST[system]','$_POST[departme    nt]','$_POST[comm]','$_POST[other]','$_POST[shift]','$_POST[comments]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);
?>

A: To detail what the comments above said:
$to_insert_in_db = $_POST['system'].','.$_POST['comm'].','.$_POST['other'];

You insert this in a single column in your db, and when you retrieve it you just do:
$retrieved_values = explode(',', $column_value_from_db);

However, if the values of system, comm and so on are a bit more complex(such as strings) i suggest you use json_encode to add the values to the database and json_decode to get them from the database.
$values = array('system' => $_POST['system'], 'comm' => $_POST['comm'], 'other' => $_POST['other']);
$column_to_insert = json_encode($values);
$values = json_decode($column_value_from_the_database);

A: Checkbox is having a unique problem i.e. when it is checked there is some value form send with the data, but when it is unchecked there is no variable and it will return undefined variable, so every time you use each checkbox variable do it like this
$check1Val = 0;
if(isset($_POST["check1"]){
  $check1Val = 1;
  //or $check1Val = $_POST["check1"];
}

In last you concate each variable and send it to single coloum
$allCheckValues = $check1Val.",".$check2Val;

Let me know if you still have any confusion about checkboxes or other

A: Try this
$value ="";
if(isset($checkbox1)){
$value = $value."1";
$flag =1;
}
if(isset($checkbox2)&&$flag==1){
$value = $value.",1";
$flag =1;
}
else{
$value = $value."0,1";
$flag =1;
}
 if(isset($checkbox3)&&$flag==1){
$value = $value.",1";
$flag =1;
}
else{
$value = $value."0,0,1";
$flag =1;
}

You can use any value for 0 or 1 depending on your application

A: Storing the checkboxes as a comma separated list in a single field
This is a clean way of doing it that won't produce undefined index/variable notices (keep in mind if a checkbox is unchecked then it won't be sent as a post value), and allows you to add more checkboxes just by adding to the $names array.
<?php

$names = array('system', 'comm', 'other');

$checkboxes = array();

foreach($names as $name)
{
    $value = 0;

    if(isset($_POST['checkboxes']) && is_array($_POST['checkboxes']) && in_array($name, $_POST['checkboxes']))
    {
        $value = 1;
    }

    $checkboxes[] = $value;
}

$checkboxString = implode(',', $checkboxes);

?>

Now you can use $checkboxString in your query. $checkboxString will be a comma separated list of 0s or 1s to indicate the checkbox values. For example: system=off, comm=on, other=on: 0,1,1.
Your HTML needs to look like (using a checkbox array):
<input type="checkbox" name="checkboxes[]" value="system" /> System

<input type="checkbox" name="checkboxes[]" value="comm" /> comm

<input type="checkbox" name="checkboxes[]" value="other" /> other
                                       ^^ square brackets for an array

SQL Injection
You need to research this because your code is vulnerable. Run the user supplied values through mysql_real_escape_string():
$firstname = mysql_real_escape_string($_POST['firstname']);

Query:
VALUES
  ('$firstname', ..............

MySQL Library
Your code is using the old mysql_* library. This is being phased out so you should choose another library for all new code, such as PDO or MySQLi.

A: So here is what I have used to get my multiple entries into a single cell in my db
('$_POST[firstname]','$_POST[lastname]','$_POST[modelid]','". implode(",", $_POST['system']) ."','$_POST[department]','". implode(",", $_POST['comm']) ."','". implode(",", $_POST['other']) ."','$_POST[shift]','$_POST[comments]')";
So maybe this will serve someone in the future who is trying to accomplish this same simple goal, now my only problem is that the entries in the db are being cut off, I believe the solution is to serialize my arrays. THANKS AGAIN for all of your assistance!!


text:
Q: drupal 6 and jquery 1.4/1.5 is there a way in drupal 6 to use in non admin pages jquery 1.5 / 1.4 without breaking the core functionality on non-admin pages??

A: Yes.
Install and enable http://drupal.org/project/jquery_update
Download the version of jQuery you want, and place it alongside the ones included in the module.
Edit the module
function jquery_update_jquery_path() {
    $curr_uri = request_uri();
     if (strpos($curr_uri,'admin')>0 || strpos($curr_uri,'edit')>0 || strpos($curr_uri,'add')>0){
        $jquery_file = array('none' => 'jquery.js', 'min' => 'jquery.min.js');
        return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')]
;
    }
    else {
        $jquery_file = array('none' => 'jquery-1.5.2.js', 'min' => 'jquery-1.5.2.min.js');
        return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')]
;
    }
}

Use the filename of the version you downloaded.
There is an issue logged about the edit above, but I have the reference at work.  I will update the answer tomorrow with the link.
I have this running live on a bunch of sites w/o a problem.
Addendum:
This is the link to the thread / patch about the issue: http://drupal.org/node/775924#comment-2987316


text:
Q: How to disable 'devTools' in Capacitor + Electron app To disable devTools we need to access webPreferences through BrowserWindow, However BrowserWindow is not available directly from the Electron app. So how do we access webPreferences to diable the devTools?
Without Capcitor Below code snippet works perfectly fine
const browserWindow = new BrowserWindow({
  .....
webPreferences: { devTools: false}
})

A: let config: CapacitorElectronConfig = {
    mainWindow: {
    windowOptions: {
    webPreferences: {
     devTools: false
     }
    }
  }
 }

While creating Capacitor Electron app, we just need to pass on the configuration.
const myCapacitorApp = createCapacitorElectronApp(config);


text:
Q: How can I inference with multiple input network on TensorRT? I would like to test GQ-CNN which is network in Dex-Net on tensorRT.
I successfully converted tflite file to uff file but when I tried to inference with that network, there is an error I couldn't figure out.
[TensorRT] ERROR: Parameter check failed at: ../builder/Network.cpp::addLRN::149, condition: lrnWindow & 0x1
python3: uff/orders.cpp:330: void UffParser::addTranspose(ParserLayer&, std::vector<int>): Assertion `outputs.size() == 1' failed.

The error is appeared when building model.
I tried to find clue from google but there are no codes and no references.
There's only different thing compare with example code that works well.
(I wrote captions which codes I added. If I remove that codes and replace model file to single input network, it works well.)
I registered input twice like below code because GQ-CNN has multiple input.
So I guess that registering multiple input using uffparser could be the main reason of that error.
class ModelData(object):
    MODEL_FILE = "./gqcnn.uff"
    INPUT_NAME_1 = "Placeholder"
    INPUT_SHAPE_1 = (1, 32, 32)
    INPUT_NAME_2 = "Placeholder_1"
    INPUT_SHAPE_2 = (2,)
    OUTPUT_NAME = "softmax/Softmax"

def build_engine(model_file):
    # For more information on TRT basics, refer to the introductory samples.
    with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network, trt.UffParser() as parser:
        builder.max_workspace_size = common.GiB(1)
        builder.fp16_mode = True
        #builder.int8_mode = True

        # Parse the Uff Network
        parser.register_input(ModelData.INPUT_NAME_1, ModelData.INPUT_SHAPE_1)
        parser.register_input(ModelData.INPUT_NAME_2, ModelData.INPUT_SHAPE_2) # added code
        parser.register_output(ModelData.OUTPUT_NAME)
        parser.parse(model_file, network)

        # Build and return an engine.
        return builder.build_cuda_engine(network)

# do inference
with build_engine(ModelData.MODEL_FILE) as engine:
    # Build an engine, allocate buffers and create a stream.
    # For more information on buffer allocation, refer to the introductory samples.
    inputs, outputs, bindings, stream = common.allocate_buffers(engine)
    with engine.create_execution_context() as context:
        for idx in range(len(val_images)) :
            start = time.time()
            val_image = val_images[idx]
            val_pose = val_poses[idx] # added code
            np.copyto(inputs[0].host, val_image)
            np.copyto(inputs[1].host, val_pose) # added code
            [prediction] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream)

Is there anyone who succeeded to inference with multiple input model?


text:
Q: Bind buttons to array with [(ngModel)] I have an array of buttons that are generated with the *ngFor. It's a two day array. It generates rows based on one array and columns based on another. So one array is x = {a,b,c} and another is y = {0,1,2,3,4,5}. so I have 3 rows of 5 buttons. I want to bind each button to a spot in array to hold the toggled value. So A,3 should be the 3rd place, and c5 should be the 18th place in the array. I have i and j tracking each position for each array.
I tried binding it like [(ngModel)]="ary[i*y.length+j]" but it's ungodly slow and should be almost instant. This doesn't work and throw the error no value accessor for form control with unspecified name attribute
Has anyone had any experience with binding things generated with a *ngFor to a spot in an array?


text:
Q: If rect has class then add list in the box I have an issue with picking rect in svg.
As you can see the example, i want to write a list inside the ul.
If the rectangle has a class something. For example if the rect has class red, then i want to add a list inside ul or if the other rect has class blue, i want to add another list and so on.

(function($) {
      var rect = $('#edna-rect');
      var ul = $('.personal-list-ul');
      var personBox = $('.person-box');

      personBox.each(function(){
          if (rect.hasClass('red')) {
              $(this).ul.html('
List 1

List2

List3
')
          }
      })

 })(jQuery);
svg rect.red {
  fill: red;
}

svg rect.blue {
  fill: blue;
}

.person-box {
  width: 45%;
  float: left;
 }

Julia

        <svg id="rect-empty-big" xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 47 47">
            <rect id="edna-rect" class="st0edna rectangle red" x=".5" y=".5"  width="46" height="46"/>
        </svg>

Personal List

Brad

        <svg id="rect-empty-big" xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 47 47">
            <rect id="edna-rect" class="st0edna rectangle blue" x=".5" y=".5"  width="46" height="46"/>
        </svg>

Personal List

A: Since hasClass is not supported on SVG you can use .indexOf()
(function($) {
  var rect = $('.st0edna');
  var ul = $('.personal-list-ul');
  var personBox = $('.person-box');
  personBox.each(function() {
    if ($(this).find(rect).attr('class').indexOf("red") > -1) {
      $(this).find(ul).html('
List 1

List2

List3
')
    }
  })

})(jQuery);

Also you can't have multiple elements with the same ID, Id should be unique.  So I've changed var rect = $('#edna-rect'); to var rect = $('.st0edna')

(function($) {
  var rect = $('.st0edna');
  var ul = $('.personal-list-ul');
  var personBox = $('.person-box');
  personBox.each(function() {
    if ($(this).find(rect).attr('class').indexOf("red") > -1) {
      $(this).find(ul).html('
List 1

List2

List3
')
    }
  })

})(jQuery);
svg rect.red {
  fill: red;
}

svg rect.blue {
  fill: blue;
}

.person-box {
  width: 45%;
  float: left;
}

Julia

    <svg id="rect-empty-big" xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 47 47">
            <rect  class="st0edna rectangle red" x=".5" y=".5"  width="46" height="46"/>
        </svg>

Personal List

Brad

    <svg id="rect-empty-big" xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 47 47">
            <rect class="st0edna rectangle blue" x=".5" y=".5"  width="46" height="46"/>
        </svg>

Personal List

A: The jquery function 'hasClass' is not well spelt:
personBox.each(function(){
      if (rect.hasClass('red')) {
          $(this).ul.html('
List 1

List2

List3
')
      }
  })


text:
Q: Scatter plot from data in array Hi I would like to graph a very simple scatter plot from vba.
My data are stored in array (result from other calculations).
I do something like that :
Option Explicit

Sub graph()
    Dim MyChart As Chart
    Dim Fonds As Range, Benchmark As Range
    Dim RdtFonds, RdtBench

    Set MyChart = Worksheets("Feuil1").Shapes.AddChart2(227, xlXYScatter).Chart

    Set Fonds = Range("B2:B1940")
    Set Benchmark = Range("C2:C1940")

    RdtFonds = Rendement(Fonds)
    RdtBench = Rendement(Benchmark)

    With MyChart
        .SeriesCollection.NewSeries
        With .SeriesCollection(1)
            .Values = Rendement(Fonds)
            .XValues = Rendement(Benchmark)
'            .Trendlines.Add
'            .Trendlines(1).DisplayEquation = True
'            .Trendlines(1).DisplayRSquared = True
'            .Trendlines(1).Format.Line.ForeColor.RGB = RGB(192, 0, 0)
'            .Trendlines(1).Format.Line.DashStyle = msoLineSolid
            .MarkerStyle = -4168
            .MarkerSize = 5
        End With
        .HasTitle = True
        .ChartTitle.Text = "Fonds vs indice"
        With .Axes(xlValue)
            .MajorGridlines.Delete
            .TickLabels.NumberFormat = "0.0%"
            .HasTitle = True
            .AxisTitle.Characters.Text = "Fonds"
        End With
        With .Axes(xlCategory)
            .MajorGridlines.Delete
            .TickLabels.NumberFormat = "0.0%"
            .HasTitle = True
            .AxisTitle.Characters.Text = "Indice"
       End With
    End With
End Sub

Function Rendement(Prix As Range) As Variant
    Dim i As Integer, Rdt As Variant

    ReDim Rdt(1 To Prix.Rows.Count)

    For i = 1 To Prix.Rows.Count
        If i = 1 Then
            Rdt(i) = ""
        Else
            Rdt(i) = Prix(i) / Prix(i - 1) - 1
        End If
    Next i

    Rendement = Rdt
End Function

but I do not get what I expected. I get:

It is as if it plots something else. For example when I put my mouse on one point on the graph, I get :
serie 1 serie "0.04" (1725, 0.002)
the strange thing is (1725, 0.002) where as I should expect something like :
serie 1 serie "0.04" "0.002") I suppose.
Thx for your help

A: on the left this is what I get and on the right what I expect (I do it from excel). In the middle my data. I know that I apply the same function to the data.


text:
Q: Use nested layouts in Middleman I'm basically work with Middleman 2 though if this can only be done in Middleman 3 I can switch to it
I have layout.haml having all the boilerplate and simultaneously being the index's layout.
Now I want the inner.haml layout that will work for the rest of the pages, will inherit from layout.haml (in terms that I won't repeat the boilerplate parts), will incude some extra common styles / scripts, some common markup and will then re-place the yield blocks.
Currently I don't realize at all from where should I start. I understand how I can set inner.haml as a default layout and layout.haml as a layout for the "/" route, but how would the system know that the inner.haml is actually nested within layout.haml?
Sample setup
layout.haml
!!!5
%html
  %head
    %script(src="HTML5 shiv")
    %title
      My Site
      \|
      = yield_content :title
    = stylesheet_link_tag "site.css"
    = yield_content :page_styles
  %body
    %div(role="main")
      = yield_content :content
    %script(src="jquery")
    = yield_content :page_scripts

index.html.haml
- content_for :title do
  Index
- content_for :page_styles do
  = stylesheet_link_tag "index.css"
- content_for :page_scripts do
  %script(src="index.js")
- content_for :content do
  Cool banner here

inner.haml
-# somehow inherits from / extends layout.haml
- content_for :page_styles do
  -# somehow I'm putting some common content and then reinclude the block from the specific page
  = stylesheet_link_tag "inner.css"
  = yield_content :page_styles
-# same thing for page_scripts
- content_fir :content do
  -# again I define some common HTML, then include page's content

A: In 3.0 you'd have index use the layout inner which would wrap_layout layout.
In 2.0, you'll need a combination of partials and content_for blocks.

A: At first glance, I'd be tempted to do this with two templates. Perhaps not as elegant or DRY, but certainly understandable and easy to tweak later. E.g. for our site we have a front page layout and a rest of the site layout. And then in each MiddleMan source file we declare which layout will be used (see example).
All that aside, I'm hoping to learn something from a HAML master who has some magic for your situation!


text:
Q: Poner JFileChooser en español Tengo un programa en Java, que intenta guardar un archivo de texto, y para eso uso JFileChooser, pero el problema es que tiene el idioma en inglés.
Pude cambiar solo el título y el botón Guardar, pero todavía falta cambiar Cancel.
Mi código es el siguiente:
private static String diálogo(String entrada, boolean[][] matriz)
throws IOException {
    JFileChooser ventana = new JFileChooser(entrada);
    ventana.setDialogTitle("Guardar");
    ventana.setFileFilter(new FileNameExtensionFilter("Texto (txt)","txt"));
    if (ventana.showDialog(null,"Guardar") == JFileChooser.APPROVE_OPTION) {
        File archivo = ventana.getSelectedFile();
        FileWriter archivo_escribe=new FileWriter(archivo);
        archivo_escribe.write('c');
        archivo_escribe.close();
    }
}

Mi pregunta es... ¿Hay alguna manera de cambiar el texto de Cancel? Si es posible, me gustaría cambiar todos los textos, como File Name, o directamente cambiar el idioma del JFileChooser al español, porque también veo que dice Desktop en vez de Escritorio, etc.
Estuve investigando, y al parecer la solución es usar Locale, pero en la lista de propiedades no aparece el idioma español, solo aparece esto:

*

*CANADA, CHINESE, ENGLISH, FRENCH, GERMANY, ITALYAN, JAPANESE, KOREAN, TAIWAN, UK y US

¿Habrá que descargar algo extra?
La imagen del diálogo:

A: Quizá es porque estas usando tu OS en ingles, pero si no es así, JFileChooser usa el lenguaje especificado por la propiedad -Duser.language con lo cual deberías iniciar la JVM con ese parámetro indicando un idioma soportado. Supongamos que mi clase principal se llama Dialogo:
Ejecutar en español con: java -Duser.language=es Dialogo

Italiano: java -Duser.language=it Dialogo

Alemán: java -Duser.language=de Dialogo

Frances: java -Duser.language=fr Dialogo


text:
Q: Bootstrap Navbar collapse not working properly
I'm using twitter bootstrap on my site and when I collapse the window partially, this happens!
If I collapse the window further, then the desired button appears and the links disappear.
Q) Why is this happening? I want the nav links to collapse at this window width, leaving the button.  Nav code below:

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
            Toggle navigation

        </button>
        My brand name

            <li class="<%= GetCssClassNavItemHome() %>">Home

            <li class="<%= GetCssClassNavItem("/about") %>">About

            <li class="<%= GetCssClassNavItem("/services") %>">Services

            <li class="<%= GetCssClassNavItem("/project") %>">Projects

            <li class="<%= GetCssClassNavItem("/prices") %>">Prices

            <li class="<%= GetCssClassNavItem("/blog") %>">Blog

            <li class="<%= GetCssClassNavItem("/contact") %>">Contact

A: The problem is the padding applied in the class .container - 15px both left and right. If you reduce the padding, the problem goes away.
If you add another class to the div.container - in this example, say lesspadding:

etc.

and then apply different padding to the new class, like so:
.lesspadding {
    padding-left: 10px;
    padding-right: 2px;
}

Bootply here