text:
Q: Override interface parent method that use type hinting Let's say my boss have a class and interface:
class HisBar {}

interface HisFooInterface
{
    public function doSomethingWithBar(HisBar $bar);
}

and I have my own class that may or may not extends HisBar
class MyBar extends HisBar {}

I wish I could do this :
interface MyFooInterface extends HisFooInterface
{
    public function doSomethingWithBar(MyBar $bar);
}

But, Yes, I get the error :

Fatal error: Declaration of MyFooInterface::doSomethingWithBar() must
  be compatible with HisFooInterface::doSomethingWithBar(HisBar $bar) in
  path\to\MyFooInterface.php on line xx

I mean, I need use an instance of the interface but with different type hinting, is that even possible ? Is there any way to do this ? How to change type of the argument ? Thanks.


text:
Q: How comes this code works in groovy? How comes that it is possible to write this.class in the fields declaration of a class and it will actually do what is expected?
E.g.:
private static final logger = Logger.getLogger(this.class)

P.S.: Seems like a great place for Schroedinbug. :)

A: In Groovy this is bound to the class in a static context, and you can call static methods on it. Logger.getLogger(this.class) would be equivalent to just Logger.getLogger(Class).
class C {
    static final staticThis = this
    static final thisClass  = this.getClass()
    static final someResult = this.someMethod()

    static someMethod() { 'static' }
}

assert C.staticThis == C.class
assert C.thisClass  == Class
assert C.someResult == C.someMethod()

A: Justin's answer is correct, in a static context this is bound to the Class object of the current class, Therefore, you can replace the code above with:
private static final logger = Logger.getLogger(this)

which you can safely copy-paste from one class to another, unlike:
private static final logger = Logger.getLogger(MyClass.class)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variable in one function picks up value from variable in another function When I run this cpp code in devC++:
#include <iostream>
using namespace std;

#include <conio.h>

void getdata();
void dis();

void getdata()
{
    int radius;
    cout<<"\n enter radius of circle:-";
    cin>>radius;
}

void dis()
{
    int rad;
    cout<<"\n num is "<<rad;
}

int main()
{
    //int radius;
    getdata();
    dis();

    getch();
    return 11;
}

My output shows:

enter radius of circle:-15
radius is 15

my question is:
radius and rad are local to their functions, then how does rad became the same value as radius? They are in different functions.
Can someone kindly explain what is happening?

A: If the variable is uninitialized it will hold the garbage value!.
in your caserad will print the garbage value .It may differ every time you compile.

A: Undefined behavior.
When getdata() is called, radius occupies a particular block of memory on the stack, and is populated with the user's input. When getdata() exits, that memory block becomes available for later reuse, and its content is not cleared.
When dis() is then called afterwards, rad is not being initialized, so it picks up whatever random value was already present in the memory block that it occupies.
Most likely, what is happening is that rad happens to occupy the same memory block that radius had previously occupied. That is why you see the same value. But this is not guaranteed, so don't rely on it.  Add some additional variables above either radius or rad and you will see different behavior.
Always initialize your variables before you perform operations that are dependent on them.


text:
Q: What does constructor.prototype.property do in Javascript? var x = { foo: "A" };
x.constructor.prototype.foo = "B";
var y = {};

After running this code x.foo returns "A" which is understood. But y.foo returns "B" even if y is an empty object. I'm interested to know what does x.constructor.prototype.foo actually do?
Thanks for everyone in advance.

A: The constructor property of an object points to the constructor function that constructed the object. Your x variable is an object-literal, which was thus constructed by the Object() constructor function. Thus, accessing x.constructor.prototype is the same as accessing Object.prototype.
All constructor functions have a prototype property which forms part of the prototype chain. Basically, when your try to access a property of any object when that property is not actually defined on the object, then the JavaScript engine follows the prototype chain backwards looking to see if that property is defined on a prototype within the chain.
Because your y variable is also an object-literal, and thus was also constructed by Object(), when you try to access y.foo, since the foo property does not exist on y, the prototype chain search is commenced, which immediately hits Object.prototype.foo, which, as you know, has been assigned to "B".

A: From the docs

Returns a reference to the Object function that created the instance's
  prototype

in other words, all objects will now have a foo property, as you've added foo as a property on the Object prototype, and it's not the same as the foo property you added to x, you just did
var x = { foo: "A" };
Object.prototype.foo = "B"; // all objects from now on inherits this
var y = {};

A: x.constructor refers to Object (since all object literals have reference to Object assigned to their constructor predefined property).
Object.prototype is given a property foo and assigned value of "B".
y is object literal, thus it's internal [[Prototype]] property (available as __proto__ in some engines) refers to Object.prototype.
Due to JavaScripts prototypal inheritance, every time when object's property is requested, and this object does not contain the property, engine looks upward the prototype chain.
Thus when accessing y.foo - since y has no property named foo - you are accessing y.[[Prototype]].foo which is exactly Object.prototype.foo.

A: This is happening because when you did
var x = {foo: 'A'};

js has created an object with constructor Object(), You can verify it by typing
x.constructor

it will write function Object () {} in console.
now you are going further and accessing prototype of Object class and added 'foo' property in that.
At this point your Object class has a new property called 'foo'.
Now you have created a new object and referenced it with y. now y is created with Object constructor which contains 'foo' property.
Here prototype inheritance also kicks in. As you don't have any property in y it starts looking for 'foo' in the prototype hierarchy and 'foo' is found at the very and when it reaches Object in the hierarchy.
If you would have written:
var y = {foo: 'C'};

y.foo will give you output as 'C'


text: Q: SPICE model for the Arduino Nano I have designed a PCB in Eagle which I want to test. For that I would need a basic Arduino model which simulates what would happen if all the pins would have a high output. Would be better if I could also do some more fine-grained tests when only some pins are active but turning on all at once should be sufficient for a start. Besides that the GND pins should work as expected. How would I makee such a model?


text:
Q: Replacing "/\ characters with sed, from within php I generate password from php (thru web page) using shell_exec / dd/ /dev/urandom.
I want to eliminate
"/\
characters from my generated password.
If I do a replacement in my sed line with
's/["/\]/!/g'
the script fails to execute. However I tested this from command line like
echo "this /is \"a \test" | sed -e 's/["/\]/!/g'
Then I get the right result : this !is !a !test
If I eliminate this replacement section from my sed line, php script does execute properly. What seems to be the issue? I thought characters within brackets [] is safe and does not need escaping.. is that the issue?

A: In PHP, if you use the command in a double quoted string literal, you need to escape the " with a single backslash, \", and the backslash inside the bracket expression must also be escaped.
In the end, this must look like
sed 's/[\"/\\]/!/g'


text:
Q: Service Bus in ASP.NET Core I would like my ASP.NET Core application to send messages to a Azure Service Bus.
In Microsoft's article Best Practices for performance improvements using Service Bus Messaging they argue that you should re-use instances of clients.

It is recommended that you do not close messaging factories or queue, topic, and subscription clients after you send a message, and then re-create them when you send the next message.

So I take that as I should not instantiate a new instance of the client (TopicClient or QueueClient) inside my controller using the new keyword.
I guess that I should use dependency injection in ASP.NET Core.
Should I directly inject a TopicClient/QueueClient or should I create an own class that wraps an instance of the client and expose a SendAsync method?
When registering the service with dependency injector should I register it as a singleton?

A: We did it with a wrapper class that is then returning the TopicClient/QueueClient and registered it as a singleton and found no big issues with this approach.
We based our approach on this example provided by Microsoft eshopOnContainers.
The example code for this functionality is found in this file. They than register this class as singleton in Startup.cs in the services where they require ServiceBus.


text:
Q: Setting up relationships between objects I have custom object lets call it as items.

*

*Items may or maynot have cases associated with it. There can be more than one case associated to an item.

*All cases may or maynot have items associated with it.

I need to show on the cases object related lists to show all items related to that case and in the items object show all cases associated to this item.
How would i have to set the relationship between these objects
Thanks

A: Contrary to Sharma's answer I would really suggest you to use a relationship object for this. Create a new custom object (ie. CaseItem) with a lookup field to Case and a lookup field to Item. That way you can really have a many-to-many relationship. Shankar's solution could work in your case but you will run into problems, for instance if you want three different cases to have a relation to the same two or three items.
For the related lists; in the Item and Case objects you can add a related list with ItemCases. In the Case object only show the Item column of the ItemCase in that related list an in the Item object only show the Case column.

A: You have to create one look-up of case on your item object and one look-up of item on Case object. By doing this , you can associate one or more cases to a single item and one or more items to a single case.
It will automatically show related  cases/items in related lists.


text:
Q: Put ubuntu PC to standby after X minutes We've been using sleepd with ubuntu 12.04 to put public desktops to suspend after 5-10 minutes of inactivity. We are planning to deploy 13.10 (later move to 14.04), and have found out that sleepd package is missing.
Is there any other tool or a system wide setting to do this job? How other system administrators solve this problem?
EDIT: In our dormitory we have 90+ students. Some have regular user access and some use only the guest account. The solution must work when there aren't any users logged in.

A: I didn't test it, I could be missing a step.

*

*Use System Setting → Power / Brightness. Set all setting you need and as you want

*Create an override file from the current user settings and place it in /usr/share/glib-2.0/schemas/
echo "[org.gnome.settings-daemon.plugins.power]" > 90_mypower.gschema.override
gsettings list-recursively org.gnome.settings-daemon.plugins.power | awk '{ gsub("org.gnome.settings-daemon.plugins.power ","") ; print $1"="$2 }' >> 90_mypower.gschema.override

sudo mv 90_mypower.gschema.override /usr/share/glib-2.0/schemas/
sudo chown root:root /usr/share/glib-2.0/schemas/90_mypower.gschema.override
sudo chmod +r /usr/share/glib-2.0/schemas/90_mypower.gschema.override

*Compile the schemas
sudo glib-compile-schemas /usr/share/glib-2.0/schemas

*Create a lock file for all org.gnome.settings-daemon.plugins.power keys  and place it in /etc/dconf/db/gdm.d/locks/
gsettings list-keys org.gnome.settings-daemon.plugins.power | xargs -L 1 -I{} echo /org/gnome/settings-daemon/plugins/power/{} > 90-mypower-locks

sudo cp 90-mypower-locks /etc/dconf/db/gdm.d/locks/90-mypower-locks
sudo chown root:root /etc/dconf/db/gdm.d/locks/90-mypower-locks
sudo chmod +r /etc/dconf/db/gdm.d/locks/90-mypower-locks

*Update for locks
sudo dconf update

As you are looking for system administration, nice to learn:

*

*Watch dconf for change
dconf watch /

*Change power setting from GUI, watch for messages

*Open dconf-editor, go through same path, select a key

*Look at bottom, it shows its schema name/id: org.gnome.settings-daemon.plugins.power
References:

*

*dconf System Administrator Guide

*Shouldn't dconf-editor and gsettings access the same database?

*dconf Settings: defaults and locks

*man gsetting, man dconf

A: On the bottom of this answer are instructions for installing sleepd if you really insist. However that package is pretty much outdated for modern hardware.
If you are going to write a program, you can consider the following sources:

*

*Devices in /dev/input/

*If a user is logged in, rely on the desktop session manager. Its properties for consideration are described at How does ubuntu determine inactivity before suspending?
Instead of using sleep(3) in the code (like sleepd does), it is more battery-friendly if you use poll(3) or select(3) which have a timeout parameter. (This assumes that the /dev/input/* devices are poll-able, I don't know if that is the case but you should look up the documentation)

Upstream (git repo) has already removed the default hal dependency (commit), so you can try building from sources. The following commands were tested in a Kubuntu 13.10 Live environment. It installs the build dependencies, fixes a bug in the Makefile that prevented HAL from getting disabled and finally creates a deb package.
sudo apt-get install build-essential git debhelper libapm-dev
git clone git://git.kitenet.net/sleepd.git
cd sleepd
sed 's/ifdef USE_HAL/ifeq ($(USE_HAL), 1)/' -i Makefile
dpkg-buildpackage -b -us -uc

This produces a sleepd_2.05_amd64.deb package in the parent directory which you can then install on machines. This package requires a battery or AC interface to be present (e.g. /sys/class/power_supply/*), otherwise it will try APM. Since modern machines do not use APM, but ACPI, it will exit silently.
So while the package builds and install fine, you are better off with writing a new daemon if something like this is not already implemented.

A: is the power settings under system settings missing because thats where you can graphically set the time

as you can see if you have this which I'm sure you have, then you can modify it.


text:
Q: R Shiny renderMenu unexpected behavior I'm coming back to R after a more than two years break, and it's not easy.
I've created an interface thanks to shinydashboard package, including two different menus in the sidebar: one short and one extended. The extended menu should display when you click on the "Country" tab, but it opens very fast and then returns to short menu, and I don't understand why. The menus are rendered from the server side. Thank you very much for any help.
This is the ui code :
 library(dplyr)
 library(shiny)
 library(shinydashboard)

 ui <- dashboardPage(
   dashboardHeader(
       title = "2019 CENSUS",
       titleWidth = 500), # f. de dashboardHeader

     dashboardSidebar(#Sidebar contents
       sidebarMenu(id = "Menu1",
                   sidebarMenuOutput("Menu"))

     ), # closes dashboardSidebar

     #### BODY CONTENTS #####

     dashboardBody(

       # Title
       tags$head(tags$style(HTML('
                                 .main-header .logo {
                                 font-family: "Georgia", Times, "Times New Roman", serif;
                                 font-weight: bold;
                                 font-size: 16px;
                                 }
                                 '))), # closes tags$head(tags$style(HTML('

       tabItems(
         # Geo levels tab contents
         tabItem(tabName = "levels",
                 fluidRow(
                   box(width = 12, background = "light-blue",title = "Welcome", "Please choose a geo level from the three available then click on the 'Home datas' tab") # closes box
                 ) # closes fluidRow
         ), # closes tabItem

         # Country level tab contents
         tabItem(tabName = "country",
                 fluidRow(
                   box(title = "Country level : please, click on the 'Home datas' tab to view datas", width = 12, background = "olive") # closes box
                ) # closes fluidRow
         ), # closes tabItem

         # Counties tab contents
         tabItem(tabName = "counties",
                 fluidRow(
                   box(title = "Counties level", width = 3, solidHeader = TRUE, status = "primary",
                       checkboxGroupInput("dynamic_provinces", label = "", c("North","South","Islands"))) # closes box
                 ), # closes fluidRow

                 fluidRow(
                   box(title = "North county", width = 9, background = "light-blue"),  # closes box

                   br()

                 ), # closes fluidRow

                 fluidRow(
                  box(title = "South county", width = 9, background = "orange"), # closes box

                   br()

                 ), # closes fluidRow

                 fluidRow(
                   box(title = "Islands county", width = 9, background = "olive"),  # closes box

                 ) # closes fluidRow

              ) # closes tabItem

            ) # closes tabItems

          ) # closes dashboardBody

        ) # closes dashboardPage

And the server code :
 shinyServer(function(input, output, session) {

   # Initialize reactive values
   rv10 <- reactiveValues(selection = numeric())

   rv10$selection <- 0 # extended/short menu reactive value : extended menu if = 1/ short menu if = 0

   #### FOCUS ON THE WELCOME TAB ####

   updateTabItems(session, "Menu1", "welcome")

   ############## SETTING MENU DEPENDING ON THE VALUE OF rv10$selection ################

   output$Menu <- renderMenu({
     if (rv10$selection == 1) { # extended/short menu reactive value : extended menu if = 1/ short menu if = 0
       sidebarMenu(# Short menu
         menuItem(strong("Geo levels"), tabName = "levels", icon = icon("arrow-down"),selected = TRUE),
         menuSubItem("Country", tabName = "country", icon = icon("globe-americas")),
         menuSubItem("Counties", tabName = "counties", icon = icon("parking")),
         menuItem(strong("Home datas"), tabName = "home_datas", icon = icon("home"),
                  menuSubItem("Home data 1", tabName = "home_1", icon = icon("home")),
                  menuSubItem("Home data 2", tabName = "home_2", icon = icon("home"))),
         menuItem(strong("Quit"), tabName = "quit", icon = icon("remove"))

       ) # closes sidebarMenu
     } # closes if

     else {

       sidebarMenu(# Extended menu
         menuItem(strong("Geo levels"), tabName = "levels", icon = icon("arrow-down"),selected = TRUE),
         menuSubItem("Country", tabName = "country", icon = icon("globe-americas")),
         menuSubItem("Counties", tabName = "counties", icon = icon("parking")),
         menuItem(strong("Quit"), tabName = "quit", icon = icon("remove"))

       ) # closes sidebarMenu

     } # closes else

   }) # closes output$Menu <- renderMenu({

   #### OBSERVEEVENT #####

   observeEvent(input$Menu1, {

     # If click on the "Geo levels" tab -> short menu

     if (input$Menu1 == "levels"){

       rv10$selection <- 0 # rv10$selection = 0 -> displaying the short menu
       print(paste("rv10$selection value =", rv10$selection)) # displaying the value of rv10$selection
     }

     # If click on the "Country" tab -> extended menu

     if(input$Menu1 == "country"){

       rv10$selection <- 1 # rv10$selection = 1 -> displaying the extended menu
       print(paste("rv10$selection value =", rv10$selection))
     }

     # If click on the "counties" tab -> short menu

     if(input$Menu1 == "counties"){

       rv10$selection <- 0 # rv10$selection = 0 -> displaying the short menu
       print(paste("rv10$selection value =", rv10$selection))
     }

     #### CLOSING THE APP ####

     if (input$Menu1 == "quit"){

       print("Quit")
       stopApp()}

   }) # closes ObserveEvent(input$Menu1

 }) # closes shinyServer(function(input, output, session) {

Thank you very much for your help.

A: Be careful with your closing brackets. menuSubItem() is placed inside a menuItem().
Incorrect:
 sidebarMenu(# Short menu
         menuItem(strong("Geo levels"), tabName = "levels", icon = icon("arrow-down"),selected = TRUE),
         menuSubItem("Country", tabName = "country", icon = icon("globe-americas")),
         menuSubItem("Counties", tabName = "counties", icon = icon("parking")),
         menuItem(strong("Home datas"), tabName = "home_datas", icon = icon("home"),
                  menuSubItem("Home data 1", tabName = "home_1", icon = icon("home")),
                  menuSubItem("Home data 2", tabName = "home_2", icon = icon("home"))),
         menuItem(strong("Quit"), tabName = "quit", icon = icon("remove"))

       ) # closes sidebarMenu

Correct version:
sidebarMenu(# Short menu
        menuItem(strong("Geo levels"), tabName = "levels", icon = icon("arrow-down"),selected = TRUE,
        menuSubItem("Country", tabName = "country", icon = icon("globe-americas")),
        menuSubItem("Counties", tabName = "counties", icon = icon("parking"))),
        menuItem(strong("Home datas"), tabName = "home_datas", icon = icon("home"),
                 menuSubItem("Home data 1", tabName = "home_1", icon = icon("home")),
                 menuSubItem("Home data 2", tabName = "home_2", icon = icon("home"))),
        menuItem(strong("Quit"), tabName = "quit", icon = icon("remove"))

All I've done is remove the closing bracket at the end of the first menuItem() and placed it at the end of the second menuSubItem()

Full server code:
server <- function(input, output, session) {

  # Initialize reactive values
  rv10 <- reactiveValues(selection = numeric())

  rv10$selection <- 0 # extended/short menu reactive value : extended menu if = 1/ short menu if = 0

  #### FOCUS ON THE WELCOME TAB ####

  updateTabItems(session, "Menu1", "welcome")

  ############## SETTING MENU DEPENDING ON THE VALUE OF rv10$selection ################

  output$Menu <- renderMenu({
    if (rv10$selection == 1) { # extended/short menu reactive value : extended menu if = 1/ short menu if = 0
      sidebarMenu(# Short menu
        menuItem(strong("Geo levels"), tabName = "levels", icon = icon("arrow-down"),selected = TRUE,
        menuSubItem("Country", tabName = "country", icon = icon("globe-americas")),
        menuSubItem("Counties", tabName = "counties", icon = icon("parking")),
        startExpanded = TRUE
        ),
        menuItem(strong("Home datas"), tabName = "home_datas", icon = icon("home"),
                 menuSubItem("Home data 1", tabName = "home_1", icon = icon("home")),
                 menuSubItem("Home data 2", tabName = "home_2", icon = icon("home")),
                 startExpanded = TRUE
                 ),
        menuItem(strong("Quit"), tabName = "quit", icon = icon("remove"))

      ) # closes sidebarMenu
    } # closes if

    else {

      sidebarMenu(# Extended menu
        menuItem(strong("Geo levels"), tabName = "levels", icon = icon("arrow-down"),selected = TRUE),
        menuSubItem("Country", tabName = "country", icon = icon("globe-americas")),
        menuSubItem("Counties", tabName = "counties", icon = icon("parking")),
        menuItem(strong("Quit"), tabName = "quit", icon = icon("remove"))

      ) # closes sidebarMenu

    } # closes else

  }) # closes output$Menu <- renderMenu({

  #### OBSERVEEVENT #####

  observeEvent(input$Menu1, {

    # If click on the "Geo levels" tab -> short menu

    if (input$Menu1 == "levels"){

      rv10$selection <- 0 # rv10$selection = 0 -> displaying the short menu
      print(paste("rv10$selection value =", rv10$selection)) # displaying the value of rv10$selection
    }

    # If click on the "Country" tab -> extended menu

    if(input$Menu1 == "country"){

      rv10$selection <- 1 # rv10$selection = 1 -> displaying the extended menu
      print(paste("rv10$selection value =", rv10$selection))
    }

    # If click on the "counties" tab -> short menu

    if(input$Menu1 == "counties"){

      rv10$selection <- 0 # rv10$selection = 0 -> displaying the short menu
      print(paste("rv10$selection value =", rv10$selection))
    }

    #### CLOSING THE APP ####

    if (input$Menu1 == "quit"){

      print("Quit")
      stopApp()}

  }) # closes ObserveEvent(input$Menu1

} # closes shinyServer(function(input, output, session) {

Then run with:
shinyApp(ui, server)


text:
Q: What was this story about interstallar magnetic beings? What was this story and who is the author?
A space ship is sent to investigate the heliopause, and finds intelligent beings made from magnetic flux.  The ship passes through one without even knowing.  Much of the story is about trying to make contact.  When the ship runs into trouble and ejects a magnetic bubble (something to do with the containment system of its propulsion) the beings recognize that as being an intelligent thing.
The alien's activity is keeping the heliopause where we want it; I think the galactic activity would be pushing it inward or something to that effect.  The beings want to go off to greener pastures and the humans want to hire them to stay put for that reason.
Asked earlier on Worldbuilding.SE

A: I think this is The Sunborn by Gregory Benford.
This is a novel rather than a story, but it sort of matches much of your description. In the book life is discovered on Pluto and magnetic beings inhabiting the Oort cloud. There is a galactic storm, or something like it, that will push the heliopause in to about Saturn's orbit and the magnetic beings can prevent this by feeding on the storm.

And as the mission had prepared, a further, ominous puzzle arose: the solar system's bow shock was moving. This "pause point" is the working front where the sun's outward wind of particles meets the interstellar plasma. This forms a surface much like the curve made by a ship powering across a lake, seen from above. Before, the nearest this bow shock had gotten to the sun was about one hundred astronomical units, a full hundred times farther than the Earth-sun distance. But now that fluttery front lay only a few AU beyond Pluto, now just a tad beyond 40 AU from the sun.
If the solar wind let that wall of molecular hydrogen behind the shock intrude into the inner solar system, Earth could be destroyed. Even approaching partway in, say into Saturn, would be very dangerous. That seemed unlikely to the specialists, but without an explanation of what was happening beyond Pluto, few found that comforting.

Looking at the comments in Worldbuilding I note there is reference to something called a sinew, and this would be:

Most Beings knew how to skirt the worst of it, skating the edge while absorbing magnetic whorls and digesting them into stronger fields within themselves. They valued the helicity above all, the twisted fields that carried the tight strands like rubber bands, that enabled a Being to confine itself. Sinew gave strength.


text:
Q: html in a php variable I want to put some procedural stuff like html in a variable;
Normally we do this:
<?php

$my_var = '

some header

    some text.

';

?>

Now I want it to look like this:
<?php

$my_var = '

?>

some header

    some text.

<?php

';

?>

So that we open a php code, declare a variable, do some stuff outside php, and then reopen php code and close the var and we get that stuff that is outside php, we get it inside that variable.
Thanks.

A: <?php
ob_start();
?>

some header

    some text.
<?php

$my_var = ob_get_contents();
ob_end_clean();

echo my_var;
?>

A: i don't think there is a way because php ignores lines outside the php tags.
if u have the php in a other file user file_get_contents

A: Please check php heredoc
http://php.net/manual/en/language.types.string.php
Hope it helps


text:
Q: Jquery autocomplete onload I'm using the jquery autocomplete plugin.
Everything works as expected , but what I'm after is to trigger the select function if there is only one item in the dropdown list, so that fields get auto populated. Essentially setting things up once the page loads.
here's a sample of what I'm doing:
$('#auto-complete').autocomplete({
    source:function(){//get data here},
    select:function(e,ui){
     //setting fields here:
      $('#user').val("");
    },
   focus:function(){}

});

I've explored adding on a response function but even that seems to require a change in the autocomplete field first.

A: You can use the Response callback:

Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom source option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled.

Source: https://api.jqueryui.com/autocomplete/#event-response

$(function() {
  /*
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    */

  var availableTags = [
    "ActionScript"
  ];

  $("#tags").autocomplete({
    source: availableTags,
    minLength: 0,
    response: function(e, ui) {
      if (ui.content.length == 1) {
        $(this).val(ui.content[0].value);
        $(this).autocomplete("close");
      }
    }
  });

  $("#tags").autocomplete("search", "");
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

This is helpful is testing the the results after your Custom Source is called. I suspect you will need to update it a bit.
Alternately, you can test the results before you send the results to response() and if they are only 1, set the value at that time.


text:
Q: The Hilbert epsilon operator Why you can use the Hilbert epsilon operator in a method and in a function, but not in a "function method"?

method choose<T>(s:set<T>) returns (x:T)
 requires s != {}
{
var z :| z in s;
return z;
}

function choose'<T>(s:set<T>):T
// function method choose'<T>(s:set<T>):T // Activate this line and comment the previous line to see the error
 requires s != {}
{
var z :| z in s;
z
}

A: In order for the Hilbert epsilon operator, also known in Dafny as the let-such-that expression,
var z :| P; E

to be compilable, the constraint P must determine z uniquely. In your case, the constraint P is z in s, which does not determine z uniquely except for singleton sets.
If s were of type set<int>, you can (inefficiently) live up to this requirement by changing your choose' function to:
function method choose'<T>(s:set<int>):int
  requires s != {}
{
  var z :| z in s && forall y :: y in s ==> z <= y;
  z
}

Almost. You need to convince Dafny there is such a z. You can do that in a lemma. Here's a probably-longer-than-necessary-but-the-first-thing-I-got-working lemma that does that. Note that the lemma also uses the Hilbert operator, but in a statement context, so the uniqueness requirement does not apply.
function method choose'<T>(s:set<int>):int
  requires s != {}
{
  HasMinimum(s);
  var z :| z in s && forall y :: y in s ==> z <= y;
  z
}

lemma HasMinimum(s: set<int>)
  requires s != {}
  ensures exists z :: z in s && forall y :: y in s ==> z <= y
{
  var z :| z in s;
  if s == {z} {
    // the mimimum of a singleton set is its only element
  } else if forall y :: y in s ==> z <= y {
    // we happened to pick the minimum of s
  } else {
    // s-{z} is a smaller, nonempty set and it has a minimum
    var s' := s - {z};
    HasMinimum(s');
    var z' :| z' in s' && forall y :: y in s' ==> z' <= y;
    // the minimum of s' is the same as the miminum of s
    forall y | y in s
      ensures z' <= y
    {
      if
      case y in s' =>
        assert z' <= y;  // because z' in minimum in s'
      case y == z =>
        var k :| k in s && k < z;  // because z is not minimum in s
        assert k in s';  // because k != z
    }
  }
}

Unfortunately, the type of your s is not set<int>. I don't know how to get a unique value from a general set. :(
For information about why the uniqueness requirement is important in compiled expressions see this paper.
Rustan


text:
Q: Understand the order of commands in bash when functions are involved I have an example where I define a function named f which prints blah and then stores command itself and all its arguments into variable $@:
# f () { echo blah; "$@"; }
# df -h | f
blah
# df -h | f cat
blah
Filesystem                                              Size  Used Avail Use% Mounted on
rootfs                                                   37G   36G     0 100% /
udev                                                     10M     0   10M   0% /dev
tmpfs                                                   304M  308K  303M   1% /run
/dev/disk/by-uuid/466fbdef-029c-4625-8bb2-cde3acd77e55   37G   36G     0 100% /
tmpfs                                                   5.0M     0  5.0M   0% /run/lock
tmpfs                                                   2.1G     0  2.1G   0% /run/shm
/dev/sda2                                                74G  7.0G   63G  11% /home
/dev/sr1                                                5.6M  5.6M     0 100% /media
#

How does this f cat part on the right of the pipe work? How does the stdout of df -h end up in the $@ variable? Why does cat print the content of the $@ variable?

A: In:
df -h | f

You redirected df -h output to f standard in, then called f without any arguments, $@ is empty.
In other hand:
df -h | f cat

You redirected df -h output to f standard in, then called f with one argument cat. "$@" inside f expanded to cat. cat concatenated standard in, which is df -h output, to standard out.


text:
Q: How to factorize this expression? I know that :
$$-2\sin ^{ 2 }{ x } -\quad \sin { x } +\quad 1\quad =\quad -(\sin(x)+1)\quad \times \quad (2\times \sin(x)-1)$$
Is true, but I am not getting at all how to factorise the LHS expression.

A: Replace $\sin x$ by a single term $t$. Then $-2 \sin^2 x - \sin x + 1 = -2t^2 - t + 1 = (-t-1)(2t - 1)$.

A: You can also do in this way:
Let $t=\sin x$, then $-2 \sin^2 x-\sin x+1=-2t^2-t+1 =-(2t^2+t-1)=-(2t^2-2-(t+1))
=-(2(t-1)(t+1)-(t+1))=-((2t-1)(t+1)$.
May it is also useful for you.


text: Q: how to use bing translator api in my website coded in PHP and mobile jquery? i want to use bing translator api in my PHP based website in mobile jquery framework, i have generated Client ID and Client Secret Code  but  it shows an error Error in bing App id ???


text:
Q: pandas for loop with mysql query and variable parmeters I was loading my data from individual csv files into a dataframe using
df = pd.read_csv('data.csv', names=col_names, sep=',', skiprows=1)
col_names = ['created_date', 'latitude', 'longitude']

This would separate my data nicely into column frames and skip the first row which had the row labels
However i wanted to automate the process using a for loop that did the same query for every user. My function goes:
sql = "select distinct mobile_user_id from score where speed_range_id > 1"
distance_query = """SELECT created_date, latitude, longitude FROM score s where s.mobile_user_id = %(mobile_user_id)s and speed_range_id > 1 group by latitude, longitude order by id asc"""
cursor1.execute(sql)
result = cursor1.fetchall()

for rowdict in result:
    distance = cursor3.execute(distance_query, rowdict)
    distance_result = cursor3.fetchall()
    df = pd.read_sql_query(distance_query, rdsConn, params={rowdict})

As you can see here the result variable holds the list of users and i want to iterate through all the users to generate a dataset for every user.
I've been trying to use the pd.read_sql_query but i've been unable to pass the mobile user parameter which is rowdict to the query.
How would i go so i can pass that variable using pandas? How can i organize my data in the way i had it before?
sample of the data.csv:
created_date,          latitude,    longitude
"2018-05-24 17:46:25", 20.61844841, -100.40813424
"2018-05-24 21:03:02", 20.58469452, -100.39204018
"2018-05-25 10:29:57", 20.61180308, -100.40826959
"2018-05-25 21:02:43", 20.59868518, -100.37825344

Any help is appreciated.

A: Consider running pure SQL combining both queries by adding a WHERE clause to your aggregate query.
Currently, you are attempting a WHERE clause comparing one value per row to many values: where mobile_user_id = %(mobile_user_id)s which will never be equal. Plus, your prepared statement does not have same number of placeholders as parameter values. Possibly you meant where mobile_user_id IN (?, ?, ?, ?, ?, ...) which involves dynamically setting placeholders, ?.
Nonetheless, simply run an aggregate query. Then, import the resultset into pandas. Specifically, add mobile_user_id as a grouping in query:
sql = """select mobile_user_id, created_date, latitude, longitude
         from score
         where speed_range_id > 1
         group by mobile_user_id, created_date, latitude, longitude
         order by id asc
      """

df = pd.read_sql_query(sql, rdsConn)


text:
Q: Does MailboxProcessor just duplicate IObservable? I want to process to types of a message
Add x makes program remember number x
Print makes it print all remembered numbers
Why would I write this:
open System
type Message =
    | Add of int
    | Print
let mailbox = new MailboxProcessor<Message>(fun inbox ->
        let rec loop history = async{
            let! msg=inbox.Receive()
            match msg with
                | Add x -> return! loop(history + x.ToString()+" ")
                | Print ->
                    printfn "%s" history
                    return! loop(history)
        }
        loop ""
    )
[<EntryPoint>]
let main argv =
    mailbox.Start()
    mailbox.Post(Add 12)
    mailbox.Post(Add 56)
    mailbox.Post(Print)
    mailbox.Post(Add 34)
    mailbox.Post(Print)
    ignore <| Console.ReadLine()
    0

instead of this:
open System
open System.Reactive.Subjects
type Message =
    | Add of int
    | Print
let subject = new Subject<Message>()
[<EntryPoint>]
let main argv =
    subject
        |> Observable.scan(fun history msg ->
                match msg with
                        | Add x -> history + x.ToString()+" "
                        | Print ->
                            printfn "%s" history
                            history
            ) ""
        |> Observable.subscribe(fun _->())
        |> ignore
    subject.OnNext(Add 12)
    subject.OnNext(Add 56)
    subject.OnNext(Print)
    subject.OnNext(Add 34)
    subject.OnNext(Print)
    ignore <| Console.ReadLine()
    0

The MailboxProcessor adds additional level of complexity. I need a state machine which takes a state and returns a state. But it forces me to take inbox, which is used to receive state.
Does it has any advantages to IObservable?

A: No, they're not duplicates of one another. MailboxProcessor and IObservable are low-level building blocks of two different models of computation - actor model and functional reactive programming respectively.
Both deal with asynchronicity, but emphasize different qualities. It's might be possible to build your solution in terms of one or the other - as you noticed in your simple example - but you will find one or the other more natural to use in a particular context.
MailboxProcessors are particularly useful for thread-safe, lock-free access to a resource, such as a file. You can have multiple threads manipulating the resource through an asynchronous interface, and the MailboxProcessor guarantees that only one of those requests is processed at a time.


text:
Q: Using time zones in a PHP web application I've been looking around for a few hours now about what's the best way to use timezones in a PHP/MySQL web application, finding a definitive answer is hard. From what I've learnt so far it is best to store everyones stuff in the database in UTC (correct me if I am wrong).
When a user registers I will ask them for there timezone and then store that against there user. This would be in this format as a dropdown menu:
<option value="Europe/London">(GMT) Greenwich Mean Time : London</option>

The app I am building will allow users to set arrangements in the future with people (meetings), much like a calendar. Obviously over the course of a year different timezones have different daylight savings periods, any idea how I would cater for this?
Say a user from the UK sets a meeting for 3:00PM on January 24th 2013 and invites someone who lives in California to this meeting, how do I get it so that the American sees that meeting in his/her timezone and the UK user sees it in his/her timezone? (Note that both users are signed up and have set their timezone).
Does anyone have a clear explanation and maybe some examples for this? Or can point me to where I can find that?
Thanks

A: In MySQL, what you need to do is:

*

*Store each user's chosen timezone someplace you can retrieve it when you're doing database queries on behalf of that user.  You can store it as a string.

*Right before you do work on behalf of a particular user (for example, storing or retrieving appointment times and dates) do SET time_zone = (stored time zone setting)
This will cause time zones to be converted appropriately to each person's local time.
Edit:
This works because

*

*MySQL tries to use UTC (universal time, formerly known as Greenwich Mean Time) to store DATETIME and TIMESTAMP data items in tables.

*It can only do this correctly if it knows the correct local time zone for each data item it is given by applications.

*In applications that don't care about different time zones, it does this in a MySQL-server-wide way.  See https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html .  Most people who run multi-national and multi-time-zone applications set their server time zones to UTC, not to local time, because it makes it much easier to keep things sorted out.

*It makes very little sense to try to convert a time from UTC to local time unless you also know the date and the timezone, because local time switches on and off at various times of year.  Just try to get this right for all three of Israel, Arizona, and New York, I dare you!  Israel switches between daylight and standard time on Passover and Rosh Hashanah; Arizona doesn't switch, and New York switches at the whim of the US federal legislature.

*There's a session-scope time_zone setting (SET time_zone = something). If you don't set it, it uses the timezone representation in item 3 above. If you set it, the server will use this as the timezone to convert its internal representation to the representation it sends back in queries.

*You can get a list of the names of the available time zones in your MySQL server by issuing SELECT Name from mysql.time_zone_name. This can populate the pulldown menu from which your user can select her time zone. If this query returns no items, take a look at bottom of https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html .

So, that means you can set your session time_zone setting to a particular user's time zone, and then get back all times in that user's time zone. Also, any DATETIME or TIMESTAMP items you INSERT or UPDATE will be converted from that user's time zone to MySQL's internal representation as they are placed in your tables.
Be careful: in web applications with persistent MySQL connections, the work for a new user request will inherit the connection's time_zone setting.  Don't forget to reset it for the new user.
If you're running a query returning local time data for more than one user, and those users happen to be in different time zones, you can't take advantage of this MySQL per-session feature set. You can work around this by running different queries for different users and changing the time_zone setting between them.
Or, you can use the MySQL function
CONVERT_TZ(datetime,'UTC','user_time_zone')

or similar on each item.
Alternatively, Java and DotNET have their own high-quality time zone manipulation systems. So, you can make the choice of running your MySQL server with the time_zone setting of UTC, and do all your timezone conversions in your application.

A: I dealt with this situation extensively in a PHP/MySQL application I wrote for a private jet operator a little over a year ago.  There are different strategies to handle timezones in these two platforms, but I will explain how I did it.  I set the MySQL server to UTC and run each PHP script in the timezone that the user specifies during the signup process for the user profile.
MySQL and PHP (PHP 5.2 and above) both have native datetime datatypes.  MySQL's datetime is a primitive data type, while PHP 5.2 and above offers the built-in DateTime class.  The MySQL datetime datatype does not include metadata for the timezone, but a PHP DateTime object always includes a timezone.  If the PHP datetime constructor does not specify the optional timezone in the second argument, then the PHP datetime constructor uses the php environment variable.
Both MySQL and PHP have default timezone set in the configuration files.  MySQL uses the datetime set in the config file for each db connection unless the user specifies a different timezone after connection is started with the command SET time_zone = [timezone];. PHP also sets a timezone environment variable for each script using the timezone set in the server config file, and this environment variable can be overriden using the PHP function date_default_timezone_set() after the script starts.
The PHP DateTime class has a property called timezone, which is a PHP DateTimeZone object.  The DateTimeZone object is specified using a string for the exact time zone.  The list of timezones is comprehensive, having hundreds of individual time zones across the world.  The PHP time zones will account for daylight savings time automatically.
When the user generates a datetime in the web app, construct a PHP datetime object in the timezone of the user's profile.  Then use the setTimezone method to modify the DateTime object to the  UTC timezone.  Now you have the user's datetime in UTC, and you can store the value in the database.  Use the DateTime format method to express the data as a string in the format accepted by MySQL.
So the user generates a datetime, and you make a PHP datetime object in the user's specified timezone:
// set using an include file for user profile
$user_timezone = new DateTimeZone('America/New_York');

// 1st arg in format accepted by PHP strtotime
$date_object1 = new DateTime('8/9/2012 5:19 PM', $user_timezone);
$date_object1->setTimezone(new DateTimeZone('UTC'));
$formated_string = $date_object1->format('Y-m-d H:i:s');
$query_string = "INSERT INTO `t_table1` (`datetime1`) VALUES('$formated_string')";

When you retrieve the value from the database, construct in UTC and then convert to the user's time zone.
$query_string = "SELECT `datetime1` FROM `t_table1`";
$date_object1 = new DateTime($datetime_string_from_mysql, new DateTimeZone('UTC'));
$date_object1->setTimezone($user_timezone);
$string_for_display_in_application = $date_object1->format('m/d/Y g:i a');

Using this method, your datetime values are always stored in UTC inside the db, and the user always experiences the values in his/her profile's time zone.  PHP will correct for Daylight Savings Time if necessary for each time zone.
One gotcha:  This explanation does not cover the MySQL timestamp datatype.  I recommend using the MySQL datetime datetype to store datetime values, not the timestamp datatype.  The timestamp datatype is covered in the manual here.
Edit:
You can produce an array containing every PHP timezone string using listIdentifiers, which is a static method of the DateTimeZone class.


text:
Q: Select Query incomplete I have 17 records inserted in my table "book".
<?php
include 'config.php';

session_start();

$sql = "SELECT * from book";
$result = mysqli_query($db, $sql);
$count = mysqli_num_rows($result);

if($count == 0){
    $error = "There is no books in the list";
}

?>

    ISBN
    Title of the book
    Cost
    Copies
    Edition
    Publisher
    Copy Year
    Shelf Number
    Subject

<?php while($row = mysqli_fetch_array($result)){

$ISBN = $row['ISBN'];
$Title = $row['Title'];
$Cost = $row['Cost'];
$Copies = $row['Copies'];
$Edition = $row['Edition'];
$Publisher = $row['Publisher'];
$CopyYr = $row['CopyYr'];
$Shelf = $row['ShelfNo'];
$Subject = $row['SubName'];

?>

    <?php echo $ISBN; ?>
    <?php echo $Title; ?>
    <?php echo $Cost; ?>
    <?php echo $Copies; ?>
    <?php echo $Edition; ?>
    <?php echo $Publisher; ?>
    <?php echo $CopyYr; ?>
    <?php echo $Shelf; ?>
    <?php echo $Subject; ?>

    <?php
}
?>

<form action="AddBook.php" method="post">
        <input type="submit" value="Add Book"/>
    </form>
<form action="editbook.php" method="post">
        <input type="submit" value="Edit List"/>
    </form>
<form action="deletebook.php" method="post">
        <input type="submit" value="Delete Book/s"/>
    </form>
<form action="AdminSummary.php" method="post">
        <input type="submit" value="Back"/>
    </form>

This will display 17 records in the table. But when I add another record to the table, It will display an incomplete record, a "500 server error", or an empty table.
I have been in the same problem for days, searching for a solution, and I can't find any.
I don't know what the problem is, so any help would be appreciated. Thank You :)


text:
Q: Reading non well-formed XML file without quotation marks in attribute - python I have an xml-like file that doesn't have the quotation marks in the attribute attribute="xxx" and it doesn't have a the standard <?xml version="1.0"?> header so when I tried to parse with minidom or elementtree, they complained the file as not well-formed:
>>> import xml.etree.ElementTree as et
>>> tree = et.parse(infile)
>>> Traceback (most recent call last):
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 25

How do I read the input file? Or how could I make the xml well-formed?
My input file looks like this:
<contextfile concordance=brown>
<context filename=br-a01 paras=yes>

<s snum=1>
<wf cmd=ignore pos=DT>The</wf>
<wf cmd=done rdf=group pos=NNP lemma=group wnsn=1 lexsn=1:03:00:: pn=group>Fulton_County_Grand_Jury</wf>
<wf cmd=done pos=VB lemma=say wnsn=1 lexsn=2:32:00::>said</wf>
<wf cmd=done pos=NN lemma=friday wnsn=1 lexsn=1:28:00::>Friday</wf>
<wf cmd=ignore pos=DT>an</wf>
<wf cmd=done pos=NN lemma=investigation wnsn=1 lexsn=1:09:00::>investigation</wf>
<wf cmd=ignore pos=IN>of</wf>
<wf cmd=done pos=NN lemma=atlanta wnsn=1 lexsn=1:15:00::>Atlanta</wf>
<wf cmd=ignore pos=POS>'s</wf>
<wf cmd=done pos=JJ lemma=recent wnsn=2 lexsn=5:00:00:past:00>recent</wf>
<wf cmd=done pos=NN lemma=primary_election wnsn=1 lexsn=1:04:00::>primary_election</wf>
<wf cmd=done pos=VB lemma=produce wnsn=4 lexsn=2:39:01::>produced</wf>
<punc>``</punc>
<wf cmd=ignore pos=DT>no</wf>
<wf cmd=done pos=NN lemma=evidence wnsn=1 lexsn=1:09:00::>evidence</wf>
<punc>''</punc>
<wf cmd=ignore pos=IN>that</wf>
<wf cmd=ignore pos=DT>any</wf>
<wf cmd=done pos=NN lemma=irregularity wnsn=1 lexsn=1:04:00::>irregularities</wf>
<wf cmd=done pos=VB lemma=take_place wnsn=1 lexsn=2:30:00::>took_place</wf>
<punc>.</punc>
</s>

</context>
</contextfile>

A: use lxml:
mytext="""<contextfile concordance=brown>
<context filename=br-a01 paras=yes>

....
<wf cmd=done pos=VB lemma=say wnsn=1 lexsn=2:32:00::>said</wf>
<wf cmd=done pos=NN lemma=friday wnsn=1 lexsn=1:28:00::>Friday</wf>
<wf cmd=ignore pos=DT>an</wf>
....
....
<punc>``</punc>
<wf cmd=ignore pos=DT>no</wf>
<wf cmd=done pos=NN lemma=evidence wnsn=1 lexsn=1:09:00::>evidence</wf>
<punc>''</punc>
....
<wf cmd=done pos=NN lemma=irregularity wnsn=1 lexsn=1:04:00::>irregularities</wf>
<punc>.</punc>
</s>

</context>
</contextfile>"""

from lxml import html
parsed = html.fromstring(mytext)
for x in parsed.getiterator(): print x.tag, x.attrib, x.text, x.tail

output:
contextfile {'concordance': 'brown'} None None
context {'paras': 'yes', 'filename': 'br-a01'} None None
p {'pnum': '1'}
....

wf {'lemma': 'say', 'cmd': 'done', 'wnsn': '1', 'pos': 'VB', 'lexsn': '2:32:00::'} said None
wf {'lemma': 'friday', 'cmd': 'done', 'wnsn': '1', 'pos': 'NN', 'lexsn': '1:28:00::'} Friday None
wf {'cmd': 'ignore', 'pos': 'DT'} an
....
....

punc {} `` None
wf {'cmd': 'ignore', 'pos': 'DT'} no None
wf {'lemma': 'evidence', 'cmd': 'done', 'wnsn': '1', 'pos': 'NN', 'lexsn': '1:09:00::'} evidence None
punc {} ''
....

wf {'lemma': 'irregularity', 'cmd': 'done', 'wnsn': '1', 'pos': 'NN', 'lexsn': '1:04:00::'} irregularities None
punc {} . None


text:
Q: What does it mean when df returns the same mount over and over? I am on the latest MacOS Catalina 10.15.5.  I have the following automount setup:
/etc/auto_master:
/- auto_smb -nosuid,timeout=35

/etc/auto_smb
/System/Volumes/Data/Users/myuser/Volumes/mymount -fstype=smbfs,soft,rw ://user:pass@smbhost/share

When I run df -h command, it shows the following duplicated over and over:
map auto_smb          0Bi 0Bi 0Bi 100% 0 0 100% /Users/myuser/Volumes/mymount
//user@smbhost/share 4.4Ti 3.1Ti 1.3Ti 71% 3341027482 1397355092 71% /Users/myuser/Volumes/mymount

Every now and then there is a new duplicate in the output.  Right now there're 100+ duplicates but the mounted disk works fine.
This problem seems to be recent as I've only begun experiencing this in the past month or so.  Even though the mount works fine, sometimes it seems to be a little slower to access than it should be...
Why is automount generating so many duplicates (or df just reporting them), is this an actual concern (I imagine it should be) and what can I do to prevent this from happening?
I have confirmed that internet speed gets slower as there are more connections.  To reset this I need to remove the auto_smb part and diskutil unmount force //user@smbhost/share and/or sudo automount -vc.
The logs in MacOS Console are showing kernel errors:
smb2fs_smb_cmpd_query: smb2fs_smb_ntcreatex failed 13


text:
Q: Как вставить два таймера обратного отсчёта на javascript на одну страницу? Есть счётчик обратного отсчёта на яваскрипт (Countdown.js):
//Скрипт обратного отсчета времени CountDown

var eventstr = "Вы опоздали"; //Эта строка выводиться по окончанию отсчета
var countdownid = document.getElementById("countdown"); //ID элемента в который выводится время

var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function CountDowndmn(yr,m,d){
    cdyear=yr;
    cdmonth=m;
    cdday=d;
    var today=new Date();
    var todayy=today.getYear();
    if (todayy < 1000)
    todayy+=1900;
    var todaym=today.getMonth();
    var todayd=today.getDate();
    var todayh=today.getHours();
    var todaymin=today.getMinutes();
    var todaysec=today.getSeconds();
    var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec;
    futurestring=montharray[m-1]+" "+d+", "+yr
    dd=Date.parse(futurestring)-Date.parse(todaystring);
    dday=Math.floor(dd/(60*60*1000*24)*1);
    dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
    dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
    dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
    if(dday<=0&&dhour<=0&&dmin<=0&&dsec<=1){
    countdownid.innerHTML=eventstr;
return
}
else {
    var lastchar = ""+dsec; lastchar = lastchar.substring(lastchar.length-1,lastchar.length);
    var dsecstr = "с";
    if (lastchar=="1") { dsecstr = "с"; }
    if ((lastchar=="2")||(lastchar=="3")||(lastchar=="4")) { dsecstr = "с"; }

    lastchar = ""+dmin; lastchar = lastchar.substring(lastchar.length-1,lastchar.length);
    var dminstr    = "м";
    if (lastchar=="1") { dminstr = "м"; }
    if ((lastchar=="2")||(lastchar=="3")||(lastchar=="4")) { dminstr = "м"; }

    lastchar = ""+dhour;    lastchar = lastchar.substring(lastchar.length-1,lastchar.length);
    var dhourstr   = "ч";
    if (lastchar=="1") { dhourstr = "ч"; }
    if ((lastchar=="2")||(lastchar=="3")||(lastchar=="4")) { dhourstr = "ч"; }

    lastchar = ""+dday; lastchar = lastchar.substring(lastchar.length-1,lastchar.length);
    var ddaystr = "д";
    if (lastchar=="1") { ddaystr = "д"; }
    if ((lastchar=="2")||(lastchar=="3")||(lastchar=="4")) { ddaystr = "д"; }

    countdownid.innerHTML= dday+" "+ddaystr+" : "+dhour+" "+dhourstr+" : "+dmin+" "+dminstr+" : "+dsec+" "+dsecstr;

}
setTimeout("CountDowndmn(cdyear,cdmonth,cdday)",1000);
}

CountDowndmn(2013,06,10); //Дата отсчета: год, месяц, число

А также код, который выводит сам счётчик на странице в диве:

Если вставляю счётчик в двух местах на странице, то один счётчик перестаёт работать.
Как этот счётчик можно вставить на страницу в двух разных местах?
A: А может быть, не стоит изобретать велосипед?


text:
Q: best (web) architecture for my project So I'm not sure if this is really the right place to ask or even the right question but I want to give it a try.
Requirements:
We should have a database & webservice (or something similar) which runs in OUR office, clients cann access the application via the internet ("wohooo").
Clients must be able to create orders in a simple mask. There is a basic mask (which all clients have), but the mask can also have some client-specific stuff.
When they created the order, a label with a barcode (which contains the order number) is printed locally (and automatically) at their office on a label-printer.
They take the label and put it on a sample, which they then send us (on the real post-way).
We get the sample, scan the barcode on the label and the order appears in our "administration-screen". We then have every information we need about the order (and the sample).
Surely we also need a backend where our staffmembers can edit the client-specific mask and add some fields (for specific-clients) and other master-data.

All in all this doesn't sound too complex. The only thing which stands out a little, may be the automatic print of labels at their place I guess. Because of this reason it may not be possible to use a "server-side only" architecture (like jsf or spring with jsp and so on), because you have to have access directly on their local printers.
So I thought a good way is maybe to use spring (with Hybernate, JavaBeans (JEE)) together with JavaFX which would allow to access local printers and so on. I thought we could just make a webinstaller/webstart for the application, which installs the JavaFX clients for the clients. The JavaFX client could then communicate with the webserver (spring) and insert the order there, get all required information like the order-number for printing the label and so on.
For the backend in our office I could also imagine to use JavaFX...
So where's my question?
Well its simple: Is this a good way to do it? Are these fitting technologies for doing it? Or is it already to complicated and this could be accomplished in a much easier way? If so what do you suggest?
Naturally I also want to lay a big focus on easy extensibility and maintainibility.

A: Do all clients have a label printer?  Is the only way to be an effective client is with a label maker?
Can you just as easily scan a plain old sheet of paper with a barcode that might be included or contained with a packing list that a client would include in their material shipment to you?
In any case, a special client side solution beyond browser HTML/CSS/JS would probably not be necessary from what was described here.

*

*A bar code can be generated dynamically on the server side.

*A recommended packing list that includes the bar code can be sent to the browser as accompanying documentation with their order receipt.

*A browser can be coerced to automatically suggest a page be printed.  The page could be an order receipt (which includes the recommended packing list with bar code).  The user still has to choose to proceed with the print job, but are not obligated to.

*Provide a facility to view and reprint past/recent/last order receipts (including the recommended packing list that contains the bar code) in case a user unknowingly cancels the first, workflow induced, prompt to print.  Printers can be problematic so having a recovery opportunity is a good thing.

Perhaps there are other features that necessitate a particular client side solution, but so far, I do not see it.


text:
Q: Can NHibernate load data from 2nd level cache after session is closed? I am trying stuff I can make with NHibernate for my app. I am using quite a lot of "dictionaries" to store all possible values for certain object properties. I've tried playing with 2nd level cache to store those dictionaries data in there. Now I wonder if there is a way to load needed data from cache after the session is closed. Let's say that is my code:
public class Class1 {
    public virtual int Id { get; set; }
    public virtual Dic1 Dic { get; set; }
}

public class Dic1 {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

and here are the mappings:
<class name="Class1" table="class1">
    <id name="Id" column="id">
        <generator class="native" />
    </id>
    <!-- I want to try not to use fetch="join" here -->
    <many-to-one
        name="Dic"
        class="Dic1"
        column="dic1_id"
    />
</class>

<class name="Dic1" table="dic1">
    <cache usage="read-write"/>
    <id name="Id" column="id">
        <generator class="native" />
    </id>
    <property name="Name" column="name" />
</class>

If I get value of Class1.Dic object before I close the session, NHibernate does not send query to the database, because value was cached by some earlier query.
But let's say, I've closed the session. In debug session, Class1.Dic is an object of Dic1Proxy type and I get an exception when I try to access it/it's properties. Is there a way to load that data after session is closed? 2nd level cache is connected to session factory, so maybe there is a way to actually turn that Proxy into the right object? Or actually force to always load those values without changing fetch method to join.

A: You can use NHibernateUtil.Initialize(class1.Dic); before closing the session. It will do nothing if the object is not actually a proxy or if it is already loaded, otherwise it will load it (from the second level cache if cached).
You can also force eager fetching while keeping the default select fetch mode: set lazy as false on the many-to-one mapping of the Dic property. Loading a Class1 will then trigger immediately a load of the Dic property. It should fetch it from second level cache if it is in it. Beware that this will cause n+1 loads issues if you query a list of Class1 and if their Dic property is not cached, even if you have enabled batching of lazy loads.
Otherwise if you do not want to do any kind of manipulation on your Dic property before closing the session, you need to change the proxy implementation for it to first check the second level cache before failing if the session is already closed. But this will require too much work to be worth it, in my opinion. (Moreover, what if the entity is missing in the cache anyway? Is it acceptable for your application to fail in such case?)
NHibernate allows you to supply your own factory of proxy factory (IProxyFactoryFactory), by using the proxyfactory.factory_class optional setting, provided you use the default bytecode provider.
Then you would need to implement your own IProxyFactoryFactory, which would likely mostly be a copy of StaticProxyFactoryFactory with BuildProxyFactory yielding a custom proxy factory.
The custom proxy factory would itself likely be mostly a copy of StaticProxyFactory, with GetProxy using a custom ILazyInitializer at this line.
The custom lazy initializer would in turn be likely a copy of LiteLazyInitializer, but with an override of Initialize. Its implementation is here.
That is for the easy part, and till there, that is not as bad as it sounds, that does not involve copying so many lines of code.
Now for the override of Initialize, it would need to check the Session property and acts accordingly, calling its base implementation if the session is usable, or trying to directly load from the second level cache otherwise.
Here you would have more code to duplicate, mainly LoadFromSecondLevelCache and AssembleCacheEntry.
You will also need the persister, which is easy to get if you have the session factory: sessionFactory.GetEntityPersister(EntityName). (ILazyInitializer has an EntityName property.)
As you can see by checking their code, these functions use at many points the session:

*

*CacheMode: checked for ensuring the cache is enabled for the session, you surely should skip that check for your use case.

*GenerateCacheKey: easy to inline out of the session, see its code.

*Timestamp: using sessionFactory.Settings.CacheProvider.NextTimestamp() instead should do it.

*Instantiate: use subclassPersister.Instantiate(id) instead. (Unless you have an interceptor to which it should be delegated.)

The other calls are more troublesome.
You will have to give-up on safe-keeping from circular references as this uses the session persistence context.
Then there is the Assemble and DeepCopy logic which use the session. Many cases just call its Factory property, so depending on the property types of your entities, a dummy session just actually supplying the factory may do.
Skip the readonly stuff if possible, otherwise you will have still more work to do.
Skip most of the persistenceContext stuff: that is the session first level cache. Still there is the InitializeNonLazyCollections call which will be lacking if your entities have some.
About AfterInitialize, this call is currently needed for handling entities having lazy properties (not being an entity or a collection). So you may be able to skip it.
And finally, the PostLoadEvent is there for entities implementing ILifecycle: again, you may be able to skip it, provided you do not use ILifecycle.
If you have also some cached collections to retrieve from the second level cache without a session, you would need to do a similar work with the collection type factory, configurable with the collectiontype.factory_class, providing your own ICollectionTypeFactory yielding collection types overriding Initialize, likewise duplicating the loading from second level cache.
Good luck if you try this.


text:
Q: Blockdiagram with dsp library I am using the dsp library, http://www.texample.net/tikz/examples/fir-filter/, to create a blockdiagram. Now I got 2 problems.

*

*I defined two labels, r and d_i however they are not visible on the screenshot because I believe the standalone package cuts down to the current shape (does not see the labels?).

*Is anyone capable of changing the plus symbol in the library. I namely want a plus symbol like in matlab or can give a different solution such that I can create e.g.

        -
    -----O-----
        +|
         |
         |_____

code:
\documentclass{standalone}
\usepackage{graphics}
\usepackage{siunitx}
\usepackage{tikz}
\usetikzlibrary{dsp,chains}
\usepackage{pgfplots}
\usepgfplotslibrary{groupplots}
\pgfplotsset{compat=newest}
\pgfplotsset{plot coordinates/math parser=false}

\DeclareMathAlphabet{\mathpzc}{OT1}{pzc}{m}{it}
\newcommand{\z}{\mathpzc{z}}

\begin{document}
\begin{tikzpicture}
    \matrix[row sep=2.5mm, column sep=5mm] {
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
        \node[dspnodeopen,dsp/label=above] (m08) {$d_i$};     &
                                              &
                                              &
                                              \\
        %--------------------------------------------------------------------
        \\
        %--------------------------------------------------------------------
        \node[dspnodeopen,dsp/label=left]  (m10) {$r$};       &
        \node[coordinate]                  (m11) {};          &
        \node[dspadder]                    (m12) {};          &
        \node[coordinate,dsp/label=above]  (m13) {$e$};       &
        \node[dspsquare]                   (m14) {$K$};       &
        \node[coordinate]                  (m15) {$u$};       &
        \node[dspsquare]                   (m16) {$T_u$};     &
        \node[coordinate]                  (m17) {};          &
        \node[dspadder]                    (m18) {};          &
        \node[coordinate]                  (m19) {};          &
        \node[dspsquare]                   (m1A) {$G$};       &
        \node[coordinate]                  (m1X) {};          \\
        %--------------------------------------------------------------------
        \\
        %--------------------------------------------------------------------
                                              &
                                              &
        \node[coordinate,dsp/label=left]   (m22) {$t$};       &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
        \node[dspsquare]                   (m2A) {$T_y$};     &
        \node[coordinate]                  (m2X) {};          \\
        %--------------------------------------------------------------------
        \\
    };

    % Draw connections
    \begin{scope}[start chain]
        \chainin (m10);
        \chainin (m12) [join=by dspconn];
        \chainin (m14) [join=by dspconn];
        \chainin (m16) [join=by dspconn];
        \chainin (m18) [join=by dspconn];
        \chainin (m1A) [join=by dspconn];
        \chainin (m1X) [join=by dspline];
        \chainin (m2X) [join=by dspline];
        \chainin (m2A) [join=by dspconn];
        \chainin (m22) [join=by dspline];
        \chainin (m12) [join=by dspconn];
    \end{scope}

    \draw[dspconn] (m08) -- (m18);

\end{tikzpicture}
\end{document}

A: another possibility with the schemabloc package http://www.ctan.org/tex-archive/graphics/pgf/contrib/schemabloc

\documentclass{article}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage{schemabloc}

\begin{document}
\begin{tikzpicture}
\sbEntree{E}
\sbCompSum*[4]{C1}{E}{}{+}{-}{ }    \sbRelier[{$r$}]{E}{C1}
\sbBloc[2.5]{K}{$K$}{C1}        \sbRelier[{$\varepsilon(p)$}]{C1}{K}
\sbBloc[2.5]{TU}{$T_u$}{K}        \sbRelier{K}{TU}
\sbComph*{C2}{TU}                 \sbRelier{TU}{C2}{}
\sbBloc{G}{$G$}{C2}        \sbRelier{C2}{G}{}
\sbSortie[1]{S}{G}                 \sbRelier{G}{S}
\sbDecaleNoeudy[-2.5]{TUdroite}{pert}    \sbRelierxy{pert}{C2}{}
\sbDecaleNoeudy[5]{G}{TY}
\sbBlocr[-1.25]{TY}{$T_y$}{TY}
                                  \sbNomLien[1]{pert}{$d_i$}
\sbRelieryx{S}{TY}{}
\sbRelierxy{TY}{C1}{}
\end{tikzpicture}

\end{document}

A: Here's one possible solution:

*

*You can use the border key specifying appropriate lengths to be added to the top and to the left.

*I defined a new shape dspvoidshapeadder suppressing the plus sign from the original dspshapeadder; using this new shape I defined a new style vdspadder using the newly defined shape and adding the + and - labels.
The code:
\documentclass[border={10pt 0pt 0pt 10pt}]{standalone}
\usepackage{graphics}
\usepackage{siunitx}
\usepackage{tikz}
\usetikzlibrary{dsp,chains}
\usepackage{pgfplots}
\usepgfplotslibrary{groupplots}
\pgfplotsset{compat=newest}
\pgfplotsset{plot coordinates/math parser=false}

\DeclareMathAlphabet{\mathpzc}{OT1}{pzc}{m}{it}
\newcommand{\z}{\mathpzc{z}}

\makeatletter
\dspdeclareoperator{dspvoidshapeadder}{
    % Coordinate offset for the plus
    \pgfutil@tempdima=\radius
    \pgfutil@tempdima=0.55\pgfutil@tempdima
    \pgfusepathqstroke
}
\tikzset{vdspadder/.style={shape=dspvoidshapeadder,line cap=rect,line join=rect,
    line width=\dspblocklinewidth,minimum size=\dspoperatordiameter,label=below left:$+$,label=above left:$-$}}
\makeatother
\begin{document}
\begin{tikzpicture}
    \matrix[row sep=2.5mm, column sep=5mm] {
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
        \node[dspnodeopen,dsp/label=above] (m08) {$d_i$};     &
                                              &
                                              &
                                              \\
        %--------------------------------------------------------------------
        \\
        %--------------------------------------------------------------------
        \node[dspnodeopen,dsp/label=left]  (m10) {$r$};       &
        \node[coordinate]                  (m11) {};          &
        \node[vdspadder]                   (m12) {};          &
        \node[coordinate,dsp/label=above]  (m13) {$e$};       &
        \node[dspsquare]                   (m14) {$K$};       &
        \node[coordinate]                  (m15) {$u$};       &
        \node[dspsquare]                   (m16) {$T_u$};     &
        \node[coordinate]                  (m17) {};          &
        \node[vdspadder]                    (m18) {};          &
        \node[coordinate]                  (m19) {};          &
        \node[dspsquare]                   (m1A) {$G$};       &
        \node[coordinate]                  (m1X) {};          \\
        %--------------------------------------------------------------------
        \\
        %--------------------------------------------------------------------
                                              &
                                              &
        \node[coordinate,dsp/label=left]   (m22) {$t$};       &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
                                              &
        \node[dspsquare]                   (m2A) {$T_y$};     &
        \node[coordinate]                  (m2X) {};          \\
        %--------------------------------------------------------------------
        \\
    };

    % Draw connections
    \begin{scope}[start chain]
        \chainin (m10);
        \chainin (m12) [join=by dspconn];
        \chainin (m14) [join=by dspconn];
        \chainin (m16) [join=by dspconn];
        \chainin (m18) [join=by dspconn];
        \chainin (m1A) [join=by dspconn];
        \chainin (m1X) [join=by dspline];
        \chainin (m2X) [join=by dspline];
        \chainin (m2A) [join=by dspconn];
        \chainin (m22) [join=by dspline];
        \chainin (m12) [join=by dspconn];
    \end{scope}

    \draw[dspconn] (m08) -- (m18);

\end{tikzpicture}
\end{document}


text: Q: Is the well-orderability of the reals independent from dependent choice? Working in $ZF$+"There is a well-order of the real numbers", is there any known model that also satisfies $\neg DC$? I have tried to look at this in Jech's "The Axiom of Choice", but I'm not very familiar with symmetric extensions or permutation models, so I don't know whether the techniques used to break $DC$ would work if the reals are well-ordered. In principle I don't see why not, but I've learned to be cautious about the $ZF$ world.


text:
Q: How to get the double quotes arround number typed field from MongoDB aggregation query result? Scenario: I have a collection 'People' with following documents
       {
         "_id" : ObjectId("512bc95fe835e68f199c8686"),
         "name": "David",
         "age" : 78
       },
       { "_id" : ObjectId("512bc962e835e68f199c8687"),
         "name" : "Dave",
         "age" : 35
       }

When I query using following code from Node.js
db.articles.aggregate(
    { $match : { author : "Dave" } }
);

The output will be like:
       { "_id" : ObjectId("512bc962e835e68f199c8687"),
         "name" : "Dave",
         "age" : 35
       }

Issues: The above is just a sample of the actual scenario, I want the 'age' filed value to be embedded in double quotes i.e for above quoted example it should be like "age": "35".
That is full resultant document should be like following:
{ "_id" : ObjectId("512bc962e835e68f199c8687"),
     "name" : "Dave",
     "age" : "35"
   }

Consider I have huge number of documents how efficiently I can achieve the same to get the desired output?
Question: Can someone help out with bright and efficient way to achieve the same?


text:
Q: Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL? What are the differences between PRIMARY, UNIQUE, INDEX and FULLTEXT when creating MySQL tables?
How would I use them?

A: Differences

*

*KEY or INDEX refers to a normal non-unique index.  Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index.  These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

*UNIQUE refers to an index where all rows of the index must be unique.  That is, the same row may not have identical non-NULL values for all columns in this index as another row.  As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.
Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself).  Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

*PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this).  A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values.  Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row.  Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.
Some database systems (such as MySQL's InnoDB) will internally store a table's actual records within the PRIMARY KEY's B-tree index.

*FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems.  FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).
Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.
Similarities

*

*All of these indexes may have more than one column in them.

*With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values.  (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)

A: I feel like this has been well covered, maybe except for the following:

*

*Simple KEY / INDEX (or otherwise called SECONDARY INDEX) do increase performance if selectivity is sufficient. On this matter, the usual recommendation is that if the amount of records in the result set on which an index is applied exceeds 20% of the total amount of records of the parent table, then the index will be ineffective. In practice each architecture will differ but, the idea is still correct.

*Secondary Indexes (and that is very specific to mysql) should not be seen as completely separate and different objects from the primary key. In fact, both should be used jointly and, once this information known, provide an additional tool to the mysql DBA: in Mysql, indexes embed the primary key. It leads to significant performance improvements, specifically when cleverly building implicit covering indexes such as described there.

*If you feel like your data should be UNIQUE, use a unique index. You may think it's optional (for instance, working it out at application level) and that a normal index will do, but it actually represents a guarantee for Mysql that each row is unique, which incidentally provides a performance benefit.

*You can only use FULLTEXT (or otherwise called SEARCH INDEX) with Innodb (In MySQL 5.6.4 and up) and Myisam Engines

*You can only use FULLTEXT on CHAR, VARCHAR and TEXT column types

*FULLTEXT index involves a LOT more than just creating an index. There's a bunch of system tables created, a completely separate caching system and some specific rules and optimizations applied. See http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html and http://dev.mysql.com/doc/refman/5.7/en/innodb-fulltext-index.html

A: All of these are kinds of indices.
primary: must be unique, is an index, is (likely) the physical index, can be only one per table.
unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.
index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.
fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.


text:
Q: How do i get more hard drive space? I'm dual booting Ubuntu 12.10 with Windows 7 & I installed Ubuntu 12.10 on a 100gig partition but the biggest HD space option when I installed Ubuntu was only 30gig. How can I allocate more space for Ubuntu on that partition?

A: I'm assuming that you were able to see an empty 100GB partition from Windows.  If that's the case, Ubuntu setup should be able to see the same 100GB partition and you should be able to allocate the entire partition to Ubuntu.
Your best option here is to run setup again, and wipe the partition during setup.  Use the manual partitioning option ("Do something else")


text:
Q: is htaccess is need to placed in every sub folder i am using the .htaccess for the first time and as every where shows i tried the following code to get the clean url
RewriteEngine on
RewriteRule ^address/([0-9a-zA-Z]+)$ detail.php?add=$1
i also tried to modify it to
Options +FollowSymLinks
RewriteEngine on

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^address/([0-9a-zA-Z]+)$ detail.php?add=$1

But it is not working. is it because i have placed in the main directory and the detail.php is in a folder "content"?


text:
Q: Showing refresh icon on the top of the screen while navigating back - React native Showing a white refresh circle on the top while navigating back from a screen having refresh control in the flatlist.
This issue is occuring in the android devices only and not occuring in the android OS 8.
this issue won't come if i refresh the screen at-least once when mounted and issue won't come if i comment the refresh control.
i'm attaching the sample code below , please help me to fix this issue.
import * as React from 'react';
import { View, Text, FlatList, StyleSheet, Button, RefreshControl } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen(props) {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Button
                title="Go to Next Screen"
                onPress={() => props.navigation.navigate('FlatList')} />

        </View>
    );
}
const DATA = [
    {
        id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
        title: 'First Item',
    },
    {
        id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
        title: 'Second Item',
    },
    {
        id: '58694a0f-3da1-471f-bd96-145571e29d72',
        title: 'Third Item',
    },
];

const Item = ({ title }) => (
    <View style={styles.item}>
        <Text style={styles.title}>{title}</Text>
    </View>
);

const FlatListScreen = () => {
    const renderItem = ({ item }) => (
        <Item title={item.title} />
    );

    return (
        <View style={styles.container}>
            <FlatList
                data={DATA}
                style={{ marginTop: 50 }}
                renderItem={renderItem}
                keyExtractor={(item, index) => index.toString()}
                refreshControl={<RefreshControl
                    onRefresh={() => { }}
                    refreshing={false}
                />
                }
            />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'black'
    },
    item: {
        backgroundColor: '#f9c2ff',
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
    },
    title: {
        fontSize: 32,
    },
});

const Stack = createNativeStackNavigator();

function App() {
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen name="Home" component={HomeScreen} />
                <Stack.Screen name="FlatList" component={FlatListScreen} />
            </Stack.Navigator>
        </NavigationContainer>
    );
}

export default App;

A: It seems to be a bug in the RefreshControl. This happens when it's unmounted.
There's an open issue for that: https://github.com/facebook/react-native/issues/34718
Someone posted a workaround: https://github.com/facebook/react-native/issues/34718#issuecomment-1295919690
The issue itself must be solved upstream tough.
Below is the workaround (I changed a bit to allow to specify a custom offset, because I use it in my code):
const selectHook = <T,>({
    useDefault,
    useAndroid,
}: {
    useDefault: T;
    useAndroid: T;
}) => {
    return Platform.select({
        default: useDefault,
        android: useAndroid,
    });
};

/**
 * Quick workaround for refreshing issue on Android:
 * The refresh control is showing up above the header when unmounting the screen.
 * Note: It's happening when using a custom header component, but didn't I try using
 * native header from the native stack.
 * See: https://github.com/facebook/react-native/issues/34718
 */
const useProgressViewOffset = selectHook({
    useDefault: (offset?: number) => offset,
    useAndroid: (offset?: number) => {
        const navigation = useNavigation();
        const [progressViewOffset, setProgressViewOffset] = useState(offset);
        const goBackEventWasHandled = useRef(false);

        // prevent the navigation event and hide the refresh indicator
        React.useEffect(() => {
            const unsubscribe = navigation.addListener('beforeRemove', (event) => {
                // Handle GO_BACK event only, because it fits my use case, please tweak it to fit yours
                if (
                    event.data.action.type === 'GO_BACK' &&
                    !goBackEventWasHandled.current
                ) {
                    event.preventDefault();
                    goBackEventWasHandled.current = true;
                    setProgressViewOffset(-1000); // set to a ridiculous value to hide the refresh control
                }
            });

            return unsubscribe;
        }, [navigation]);

        // perform the navigation with the hidden refresh indicator
        React.useEffect(() => {
            if (progressViewOffset !== undefined && goBackEventWasHandled.current) {
                navigation.goBack();
            }
        }, [navigation, progressViewOffset]);

        return progressViewOffset;
    },
});

Then you can use it in your code like:
// ...
const progressViewOffset = useProgressViewOffset()
// ...
<RefreshControl
  {...refreshProps}
  progressViewOffset={progressViewOffset}
/>


text:
Q: WebView crashes on navigation popBackStack() with Jetpack Compose LazyColumn I have WebView inside the LazyColumn. It shows up fine. The thing is when I try to navigate back by calling navController.popBackStack(), I got fatal crash (Fatal signal 11 (SIGSEGV)).
I ran it on the emulator. It works fine when click the "Back" button in the emulator.
Also, it works fine when I replace LazyColumn with Column.
Any idea or thought?

A: I had the same issue and you can fix this in some ways that I've found:

*

*destroying your WebViev webView.destroy() or making it invisible webView.visibility = View.INVISIBLE when your screen disappears.

*adding alpha = 0.99F (any value but less than 1) to WebView.  webView.alpha = 0.99F

A: When using WebView inside LazyColumn try using the remember function to retain the state across rebuilds. Alternatively, you can try a different layout component like VerticalScroller to wrap the WebView.
LazyColumn{
    items(items){
    // ...
        remember {
            WebView(/* ... */)
        }
    }
}