text:
Q: How can the (JSON) formatted results from MySQL Shell be saved to a file? Somewhat uniquely among official MySQL applications, MySQL Shell offers (easy) JSON output. From the MySQL shell prompt, typing the following will get you results as a JavaScript array of objects (one for each row):
\option resultFormat json/array
\use information_schema
SELECT table_catalog, table_schema, table_name, engine, create_time, table_collation
  FROM tables
  WHERE table_schema='INFORMATION_SCHEMA' AND table_name LIKE 'T%';

This is then passed to a pager for display on-screen. How can the output instead be redirected or otherwise saved to a file (named e.g. results.json)?
(Note: the query could be anything. The above is provided as a simple, yet not trivial, test case that should be runnable against any MySQL installation.)
As MySQL Shell is available on various platforms, platform agnostic solutions are preferred, but solutions for specific platforms are also of interest.

A: Simple Solutions
From what I can determine, there are two simple ways. One is from a login shell command line in non-interactive mode, and the other is to (ab)use MySQL Shell's \pager command.
Login Shell
The login shell way is what you would do to capture any command output, along with specific mysqlsh arguments to run the query. For a Unix shell:
sql="SELECT table_catalog, table_schema, table_name, engine, create_time, table_collation
    FROM tables
    WHERE table_schema='INFORMATION_SCHEMA' AND table_name LIKE 'T%';"
mysqlsh -u user --sql --result-format=json/array --schema=INFORMATION_SCHEMA --execute "$sql" > results.json

For PowerShell, the variable would be set differently (i.e. with sv sql "..."), but the rest would be the same.
\pager Trickery
The old mysql client has a tee command that could send output to a file. While MySQL Shell has no similar command, \pager can be set to a (login shell) command that will output the results to a file. If you want to see the results as well, use whatever tee command the system has.
\option resultFormat json/array
\pager tee results.json
\use information_schema
SELECT table_catalog, table_schema, table_name, engine, create_time, table_collation
    FROM tables
    WHERE table_schema='INFORMATION_SCHEMA' AND table_name LIKE 'T%';

If you don't want to see the results, use a login shell command that produces no output, such as \pager cat >results.json or \pager type >results.json.
Note that each query result will replace the previous one (with a bit of trickery, you could probably create a command that would pick a file name that doesn't exist each time it's run).
Note also that the output will include the result summary ("<N> rows in set (<time> sec)") at the end. If you don't want this, either remove it from the file, or pipe the results through a command that will remove it before outputting to a file (e.g. grep -E -v '^[0-9]+ rows in set \([.0-9]+ sec\)$' | tee results.json or Select -SkipLast 1 | Tee-Object results.json; see "Opposite of tail: all lines except the last n lines" for more Unix options).
You can still pipe the results through a pager, if you want to view paged results. For example:
\pager sed '$d' | tee results.json | less

Complex Solutions
Python
Interactively, Python can be used, but only with appropriately defined helpers. As this solution relies on coding, it's potentially off-topic for DBA.SE and more suited for SO. However, the alternative of creating a related question on SO for this solution borders on cross-posting and splinters the answer, so the solution is presented here.
In programmatic modes (JS or Python), query results are Result or ClassicResult objects. MySQL Shell will format these when displaying them, but the results themselves have no format. This means in any programmatic mode, the results would have to be formatted programmatically before being output.
The Python engine has open, and the json module is available. Between the two of these, suitable functions can be defined to format results as JSON and output them to a file. json.JSONEncoder doesn't support Result and ClassicResult, so either a suitable JSONEncoder would need to be defined, or they'll need to be converted to built-in types, as will any fields that aren't built-in types (e.g. Date columns). The latter can be done fairly succinctly.
First, fields. A simple method to tell whether json can encode a field is to try it and handle the failure by converting the value to a string. Additionally, the field is to be fetched by name from the row using get_field.
def row_field(row, name):
    """Get a field by name from a row, converting it to a built-in type if necessary."""
    field = row.get_field(name)
    try:
        json.dump(row.get_field(name))
    except:
        field = str(field)
    return field

Converting to a built-in is fairly straight forward: the results must be fetched, and then list and dict comprehensions will assemble the row data into built-in types, using the above row_field() to fetch & convert fields.
def nativize(results):
    """Convert SQL query results to built-in types."""
    rows = results.fetch_all()
    return [{name:row_field(row, name) for name in results.column_names} for row in rows]

json.dump() will convert supported objects to JSON and output to a given file object.  To tie everything together, here's a function to convert results, open a file and pass them to json.dump().
def dump_json(results, file=None, **kwargs):
    """Dump (or return) results as JSON to a file.

    If no `file` is given, returns JSON results as string.
    """
    data = nativize(results)
    if file:
        fp = open(file, 'w')
        json.dump(data, fp, **kwargs)
        fp.close()
    else:
        return json.dumps(data, **kwargs)

The above functions can be added to a plugin starting with version 8.0.17. In the 'plugins' directory on your platform, place the above functions (and an import json statement) into the init script in a plugin folder (e.g. 'dump_json/init.py'), along with the following to create an extension and add the file output function (adapted from the example plugin):
if 'ext' not in globals():
    ext = shell.create_extension_object()
    shell.register_global("ext", ext, {"brief":"MySQL Shell extension plugins."})

try:
    shell.add_extension_object_member(ext, "dump_json", dump_json, {
        'brief': 'Writes or returns the JSON representation of results to a given file.',
        'parameters': [
            {
                'name': 'results',
                'type': 'object',
                'brief': 'Query results.',
            },
            {
                'name': 'file',
                'type': 'string',
                'brief': 'output pathname',
                'required': False,
            },
        ]
    })
except Exception as e:
    shell.log("ERROR", f'Failed to register util.dump_json: {e}.')

The dump_json function can then be accessed via the ext global in MySQL Shell:
\py
query="""SELECT table_catalog, table_schema, table_name, engine, create_time, table_collation
    FROM tables
    WHERE table_schema='INFORMATION_SCHEMA' AND table_name LIKE 'T%';
"""
\use information_schema
results = session.run_sql(query)
ext.dump_json(results, 'path/to/results.json')

If using a version older than 8.0.17, instead create a Python module with the helper functions (the code to create an extension ext and add dump_json to it should be left out), and import the module from within MySQL shell.
Dead Ends
From within an interactive shell, INTO OUTFILE is handled by the server, so doesn't have the chance to be formatted by MySQL Shell. More generally, SQL is interpreted server-side and doesn't have a way of directing a client to save results to a file, so interactive SQL mode in MySQL Shell offers no solution on its own.
JavaScript doesn't have a standard way (either built-in, or from a library) of accessing files. The MySQL JS API offers a few of its own methods, such as reading text files via os and util's various file I/O methods, but not general file output. util misses the mark on two counts: though it has a few file output methods, they can only dump databases & tables (not arbitrary query results) and only in the standard dump format. (One method of general interest, though, is util.importJSON, which supports importing a JSON file into a document store.)
Additionally, JavaScript mode doesn't appear to have the standard JSON object to produce JSON output.


text:
Q: Recovering Password
Possible Duplicate:
How do I reset a lost password (using recovery mode requires me to type the password)?

My sister gave me her Mini inspiron 1010 with ubuntu 8.04 that she bought in the Philippines more than 3 years ago. The problem is she said she forgot her password so i cant upgrade my ubuntu.
I tried doing this :

*

*Boot the mini 9 while pressing ESC every second

*When you see the "MBR 2FA:" prompt or similar, the boot process is stopped.

*Press ENTER and ESC very fast one after the other.

*You should then see the GRUB menu. Using the up and down arrows, highlight the second option and press ENTER to boot into recovery mode.

but nothing happens when i press Enter and Esc nothing happens.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to include headefile and functions at runtime C++? I two base projects. Proj1.lib and Proj2.exe. Now Proj2.exe is the startup projects and it will invoke Proj1.lib. Now when i will add another Test.lib to my main project, which contains Gtest. Now, to make Gtest to accumulate all the test cases in GTest, we need to call a function from Test.lib and that function name and header file need to be included in Proj2.exe. Then Proj.exe will get compiled and then it will compile Test.lib and then it will execute test cases. But now my requiremnet is not to disturb Proj2.exe. When ever I want I will attach/deachTest.lib or Test2.lib ... and so on.
Below will show, how we are doing it currently.
Proj1.lib
x.c file
y.c file {/*App_Main_function()*/}

Proj2.exe
A.cpp
B.cpp file {/*Call App_Main_function();*/}
AttachTest.cpp {Test_Main();}

Test.lib
Test.cpp
{
    TestMain()
    {/*Body*/
        InitilizeGoogleTest();
        TEST_F(abc, ab)
        {}
    }
}

Tomorrow if there will be more or new test libraries then I have to open AttachTest.cpp file from Proj.exe and add the function name and header files name. Then Proj2.exe will compile again.
But I want now I will keep Proj1.lib and Proj2.exe fix they won't get compile except new Test.lib
How to do that,
I have thought of a way to do it as, I will have .xml file, which will have function name. In Proj2.exe, I will have function pointers it will call them at run time. But how to include header file then??
Please help me.

A: You will need to build Dynamic-Link libraries (DLL) for doing what you want. .lib libraries can't be loaded dynamically.
Below some example code how to use such libraries, from Wikipedia:
#include <windows.h>
#include <stdio.h>

// DLL function signature
typedef double (*importFunction)(double, double);

int main(int argc, char **argv)
{
        importFunction addNumbers;
        double result;
        HINSTANCE hinstLib;

        // Load DLL file
        hinstLib = LoadLibrary(TEXT("Example.dll"));
        if (hinstLib == NULL) {
                printf("ERROR: unable to load DLL\n");
                return 1;
        }

        // Get function pointer
        addNumbers = GetProcAddress(hinstLib, "AddNumbers");
        if (addNumbers == NULL) {
                printf("ERROR: unable to find DLL function\n");
                FreeLibrary(hinstLib);
                return 1;
        }

        // Call function.
        result = addNumbers(1, 2);

        // Unload DLL file
        FreeLibrary(hinstLib);

        // Display result
        printf("The result was: %f\n", result);

        return 0;
}


text:
Q: Converting a common js global namespace A-Frame project into es6 modules I have an A-Frame project with a primary component street that also depends on other components and helper functions from the same repo.
Currently using the street component in an A-Frame scene requires importing 8 separate js files from the same repo each with their own <script> tag. (code / show page)
Instead, I would prefer a simpler structure to import just one file, but I'd rather not use a bundler such as webpack. I think there is an ES6 approach but I'm confused about how to go about leveraging ES6 imports while still allowing the components to access functions from other files. In other words, how to get the imported files into the same namespace.
This question helps but the comments clarify the imported functions are not added to the global namespace automatically:
ES6 import equivalent of require() without exports
Maybe the structure would be something like this?
// index.html
<script src="src/street.js" ></script>
<a-scene>
 <a-entity street="dosomething"></a-entity>
</a-scene>

// helperFunctions1.js
function coolHelperFunction1a (variable) {
  // useful code
}

// street.js
import 'helperFunctions1.js'
import 'helperFunctions2.js'

AFRAME.registerComponent('street', {
  coolHelperFunction1a (variable);
})

That probably won't work, what's the right way to do it?

A: A-Frame and ES Modules don't play well together, and I don't think there's a solution without using a bundler like Webpack.
In short, if you want to have a single <script> element for your entire app while still organizing your code well, I'd recommend Webpack, with the generated bundle being loaded synchronously in the <head> of your HTML document. Webpack can consume ES Modules, so you're still free to use those with the build process.
More detail on why native module loading won't work:
Your code would need a few changes for native ES Module usage, but the first one presents a problem: the <script> elements loading your modules need the type="module" attribute. This has a side effect: the browser treats modules the same way it treats traditional script tags with the defer attribute, meaning the script is executed after the DOM has been parsed. This is by design, as it leads to better initial page performance. Unfortunately A-Frame expects to run before the DOM has been parsed, and further it expects that you've initialized all of your components, systems, etc. before it runs. That is why they recommend putting the a-frame script in the <head>, and you'll notice there is no defer attribute.
A-Frame is kind of going against modern web performance advice, but it has a good reason: it doesn't want the browser to render the HTML before it runs, since its using the HTML for its own purposes.
This all means using native ES modules directly in the browser isn't going to work for an A-Frame app.

A: The suggested structure above needs a few fixes.
First, add export to the helper functions. For example,
function helperFunction (variable) {
  code (variable);
}

changes to
export function helperFunction (variable) {
  code (variable);
}

(See How can I export all functions from a file in JS?)
In street.js we also need to make sure to reference the module object it's imported as (See MDN Creating a module object)
We also need to change the <script> tag to include type="module" to use import and export keywords.
Here is a revised structure:
// index.html
<script src="src/street.js" type="module"></script>
<a-scene>
 <a-entity street="dosomething"></a-entity>
</a-scene>

// helperFunctions1.js
export function coolHelperFunction1a (variable) {
  // useful code
}

// street.js
import * as helperFunctions1 from 'helperFunctions1.js'
import * as helperFunctions2 from 'helperFunctions2.js'

AFRAME.registerComponent('street', {
  helperFunctions1.coolHelperFunction1a(variable);
})

A: Another option, don't use ES6 Modules and use webpack instead. This is a nice example of a webpack A-Frame component project:
https://github.com/supermedium/superframe/blob/master/components/state/


text:
Q: deleting selected record in subform (query) I have main form with subform which contains the query from six tables, how do i delete the record when the user selects a record in subform (deleting that record in those six tables too). I had this working with listbox which had query before, but i liked the format of subform over a listbox. Here is what i did for deleting record from listbox:
Option Compare Database

Private Sub Delete_Record_Click()
    If IsNull(Me.List10) Then
         MsgBox "Please select a record from the list to delete", vbCritical
    Else

        DoCmd.SetWarnings False
            If MsgBox("Are you sure you want to delete this record?", vbYesNo + vbDefaultButton2 + vbCritical, "Warning") = vbYes Then
                    DoCmd.RunSQL "Delete * from Ref Where Ref.Record_Num=" & Me.List10
                    DoCmd.RunSQL "Delete * from S_Properties Where S_Properties.Record_Num=" & Me.List10
                    DoCmd.RunSQL "Delete * from C_Type Where C_Type.Record_Num=" & Me.List10
                    DoCmd.RunSQL "Delete * from C_Measurement Where C_Measurement.Record_Num=" & Me.List10
                    DoCmd.RunSQL "Delete * from C Where C.Record_Num=" & Me.List10
                    DoCmd.RunSQL "Delete * from C_Position Where C_Position.Record_Num=" & Me.List10
                    Me.List10.Requery
            End If
            DoCmd.SetWarnings True

   End If End Sub

I tried this following code but did not work:
I am getting error 3075 missing operator at S_properties
Option Compare Database

 Dim db As Database
 Dim sSQL As String
Private Sub Delete_Record_Click()
    If IsNull(Me.Child15) Then
       MsgBox "Please select a record from the list to delete", vbCritical
    Else

        DoCmd.SetWarnings False
            If MsgBox("Are you sure you want to delete this record?", vbYesNo + vbDefaultButton2 + vbCritical, "Warning") = vbYes Then
                    DoCmd.RunSQL ("Delete * from Ref Where Ref.Record_Num=" & Me.[Child15].Form![Record_Num] & ";")
                    DoCmd.RunSQL ("Delete * from S_Properties Where S_Properties.Record_Num=" & Me.[Child15].Form![Record_Num] & ";")
                    DoCmd.RunSQL ("Delete * from C_Type Where C_Type.Record_Num=" & Me.[Child15].Form![Record_Num] & ";")
                    DoCmd.RunSQL ("Delete * from C_Measurement Where C_Measurement.Record_Num=" & Me.[Child15].Form![Record_Num] & ";")
                    DoCmd.RunSQL ("Delete * from C Where C.Record_Num=" & Me.[Child15].Form![Record_Num] & ";")
                    DoCmd.RunSQL ("Delete * from C_Position Where C_Position.Record_Num=" & Me.[Child15].Form![Record_Num] & ";")
                    Me.Child15.Requery
            End If
            DoCmd.SetWarnings True

   End If
End Sub


text:
Q: How do I unmarshal a JSON string containing a UTF-8 Byte Order Mark (BOM)? So, I kind of already solved the problem I'm having. It has to do with whether or not I use encoding on my C# client's StreamWriter, but I want to know how to handle these extra 3 bytes regardless.
This is a client written in C# and a server written in Go. Why C#? It will have Unity applications later for cloud stuff. Why Go? I just wanted to use it. Also my server box is Linux and Go is easy to x-compile.
The problem was that the data being sent from my C# client was having 3 extra bytes appended to the front which conflicted with Go's Json.Unmarshal function feeding it in directly once this data arrived at the server.
This is the JSON formatted string leaving the C# client
{"channel":0, "data": {"name":"Hasty Wombat","uuid":"e91ccc23-7e80-4189-958e-9b778dce1146","type":"Drone"}}\n
This is the byte array before going through the stream writer configured with UTF8 in the C# client.
_sWriter = new StreamWriter(_tStream, System.Text.Encoding.UTF8, 8192);
Length: 108
123 34 99 104 97 110 110 101 108 34 58 48 44 32 34 100 97 116 97 34 58 32 123 34 110 97 109 101 34 58 34 72 97 115 116 121 32 87 111 109 98 97 116 34 44 34 117 117 105 100 34 58 34 101 57 49 99 99 99 50 51 45 55 101 56 48 45 52 49 56 57 45 57 53 56 101 45 57 98 55 55 56 100 99 101 49 49 52 54 34 44 34 116 121 112 101 34 58 34 68 114 111 110 101 34 125 125 10

And when it arrives at my Go server, it looks like this:
Length: 111
[239 187 191 123 34 99 104 97 110 110 101 108 34 58 48 44 32 34 100 97 116 97 34 58 32 123 34 110 97 109 101 34 58 34 72 97 115 116 121 32 87 111 109 98 97 116 34 44 34 117 117 105 100 34 58 34 50 99 57 49 48 97 99 98 45 53 101 101 102 45 52 98 56 101 45 56 52 50 54 45 54 49 102 100 100 99 99 51 101 51 55 100 34 44 34 116 121 112 101 34 58 34 68 114 111 110 101 34 125 125 10]

From my quick research, those 3 extra bytes being added at the front have something to do with the byte order regarding UTF8. That's fine, but it's interfering with my ability to unmarshal this JSON byte array into a map.
func handleRequest (conn net.Conn) {

  for {
    data, err := bufio.NewReader(conn).ReadBytes('\n');
    if err != nil {
      fmt.Println("Client disconnect")
      conn.Close()
      return
    }

    var mappedData map[string]interface{}
    err = json.Unmarshal(data, &mappedData)
    if err != nil {
      fmt.Println("err:", err)
      continue
    }

  // ...
  }
}

err: invalid character 'ï' looking for beginning of value

The Json.Unmarshal function in Go doesn't like that byte array. At first my workaround was to just slice off the first 3 bytes. But, that causes problems when I started added Go clients whose TCP output isn't adding those 3 bytes.
The obvious workaround is to just not use UTF8 in my StreamWriter on the C# client.
// NetworkManager.cs

_tcpconn = new TCPConnection(_ipAddress, _port, OnConnectionFailure);

if (_tcpconn.SetupSocket()) {

var data = "{\"channel\":0, \"data\": {" +
  "\"name\":" + "\"" + _clientName + "\"," +
  "\"uuid\":" + "\"" + _uuid + "\"," +
  "\"type\":" + "\"Drone\"" +
"}}" + "\n";

_tcpconn.WriteSocket(data);

// TCPConnection.cs

public bool SetupSocket () {
  try {
    _socket = new TcpClient(_conHost, _conPort);

    _tStream = _socket.GetStream();
    // _sWriter = new StreamWriter(_tStream, System.Text.Encoding.UTF8, 8192);
    _sWriter = new StreamWriter(_tStream); // Fixed my problem
    _sReader = new StreamReader(_tStream);
  }
  catch (Exception e) {
    throw new Exception("Socket error:" + e.Message);
    return false;
  }
  _socketReady = true;
  return true;
}

public void WriteSocket (string theLine) {
  if (!_socketReady)
  return;

  try {
    _sWriter.Write(theLine);
    _sWriter.Flush();
  }
  catch {
    _socketReady = false;
    _onConnectionFailure();
  }
}

Now I want to know if Go has something that properly decodes a UTF8 byte array or something that correctly detects those extra bytes (or any extra encoding bytes really), and give me the raw JSON the Json.Unmarshal function wants. I'm trying to have my Stream Writer setup to be versatile, but I'm not sure yet if I'll ever need something encoded UTF8 or what the advantages are.

A: UTF-8 has a well-defined byte order.  There's no such thing as big-endian UTF-8 vs little-endian UTF-8; there is only UTF-8.  This means that a byte order marker or BOM in UTF-8 is pointless.  Some software thinks it's pointful: that it marks a data file as being stored in UTF-8 (vs UTF-16-LE or UTF-16-BE, each of which would start with the two bytes 0xFF and 0xFE but in either order, if that UTF-16-xx file has a BOM).  As long as you agree that such software is wrong, don't use it, or use it in a way that defeats this initial BOM.
As Jim B noted, systems that generate JSON text must not embed a UTF-8-ized BOM (which comes out as the three bytes 0xEF, 0xBB, 0xBF) at the front of its output.  However, it may accept and ignore a BOM at the start of a stream.  To do that in Go, inspect the incoming stream data and remove an initial BOM if present, passing the rest of the data on as the JSON bytes.  But you're probably better off making your C# code generate allowed output, rather than fancying up your Go code to allow forbidden input.


text:
Q: Alpine netboot APKs at boot time I new to alpine linux, so I didn't really grasped the concept of it yet.
What I want to accomplish is a netboot alpine with apks that aren't included in the alpine-base pkg. For example sudo python3
I managed to boot alpine with dnsmasq's tftp server and lighttpd.
As far I understand I can provide an overlay.tar.gz in cmdline.txt. If i add the alpine repo to /etc/apk/repositories and then apk add the pkgs then save the overlay and boot with it, it will have the pkgs I need.
But then it will load them from the external alpine repos.
What I want is to have them served with my http server.
What is the best way to do this?
I figured I could maybe add the pkgs in the APKINDEX.tar.gz and the corresponding .apk-s to the http server.
But this doesn't really seem to be a good solution in my opinion.
Or is it?
Or maybe I should make a custom alpine image and then boot that?
Any help would be much appreciated, because I don't think I even managed to formulate the problem, since I didn't really found anything on the internet yet.

A: Found the easyest solution:
Serving an extra repository with the http server with the needed packages, adding the repository to /etc/apk/repositories, and including the packages in /etc/apk/world.
This way when it boots it will install the additional packages from the extra repository.


text:
Q: how to place indent in navigation drawer menu in android application I want to create menu like Google play store application as I have shown in image.
Difficulty which I am facing right now is placing indent space in menu to create second level menu in application.

Here is code what i am using right now .

acivity_main_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_camara"
            android:icon="@android:drawable/ic_menu_camera"
            android:title="Import" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@android:drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@android:drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@android:drawable/ic_menu_manage"
            android:title="Tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@android:drawable/ic_menu_send"
                android:title="Send" />
        </menu>
    </item>

</menu>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

MainActivity.java

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);

        //How to change elements in the header programatically
        View headerView = navigationView.getHeaderView(0);
        TextView emailText = (TextView) headerView.findViewById(R.id.email);
        emailText.setText("newemail@email.com");

        navigationView.setNavigationItemSelectedListener(this);

A: Here is an example of a RecyclerView adapter that I have in my menu.
Here I have two item types - selected and regular. You will probably have 4 types
 - regular item
 - regular selected
 - sub item
 - sub selected
 public class MenuItemAdapter extends RecyclerView.Adapter<MenuItemHolder> {

        private static final int VIEW_ITEM_SELECTED = 0;
        private static final int VIEW_ITEM_UNSELECTED = 1;

        private static final int MESSAGES_POSITION = 0;
        private static final int HOME_POSITION = 1;
        private static final int SEARCH_POSITION = 2;
        private static final int FAVORITES_POSITION = 3;

        private final ItemHolder.OnItemClickListener onItemClickListener;

        public final int[] MENU_TEXTS = {
                R.string.messages_menu_item_title,
                R.string.home_menu_item_title,
                R.string.search_menu_item_title,
                R.string.favorites_menu_item_title,

        };

        private static ArrayList<Integer> MENU_IMAGES;

        private int selectedPosition = 1;

        public MenuItemAdapter(ItemHolder.OnItemClickListener listener) {

            this.onItemClickListener = listener;
            MENU_IMAGES = new ArrayList<>();

            MENU_IMAGES.add(R.drawable.messages);
            MENU_IMAGES.add(R.drawable.home_yellow);
            MENU_IMAGES.add(R.drawable.search);
            MENU_IMAGES.add(R.drawable.favorites);

        }

        // Create new views (invoked by the layout manager)
        @Override
        public MenuItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // create a new view
            View v = null;
            switch (viewType){
                case VIEW_ITEM_SELECTED :
                   v = LayoutInflater.from
                           (parent.getContext()).inflate(R.layout.menu_item_selected, parent, false);
                    break;
                case VIEW_ITEM_UNSELECTED :
                    v = LayoutInflater.from
                            (parent.getContext()).inflate(R.layout.menu_item_unselected, parent, false);
            }

            return new MenuItemHolder(v, (position, view) -> {
                onItemClickListener.onItemClick(position, view);
                selectedPosition = position;
                MenuItemAdapter.this.notifyDataSetChanged();
            });
        }

        @Override
        public void onBindViewHolder(MenuItemHolder holder, int position) {
            holder.title.setText(MENU_TEXTS[position]);
            holder.image.setImageResource(MENU_IMAGES.get(position));
        }

        @Override
        public int getItemCount() {
            return MENU_TEXTS.length;
        }

        @Override
        public int getItemViewType(int position){
            if (position == selectedPosition){
                return VIEW_ITEM_SELECTED;
            }
            return VIEW_ITEM_UNSELECTED;
        }

        public void setHomePosition(){
            selectedPosition = HOME_POSITION
            notifyItemChanged(selectedPosition);
        }

        ...

A: Instead of using the new NavigationView, which is ment to be simple, easy to use and preserve design guidlines, you can put a Fragment as your menu.
In that Fragment put a RecyclerView with 2 ViewTypes: 1 for indented item and 1 for a regular not indented.


text:
Q: Does underscore character in python variable names matter to the interpreter? I have seen underscore character used in python variables. Does the interpreter interpret variables differently with presence of underscore _ or is it purely a matter of convention? If it's convention, is there a standard document on the naming convention in python variables?
I'm using python 3.8.5

A: *

*Single Leading Underscore: _var
The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8.

*Single Trailing Underscore: var_
Sometimes the most fitting name for a variable is already taken by a keyword. Therefore names like class or def cannot be used as variable names in Python. In this case you can append a single underscore to break the naming conflict.

*Double Leading Underscore: __var
With Python class attributes (variables and methods) that start with double underscores, things are a little different.
A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses.
This is also called name mangling—the interpreter changes the name of the variable in a way that makes it harder to create collisions when the class is extended later.

*Double Leading and Trailing Underscore: var
Perhaps surprisingly, name mangling is not applied if a name starts and ends with double underscores. Variables surrounded by a double underscore prefix and postfix are left unscathed by the Python interpeter.
These paragraphs are taken from https://dbader.org/. Please check the page for more detailed information and examples.

A: By convention, a variable beginning with a single underscore as in _some_var is considered private - meaning that external entities should not expect its use to remain stable across releases or ever be in any generally sane state. Its slightly more than just convention. from somemodule import * will not add these "private" variables to the module namespace.
From PEP8, the standard style guide for python:

[T]he following special forms using leading or trailing underscores
are recognized (these can generally be combined with any case
convention):
_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose names start with an underscore.


text: Q: calling javascript function inside div I am following the Google Map API tutorial here, specifically the JAVASCRIPT + HTML version. I believe the relevant part would be


text:
Q: cakephp path to root for javascript I need to create a javascript variable with the path to the css folder in the webroot for a jQuery WYSIWYG plugin which references a css.
My code into the head in the layout file
echo $this->Html->scriptBlock(sprintf('var WEBROOT_PATH = "%s";', WWW_ROOT));

bootstrap3-wysihtml5.js
var defaultOptions = $.fn.wysihtml5.defaultOptions = {
    "link": true,
    "image": true,
    "size": 'sm',
    events: {},
    parserRules: {
        classes: {
            "wysiwyg-color-silver" : 1,
        },
        tags: {
            "b":  {},
            "i":  {},
            "blockquote": {},
            "u": 1,
            "img": {
                "check_attributes": {
                    "width": "numbers",
                    "alt": "alt",
                    "src": "url",
                    "height": "numbers"
                }
            },
            "span": 1,
        }
    },
    stylesheets: [WEBROOT_PATH+"css/bootstrap3-wysiwyg5-color.css"],
    locale: "en"
};

I have tried all the cakephp constants and they all lead to the absolute path
http://localhost:8888/Users/keithpower/Documents/Website%20Projects/btstadmin/app/webroot/css/bootstrap3-wysiwyg5-color.css

the path I need is
 http://localhost:8888/btstadmin/app/webroot/css/bootstrap3-wysiwyg5-color.css

I have also tried
stylesheets: ["/css/bootstrap3-wysiwyg5-color.css"],

and I get
http://localhost:8888/css/bootstrap3-wysiwyg5-color.css


text:
Q: SSRS - Get the ReportItem!____.Name of the current item (textbox or column) I have a big report with 100+ columns named 'Column001', 'Column002' etc etc.
These columns hide depending on whether there is any data or not, and I'd like to have the last column have a right side border.
So I could do something like (in pseudocode)

= IIF(COUNT(ReportFields!Columns.Values) = CINT(RIGHT([CurrentReportItem].Name,3)), RIGHT_BORDER, NO_BORDER)

Is there any way to get the current item (ReportItem!) so that I can get it's name?

A: If you have control over the query then you can modify it to return the number of visible rows as a non-displayed new field in the result set and then compare that value at each column to decide if the border should be displayed.
If you do not have control over the query then I think you are limited to a painful series of nested IIf() statements.


text:
Q: Comparing variables in a Bash script Looking at other Bash scripts, I see people comparing variables like: $S == $T while at other times I see the variable being wrapped inside strings: "$S" == "$T".
Some experiments seem to suggest that both do the same. The demo below will print equal in both cases (tested with GNU bash, version 4.2.37):
#!/usr/bin/env bash

S="text"
T="text"

if [[ $S == $T ]]; then
  echo "equal"
fi

if [[ "$S" == "$T" ]]; then
  echo "equal"
fi

My question: if there's a difference between $S == $T and "$S" == "$T", what is it?

A: If you use [[ they are almost the same, but not quite...

When  the  ==  and  != operators are used, the string to the right of the operator is
   considered a pattern and matched according to the rules described below under Pattern
   Matching. [...]
   Any part of the pattern may be quoted to force it to be matched as a string.

If you use [ then you have to use quotes unless you know that the variables cannot be empty or contain whitespace.
Just to be on the safe side, you probably want to quote all your variables all the time.


text:
Q: Optional Input Context in dialogflow I have a voice commands such as
- turn on lights in the lounge
- turn on lights in the kitchen

The room (lounge, kitchen) and is a mandatory parameter is stored as a context variable.
My question is - is there a way to have an optional input context for an intent. If context exists, use data from it, otherwise get the user to specify the context via slot filling.
Without this feature, it seems I need to have two intents which are almost identical.
- TurnOnLights_WithContext
- TurnOnLights_WithoutContext

A: The solution is to set the default value for the parameter from the context. If the value exists in the context it will be set. If not, the user will have to specify the value via slot-filling.
See screenshots below


text:
Q: SQL join one to many - multiple tables I have a MySQL database with a table 'items'.
Each item can have multiple prices in the 'prices' table and multiple images in the 'images' table. They both have a one to many relationship to items.
I'd love to have a query that gets me all the data at once, but in with the query I came up with, I get a lot of duplicate records. If an item has 3 prices and 3 images, I get 9 rows for that item (instead of the desired 6):
My query:
SELECT * FROM items
LEFT JOIN prices
    ON items.item_id = prices.item_id
LEFT JOIN images
    ON items.item_id = images.item_id
ORDER BY items.item_id

E.g. I'd love to have:
itemid
  1    item1          price1              NULL
  1    item1          price2              NULL
  1    item1          price3              NULL
  1    item1           NULL              image1
  1    item1           NULL              image2
  1    item1           NULL              image3
  2    item2 ....

A: Your best bet here is a UNION query:
    SELECT items.item_id, items.item_name, prices.price, CAST(NULL AS VARCHAR(100)) as image
    FROM items
    LEFT JOIN prices
        ON items.item_id = prices.item_id

    UNION ALL

    SELECT items.item_id, items.item_name, NULL, images.image
    FROM items
    LEFT JOIN images
        ON items.item_id = images.item_id

This will stack each query on top of one another, which is why the CAST() is necessary in the first query as a place holder for the image data that will eventually be stacked in that same column. You may have to change that VARCHAR(100) to match whatever data type is in the images column you are pulling. Furthermore, you will probably have to change the field names since I can't see your schema.

A: Try with only join not left join, like this:
SELECT * FROM items
JOIN prices
    ON items.item_id = prices.item_id
JOIN images
    ON items.item_id = images.item_id
ORDER BY items.item_id


text:
Q: Rundeck/WINRM - Rundeck manage to connect, move file, failing executing inline powershell script Currently I am facing a very confusing issue.

*

*I am executing a job from (Rundeck) to (remote windows machine) using winrm as executor and file copier, which execute an inline powershell script.

*Tried and worked fine on one of 3 environments.

*On the Preprod, and Prod Rundeck.. Same job (exported/imported), fails, though same setting on the 3 environment, same script, same args, even same windows version.

*I added a WINRM Check connection step, and it succeeds.

*Rundeck manage to throw the script on the machine (with wrong name however), which means authentication is going well. However, it fails with this abstract error.

[ERROR  ]  Execution finished with the following error (winrm-exec.py:304)[root]
[ERROR  ]  The parameter is incorrect.  (extended fault data: {u'fault_subcode': 'w:InvalidParameter', u'fault_code': 's:Sender', u'wsmanfault_code': '87', 'transport_message': u'Bad HTTP response returned from server. Code 500', 'http_status_code': 500}) (winrm-exec.py:305)[root]
[WinRMPython]: result code: 1, success: false
Failed: NonZeroResultCode: [WinRMPython] Result code: 1

*When I try to execute the thrown Powershell script locally from the machine it works well.

WinRM plugin version: 2.0.9
Python: 2.7.17

A: For future references, the solution is here. Switching to Python 3 interpreter (instead of Python 2) on Default Node Executor and Default File Copier (Project Settings > Edit Configuration > Default Node Executor and Default File copier tabs) solves the issue.

A: Switching to python3 in WINRM resolved the problem. However, it caused problem for Windows server 2008 and older version.
So if you have both Windows OS version [pre and post 2008], you would need to split RUNDECK projects, and have winrm available on both python2 and python3.


text:
Q: How to use adobe's pdf reader on chrome I want to disable the pdf plugin built into Google Chrome, and use the official one by adobe. I was able to disable the built in plugin, I don't know where to get the alternative plugin. Where can I get it?

A: You can also download the oficial PDF from Adobe. Just go to their website and download Adobe Reader .deb: http://get.adobe.com/br/reader/otherversions/
Because if you've disabled the built-in PDF viewer, Chrome will use Adobe Acrobat or Adobe Reader to display PDFs
More info on this can be found here: http://support.google.com/chrome/bin/answer.py?hl=en&answer=142056

A: the latest solution can be found here: https://support.google.com/chrome/answer/142056?hl=en
But most oficial Adobe pdf plugin is charged.Is it possiable for us to find other pdf add-on to enable Chrome to read PDF files?After searching from internet ,I got pdf add-on for web viewer ,but It seems not working.
Any free pdf add-on works ?


text:
Q: Sfinae on function with either zero or one parameter Consider the two following declarations:
template <class Function,
          class = typename std::enable_if</*Function has zero argument*/>::type>
void apply(Function&& function);
template <class Function,
          class... Dummy,
          class = typename std::enable_if</*Function has one argument*/>::type,
          class = typename std::enable_if<sizeof...(Dummy) == 0>::type>
void apply(Function&& function, Dummy...);

What should I put in the std::enable_if in the first and second case to constrain the overload when the function has zero or one argument (regardless the type of the argument)?

A: Following traits may help you:
#include <type_traits>
#include <functional>

template <typename T>
struct arity : public arity<decltype(&T::operator())> {};

template <typename C, typename Ret, typename... Args>
struct arity<Ret(C::*)(Args...) const> :
    std::integral_constant<std::size_t, sizeof...(Args)>
{
};

// Do the same for other (11) combination of volatile, const, reference method.

// function pointer
template<class R, class... Args>
struct arity<R(*)(Args...)> : public arity<R(Args...)>
{};

template<class R, class... Args>
struct arity<R(Args...)> : std::integral_constant<std::size_t, sizeof...(Args)>
{
};

And then
template <class Function,
          class = typename std::enable_if<arity<typename std::remove_reference<Function>::type>::value == 0>::type>
void apply(Function&& function);


text:
Q: How to create date fields on the fly using symfony/doctrine I have a user database, and when a new user signs up, I store the name, age, address ... but there is a field in my databases named created_at which should store the time when the user is registerd. In plain php I used to do it like:
INSERT INTO users (name, created) VALUES (?, NOW())

But with symfony doctrine does everything and I don't know how to alter the entity or database to create the date using something equivallent to NOW()

A: Add it into the constructor for the class:
public function __construct()
{
    $this->created = new \DateTime;
}


text:
Q: How does jquery mobile inject classes in HTML? I am building a jqm/backbone app.
I have this HTML in a backbone template, loaded into a backbone view :

Test2

testmodeledit

At first rendering, this shows a grey header. When the view model changes, and so the view renders again the template, the grey background color is lost.
I noticed that at first rendering, the html looks like this :

Test2

testmodeledit

I guess that JQM injected the classes in header and that it doesn't reinject them upon template re-rendering.
How and when does JQM inject those classes and how can I "refresh" this inject when I re-render my template ?

A: use a .trigger("create"); on your data-role='page'.


text:
Q: Trying to remove bad data using countif function First, thank you for the help in solving this problem. It's pretty simple but I'm just not getting it.
In excel, I have 2 tabs. In the first tab, I have rows of personel data (job title, country of business, Industry, etc.)
In the second tab, I have a column of prohibited titles. These are titles that don't match the criteria we want.
I'd like to create a formula that checks the rows in tab 1 against the prohibited titles in tab 2. If the data matches, I'd like it to return 'N' in column A, which signals that we should remove that row of data. Title information is found in row F on tab 1.
My various countif functions aren't working and I'm not sure why.
Various countif formulas, like
=COUNTIF(F:F,"'Bad Titles!'A:A")
Produces N for all titles we want to disregard

A: Use MATCH it is quicker:
=IF(ISNUMBER(MATCH(F2,'Bad Titles!'A:A,0)),"N","")

If the matches are partial then:
=IF(SUMPRODUCT(--ISNUMBER(SEARCH('Bad Titles!'$A$1:$A$100,F2))),"N","")


text:
Q: jquery select THIS id inside li How to use "THIS" in the right way in order to select an ID inside "li"?

text

$("li.item").hover(function () {
        $("#sale_container").fadeIn(400);
    })
    $("li.item").mouseleave(function () {
        $("#sale_container").fadeOut(400);
    })

How ever it affects all li with class "item". So, i want it to take affect inside each li, when mouse is over.
This example doesn't work
$("li.item").hover(function () {
    $(this)("#sale_container").fadeIn(400);
})
$("li.item").mouseleave(function () {
    $(this)("#sale_container").fadeOut(400);
})

A: Since IDs are unique, you only need to use $('#sale_container') without any other qualifiers.
Assume you are not using an ID, then you'd use:
$(this).find(...).fadeIn(400); "..." being a selector of what you're looking for inside, which could be ("div") or a (".myClassname") etc.

A: Replace:
$(this)("#sale_container").fadeIn(400);

With:
$(this).find("#sale_container").fadeIn(400);

Or even:
$(this).children().fadeIn(400); // will fade any element inside .item

Note that you can only have one unique ID on one page.

A: You can use this code:
$("li.item").hover(function () {
    $(this).find("#sale_container").fadeIn(400);
});

A: Use the find function to find an element contained inside the parent element (this).
$("li.item").hover(function () {
    $(this).find("#sale_container").fadeIn(400);
})

A:  $("li.item").hover(function () {
        $("#sale_container",$(this)).fadeIn(400);
    }, function () {
       $("#sale_container",$(this)).fadeOut(400);
    });

FIDDLE Demo


text:
Q: php foreach how to filter image names to display certain images you want Files are

AAA_1.jpg AAA_2.jpg AAA_3.jpg BBB_1.jpg BBB_2.jpg CCC_1.jpg

foreach ($carousel as $image) {
    echo "";
}

How to filter image names, just to display AAA_ images.
result to see

A: There are a probalby a million ways to do this, but I would just check the name of the image to see it begins with 'AAA_'
foreach ($carousel as $image) {
    if(strpos($image,'AAA_') === 0){
      echo "";
   }
}

Or more complex, but still fun, entertainingly worth the extra performance hit of explode:
foreach ($carousel as $image) {
   $image_parts = explode('_', $image);
   if($image_parts[0] == 'AAA'){
      echo "";
   }
}

A: foreach ($carousel as $image) {
    if(substr($image, 0, 3) == 'AAA'( {
        echo "";
    }
}

A: If you know all your file, you can use that code, also use in_array ;-)
$carousel = array('AAA_1.jpg', 'AAA_2.jpg', 'AAA_3.jpg','BBB_1.jpg','BBB_2.jpg','CCC_1.jpg');
$entry = array('AAA_1.jpg', 'AAA_2.jpg', 'AAA_3.jpg');

foreach ($carousel as $image) {
    if(in_array($image, $entry)) {
        echo "";
    }
}

A: By using substr and strlen you will be able to get the images you want starting with the prefix variables value.
$prefix = 'AAA_';

$carousel = array(
   "AAA_1.jpg",
   "AAA_2.jpg",
   "AAA_3.jpg",
   "BBB_1.jpg",
   "BBB_2.jpg",
   "CCC_1.jpg"
);

foreach ($carousel as $k => $v) {
   if (substr($v, 0, strlen($prefix)) == $prefix) {
      echo "";
   }
}


text:
Q: A disabled but readable input So I have two forms, one is for creating and the other for editing. Both using method="post".
There's one difference between both, which is the code_product, that is generated via php's rand() function, used only when creating a product (so there's no code_product input here).
And when editing it, the code_product value is shown inside of an additional input at the top of the entire form.
Objective: code_product's input mustn't be edited.
Problem: Using the disabled attribute makes it unreadable for php too.
Avoiding the asp.net (mentioned in another post), is there another way to make it uneditable, through css or javascript?

A: Add an attribute called readonly to your input elements. This way it cant be edited but still viewed as normal.
<input type="text" readonly />

For older browsers, you will need
<input type="text" readonly="readonly" />


text:
Q: Is it better to use or to extend a class? (swift) I want a Panel that contains colors to be a UIVisualEffectView. So, blur background and buttons. Like this:

Should I create a ColorPanelView class that extends UIVisualEffectView (or UIView?) or a ColorPanel class that uses a UIVisualEffectView?
What are the differences and which way is better?

A: If I understand correctly, you're asking if you should make a custom view that subclasses UIVisualEffectView or if you should just add a UIVisualEffectView to an existing view.
If my understanding is correct, then the answer depends on if you need to reuse this view  anywhere else in your code. By making a custom subclass of UIVisualEffectView that has your panels on it, you can easily reuse it without repeating much code.
If you know you'll only need it once, you can just add a UIVisualEffectView to an existing view and then customize it the way you want it.

A: Either will work.
In this case I would just extend UIView instead of UIVisualEffectView. The reason being is that if the design changes and you want the color panel to be on a solid background instead of a blurred background, you can make that change without changing the class you're extending from.


text:
Q: Customize the FF DOM Inspector How can I customize the Firefox DOM Inspector? The white color and the font size makes it difficult to read.

A: I found a solution. I used Stylish addon
https://addons.mozilla.org/en-US/firefox/addon/stylish/
@namespace url(http://www.w3.org/1999/xhtml);

@-moz-document url("chrome://browser/content/devtools/markup-view.xhtml") {

body { background: white !important }

}

The above is a sample for the background only. Another css example is one below.
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

* {
  padding: 0;
  margin: 0;
}

body {
  color: hsl(0,0%,50%);
  background: black !important;
}

.text {
  color: white !important;
}

.newattr {
  cursor: pointer;
}

.selected {
  background-color: hsl(0,0%,90%);
}

/* Give some padding to focusable elements to match the editor input
 * that will replace them. */
span[tabindex] {
  display: inline-block;
  padding: 1px 0;
}

li.container {
  position: relative;
  padding: 2px 0 0 2px;
}

.codebox {
  padding-left: 14px;
}

.expander {
  position: absolute;
  -moz-appearance: treetwisty;
  top: 0;
  left: 0;
  width: 14px;
  height: 14px;
}

.expander[expanded] {
  -moz-appearance: treetwistyopen;
}

.more-nodes {
  padding-left: 16px;
}

.styleinspector-propertyeditor {
  border: 1px solid #CCC;
}

}

Source


text:
Q: One-to-Many Mongoose relationship - Where to store the reference I'm designing the MongoDB collection architecture for a new project, and being new to MongoDB, I had a question about a one-to-many relationship.
For the sake of this example, lets say the relationship is Datacenter-to-Servers, meaning one Datacenter can have multiple servers (thousands, not limited in the app), and the servers can only belong to one Datacenter.
Would it be best to have Servers._datacenter referencing the Datacenter._id? Or a Datacenter.servers array to store the server ID's?
If you suggest having an array in the Datacenter documents to reference what server ID's are associated to it... Then is there a way to find out what Datacenter a server belongs to when you just have the server ID? (Kinda like a quick where serverId in Datacenter.servers query) without having to query every Datacenter, and then check for the ID in every Datacenter.servers array
If you suggest having an element in the Servers documents to reference what Datacenter it belongs to, then is there a way to query for the Datacenter, and return all of the associated Server documents inside a virtual Documents.servers array or something?
Im not quite sure what the best route to take is, since there can be a very very large amount of servers for each datacenter, I think it may be a better idea to not have such a large array inside each Datacenter document...  But then if I set it up so that each Server document has the parent Datacenter referenced in it, that makes queries rather difficult (Or not? Maybe theres a very easy way I just haven't discovered, I did say I'm new to Mongo)
I was reading through this document, and it shows how set the reference direction up either way, and it states:

To avoid mutable, growing arrays, store the publisher reference inside the book document

So that makes me think it would be best to reference the Datacenter ID's in the Server documents.. So if thats the case, is there a way to return all the server documents as an array inside the Datacenter documents? Or would I have to query for the Datacenter, then query for all the Servers with that Datacenter._id, then return a merged object..

A: It would depend on the access pattern. How you are planning to code this as null1941 said.
If the number of servers are in 10s or hundreds I guess that would be a one to few relationship instead of one to many so you could go ahead and embed datacenters inside of servers. This means you will be getting all the information you need in one go and a single query.
This approach could work if you can guarantee consistency but you will end up having duplication given many servers exist in one datacenter. So datacenter document could be duplicated in many server document. This approach can work if again you can guarantee consistency and that datacenters maybe have few information on them. The only advantage with this approach is that you only be doing one query.
Generally this approach is not recommended; also if you want to treat datacenter as a separate document such that you want to run some operations on it than avoid this approach.
if you decided to go for this approach; To embed datacenter as an array You can use $all or $in to search inside the array.
example:
{
"_id" : ObjectId("63546464sad65s4ad3654"),
"name" : "Server1",
"datacenter" : ["gamma", "500"]

}

query:
db.users.find({ "datacenter": { $in: [ "gamma", "delta" ] } } )

if you decided to embed servers as a document (you can embed datacenter document as well inside servers both can work). So for embedding servers inside of datacenter document, you could search inside the embedded document using the dot notation. example:(servers is the dictionary, name is an attribute inside of servers):
{
"_id" : ObjectId("63546464sad65s4ad3654"),
"name" : "gamma",
"servers" : [
            {
              "title" : "server1",
              "speed" : "3.2GHZ",
              "ram"   : "200GB"
            },
            {
              "title" : "server2",
              "speed" : "3.2GHZ",
              "ram"   : "64GB"
            }
         ]
}

query:
db.datacenters.find( { "servers.title": "server1" }

Again you judge. However you decide to do it there is a way in mongodb to retrieve the information you need.
Now keep in mind that if you decided to go for embedding servers inside of datacenter document that in mongodb a single document should not exceed 16MB. If by embedding this size could be exceeded you should go splitting approach (below).
Now the better approach for your is the case which is not embedding; basically as gnerkus said. However keep in mind that there is no foreign key constraints in mongodb you have to ensure consistency using the application. Such that server_id in datacenter collection could be found in server collection (and vise versa). You could also put datacenter_id inside of server collection; my way of deciding which one to go for is my use case. For example if most of my operations are on datacenters I will add server_id to it. if most of my operations are on the server collection I will add datacenter_id to it. In both cases you will be doing two or more queries. Here is an example:
Datacenter document example
 {
     _id : ObjectId("10001000010000"),
     name : 'Gamma',
     location: 'pluto',
     servers: [
         ObjectID('1212'),
         ObjectID('1213')
              ]
 }

Servers document example:
{
    _id : ObjectId("1212"),
    name : 'Server1',
    ram: '250GB',
    type: 'processing',
    status: 'running'
}

In this case you could query as: First you get the datacenter you need (assuming name is unique)
datacenter = db.datacenter.findOne({name: "Gamma"})

then you will query for the servers' details you need; example to get all servers in the given datacenter above
servers = db.servers.find({_id: { $in : datacenter.servers } } )

after you have all the servers you can loop through each and check the status or something. You will end up having the server documents in servers variable.
I hope that helps

A: It is best to reference the Datacenter IDs in the Server documents. To retrieve the servers with the specified datacenter's ID, you'll simply query the server collection. The query isn't difficult and looks like this:
var dataID = datacenter._id

db.servercollection.find({ datacenter: dataID }, function(err, servers) {

});


text:
Q: Rails how to get @products in the controller to be passed to another Java Script I am getting my products index from another custom developed class which is passed to the index.html.erb for rendering in a table format, using DataTables and JavaScript in the index.html.erb page. This code is woking very well so far, doing pagination, sorting and filtering on the server side, but now I want to get a @products variable from the JSON used by DataTables which I want to process it in the ProductsController before it is passed as a @hash to another JavaScript eventualy to render the @markers of the @products on a Google Map.
Here is my code:
products_controller.rb
...
  def index
    respond_to do |format|
      format.html
      format.json { render json: ProductsDatatable.new(view_context) }
    end
  end
...

index.html.erb

Products

      <table id="products" width="100%" class="display cell-border compact hover order-column row-border stripe" data-source="<%= products_url(format: "json") %>">

            Product ID
            Product Name
            Category
            Release Date
            Price
            Created At
            Updated At

Custom class fetching the records from server with pagination, sorting and filtering.

`/datatables/products_datatables.rb`

class ProductsDatatable
  delegate :params, :link_to, :number_to_currency, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: Product.count,
      iTotalDisplayRecords: products.total_entries,
      aaData: data
    }
  end

private

  def data
    products.map do |product|
      [
        link_to(product.id, product),
        product.product_name,
        product.category,
        product.release_date.strftime("%Y-%m-%d"),
        number_to_currency(product.price),
        product.created_at.strftime("%Y-%m-%d %I:%M%p"),
        product.updated_at.strftime("%Y-%m-%d %I:%M%p")
      ]
    end
  end

  def products
    @products ||= fetch_products
  end

  def fetch_products #this version genertes more optimized queries for the db
    if params[:sSearch].present?
      products = Product
      .where("product_name like :search
        or category like :search
        or date_format(release_date, '%Y-%m-%d') like :search
        ", search: "%#{params[:sSearch]}%"
      )
      .order("#{sort_by}")
      .page(page).per_page(per_page)
    else
      products = Product
      .order("#{sort_by}")
      .page(page).per_page(per_page)
    end
    products
  end

  def page
    params[:iDisplayStart].to_i/per_page + 1
  end

  def per_page
    params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
  end

  def sort_by
    columns = %W[id product_name category release_date price created_at updated_at]
    s = String.new
    if params[:iSortCol_0].present?
      s = s + "," + columns[params[:iSortCol_0].to_i] + " " + sort_direction(params[:sSortDir_0])
    end
    if params[:iSortCol_1].present?
      s = s + "," + columns[params[:iSortCol_1].to_i] + " " + sort_direction(params[:sSortDir_1])
    end
    if params[:iSortCol_2].present?
      s = s + "," + columns[params[:iSortCol_2].to_i] + " " + sort_direction(params[:sSortDir_2])
    end
    if params[:iSortCol_3].present?
      s = s + "," + columns[params[:iSortCol_3].to_i] + " " + sort_direction(params[:sSortDir_3])
    end
    if params[:iSortCol_4].present?
      s = s + "," + columns[params[:iSortCol_4].to_i] + " " + sort_direction(params[:sSortDir_4])
    end
    if s.empty?
      s = columns[params[:iSortCol_0].to_i] + " " + sort_direction(params[:sSortDir_0])
    end
    if s[0] == ","
      s.slice!(0)
    end
    s
  end

  def sort_direction (n)
    n == "desc" ? "desc" : "asc"
  end
end

How i can get the @products in the controller, such a way when user navigates between the pages index pages, to have the content of @products changed accordingly?

A: If I'm reading this correctly, you can't do exactly what you're proposing. You're dealing with 2 requests. You can expose the data or even the JSON from your ProductsDataTable class as a controller instance variable easily enough and write it into a JavaScript variable in a script tag in the template, but as it sits, you'll still get a second call to get the JSON as soon as the data table initializes.
It looks as though what you're trying to do can be accomplished completely in JavaScript. You can pass an initComplete option to the data table as in https://datatables.net/reference/option/initComplete. This will call the passed callback when the data has been retrieved.
This will make the JSON data in the table available in the json variable passed to your specified callback function. You can then initialize your map in the callback.

A: Here is the kind of solution I was expecting.
In the controller, one single line of code:
@json = ProductsDatatable.new(view_context).as_json

This makes data available for further processing like this example below.
You can display the entire JSON object:
<%= @json %>

And slice and dice as wished this json object further.
Total Records Count: <%= @json[:iTotalRecords] %>
aaData class: <%= @json[:aaData].class %>
aaData count: <%= @json[:aaData].count %>
aaData first class: <%= @json[:aaData].first.class %>
aaData first content: <%= @json[:aaData].first %>
aaData first content product Product ID (link): <%= @json[:aaData].first[0] %>
aaData first content product Product Name: <%= @json[:aaData].first[1] %>

The problem now is that when the page is changed (through table pagination) only the first 10 records are visible not the current 10 records from pages 5, 7, 10, etc.

A: Here is the same old problem persisting even after I received advise and I reworked the code. When I am using the navigation buttons for the data table to move to another page, first, last, previous, next etc, the table content changes accordingly, but the map shows always the same first 10 products.
The Google Map is never changing when the content rendered in the table changes. How I can fix this?Don't know how to change my code to make it working properly?
What I need is to have the @hash content changing when the @products is changed with the pagination. How this can be done?
products_controller.rb
class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  # GET /products
  # GET /products.json
  def index

    if params[:sSearch].present?
      @products = Product
      .where("product_name like :search
        or category like :search
        or date_format(release_date, '%Y-%m-%d') like :search
        ", search: "%#{params[:sSearch]}%"
      )
      .order("#{sort_by}")
      .page(page).per_page(per_page)
    else
      @products = Product
      .order("#{sort_by}")
      .page(page).per_page(per_page)
    end

    @hash = Gmaps4rails.build_markers(@products) do |product, marker|
      marker.lat product.lat || 0.0
      marker.lng product.lng || 0.0
      title = product.product_name
      marker.infowindow make_content_for_infowindow(product)
      marker.json({:title => title})
    end

    @products_data = @products.map do |product|
      [
        product.id,
        product.created_at.strftime("%Y-%m-%d %H:%M:%S %Z"),
        product.updated_at.strftime("%Y-%m-%d %H:%M:%S %Z"),
        product.product_name,
        product.category,
        product.release_date ? product.release_date.strftime("%Y-%m-%d") : nil,
        product.price,
        product.current_location,
        product.lat,
        product.lng
      ]
    end

    @json = {
      "sEcho"               => params[:sEcho].to_i,
      "iTotalRecords"       => @products.count,
      "iTotalDisplayRecords"=> @products.total_entries,
      "aaData"              => @products_data.as_json
    }

    respond_to do |format|
      format.html
      format.json { render :json=> @json }
    end
  end

  # GET /products/1
  # GET /products/1.json
  def show
  end

  # GET /products/new
  def new
    @product = Product.new
  end

  # GET /products/1/edit
  def edit
  end

  # POST /products
  # POST /products.json
  def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /products/1
  # PATCH/PUT /products/1.json
  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { render :show, status: :ok, location: @product }
      else
        format.html { render :edit }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /products/1
  # DELETE /products/1.json
  def destroy
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_product
      @product = Product.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def product_params
      params.fetch(:product, {})
    end

    def page
      params[:iDisplayStart].to_i/per_page + 1
    end

    def per_page
      params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
    end

    def sort_by
      #these should be enumerated in the same order as they appear rendered in the table from left to right
      columns = %W[id created_at updated_at product_name category release_date price current_location lat lng]
      s = String.new
      if params[:iSortCol_0].present?
        s = s + "," + columns[params[:iSortCol_0].to_i] + " " + sort_direction(params[:sSortDir_0])
      end
      if params[:iSortCol_1].present?
        s = s + "," + columns[params[:iSortCol_1].to_i] + " " + sort_direction(params[:sSortDir_1])
      end
      if params[:iSortCol_2].present?
        s = s + "," + columns[params[:iSortCol_2].to_i] + " " + sort_direction(params[:sSortDir_2])
      end
      if params[:iSortCol_3].present?
        s = s + "," + columns[params[:iSortCol_3].to_i] + " " + sort_direction(params[:sSortDir_3])
      end
      if params[:iSortCol_4].present?
        s = s + "," + columns[params[:iSortCol_4].to_i] + " " + sort_direction(params[:sSortDir_4])
      end
      if s.empty?
        s = columns[params[:iSortCol_0].to_i] + " " + sort_direction(params[:sSortDir_0])
      end
      if s[0] == ","
        s.slice!(0)
      end
      s
    end

    def sort_direction (n)
      n == "desc" ? "desc" : "asc"
    end

    def make_content_for_infowindow(product)
      s = String.new
      s << "Name: "
      s << product.product_name
      s << " ID: "
      s << product.id.to_s
      s << " Category: "
      s << product.category
      s << " Price: "
      s << product.price.to_s
      s
    end
end

index.html.erb
div class="container-fluid">

Products

  <table id="products" width="100%" class="display cell-border compact hover order-column row-border stripe" data-source="<%= products_url(format: "json") %>">

        Product ID
        Created At
        Updated At
        Product Name
        Category
        Release Date
        Price
        Current Location
        Latitude
        Longitude

Coffee script for the Google Map to be rendered gmaps_google.js.coffee
class RichMarkerBuilder extends Gmaps.Google.Builders.Marker #inherit from builtin builder
  #override create_marker method
  create_marker: ->
    options = _.extend @marker_options(), @rich_marker_options()
    @serviceObject = new RichMarker options #assign marker to @serviceObject

  rich_marker_options: ->
    marker = document.createElement("div")
    marker.setAttribute 'class', 'marker_container'
    marker.innerHTML = @args.title
    _.extend(@marker_options(), { content: marker })

  infobox: (boxText)->
    content: boxText
    pixelOffset: new google.maps.Size(-140, 0)
    boxStyle:
      width: "400px"

  # override method
  create_infowindow: ->
    return null unless _.isString @args.infowindow
    boxText = document.createElement("div")
    boxText.setAttribute("class", 'marker_info_box') #to customize
    boxText.innerHTML = @args.infowindow
    @infowindow = new InfoBox(@infobox(boxText))

@buildMap = (markers)->
    handler = Gmaps.build 'Google', { builders: { Marker: RichMarkerBuilder} } #dependency injection

    #then standard use
    handler.buildMap { provider: {}, internal: {id: 'map'} }, ->
      markers = handler.addMarkers(markers)
      handler.bounds.extendWith(markers)
      handler.fitMapToBounds()


text:
Q: Objective-C JavaScriptCore Bind a Completion Handler with JSExport Supposed to have a completion block like
typedef void(^JSAPICallback)(id result);

and a binding class
@protocol JSProtocol<JSExport>

- (void)initAPI:(JSAPICallback)success;

@end

@interface JSObject : NSObject<JSProtocol>
- (void)initAPI:(JSAPICallback)success error:(JSAPICallback)error;
@end

@implementation JSObject
- (void)initAPI:(JSAPICallback)success  {
    [[API sharedInstance] initialize:^(id results, NSError *error) {
        if(error==nil) {
            success(results)
        } else {
            error()
       }
    }];
}
}

If I try to bind it in a JSContext in this case in a tvOS TVApplicationControllerDelegate delegate like:
- (void)appController:(TVApplicationController *)appController evaluateAppJavaScriptInContext:(JSContext *)jsContext {

    JSObject *jsObject = [[JSObject alloc] init];
    [jsContext setObject:jsObject forKeyedSubscript:@"jsobject"];
    [jsContext setExceptionHandler:^(JSContext *context, JSValue *value) {
        NSLog(@"%@", value);
    }];
}

I have a crash:
2015-10-09 23:33:16.669 TestbedTV[9707:3524754] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000011008f105 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010fb07deb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ff9206e -[__NSPlaceholderDictionary initWithObjects:forKeys:count:] + 318
    3   CoreFoundation                      0x000000010ffa43bb +[NSDictionary dictionaryWithObjects:forKeys:count:] + 59
    4   JavaScriptCore                      0x000000011905d388 -[JSObjCClassInfo allocateConstructorAndPrototype] + 2664
    5   JavaScriptCore                      0x000000011905e25f -[JSObjCClassInfo prototype] + 47
    6   JavaScriptCore                      0x000000011905e0ab -[JSObjCClassInfo wrapperForObject:] + 587
    7   JavaScriptCore                      0x000000011905e737 -[JSWrapperMap jsWrapperForObject:] + 423
    8   JavaScriptCore                      0x0000000118fdce80 -[JSContext(Internal) wrapperForObjCObject:] + 64
    9   JavaScriptCore                      0x0000000119054238 _ZL24objectToValueWithoutCopyP9JSContextP11objc_object + 760
    10  JavaScriptCore                      0x000000011905053a _Z13objectToValueP9JSContextP11objc_object + 74
    11  JavaScriptCore                      0x0000000119051ad9 -[JSValue setValue:forProperty:] + 137
    12  TestbedTV                           0x000000010eeb42cd -[AppDelegate appController:evaluateAppJavaScriptInContext:] + 141
    13  TVMLKit                             0x000000011048d3be -[TVApplicationController appContext:evaluateAppJavaScriptInContext:] + 889
    14  ITMLKit                             0x000000011b47d431 -[IKAppContext(JS) evaluateFoundationJS] + 2566
    15  ITMLKit                             0x000000011b4a56b3 -[IKAppContext _startWithScript:scriptUrl:] + 262
    16  ITMLKit                             0x000000011b4a52a5 -[IKAppContext _startWithURL:urlTrusted:] + 1277
    17  ITMLKit                             0x000000011b4a37e7 __21-[IKAppContext start]_block_invoke + 46
    18  ITMLKit                             0x000000011b4a6633 -[IKAppContext _sourcePerform] + 379
    19  ITMLKit                             0x000000011b4a647d IKRunLoopSourcePerformCallBack + 34
    20  CoreFoundation                      0x000000010ffbb1b1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    21  CoreFoundation                      0x000000010ffb10dc __CFRunLoopDoSources0 + 556
    22  CoreFoundation                      0x000000010ffb0593 __CFRunLoopRun + 867
    23  CoreFoundation                      0x000000010ffaffa8 CFRunLoopRunSpecific + 488
    24  CoreFoundation                      0x0000000110063201 CFRunLoopRun + 97
    25  ITMLKit                             0x000000011b4a62ea -[IKAppContext _jsThreadMain] + 337
    26  Foundation                          0x000000010f79224b __NSThread__start__ + 1198
    27  libsystem_pthread.dylib             0x000000011311505a _pthread_body + 131
    28  libsystem_pthread.dylib             0x0000000113114fd7 _pthread_body + 0
    29  libsystem_pthread.dylib             0x00000001131123ed thread_start + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException

It seems that the JavaScriptCore is not able to bind the completion block. Having a simple function with simple parameters like this
@protocol JSProtocol<JSExport>
- (void)initAPI:(NSString*)options;
@end

instead the binding would work as expected.
This happens in tvOS9.0, but I think it would crash in iOS9.1 as well.
The most likely question to get some idea is ObjectiveC and JavaScriptCore: Will using this method of calling CallBacks cause memory issues?.


text:
Q: Jenkins android emulator plugin creating multiple virtual devices I have a simple test android project that I can test fine using ".\gradlew calabashDebug" in a DOS shell logged in as myself. However, when I run the project under Jenkins on a Continuous Integration server it fails during calabashDebug task because there are multiple Android Virtual Devices running:
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/tools/android.bat list target
[android] Using Android SDK: C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe start-server
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/tools/emulator.exe -snapshot-list -no-window -avd hudson_en-US_213_800x1280_android-17_x86
[android] Starting Android emulator and creating initial snapshot
[android] Erasing existing emulator data...
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/tools/emulator.exe -no-boot-anim -ports 50834,50835 -avd hudson_en-US_213_800x1280_android-17_x86 -no-snapshot-load -no-snapshot-save -wipe-data
* daemon not running. starting it now on port 50836 *
* daemon started successfully *
Failed to create Context 0x3005
emulator: WARNING: Could not initialize OpenglES emulation, using software renderer.
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
could not get wglGetExtensionsStringARB
emulator: warning: opening audio output failed

$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
[android] Waiting for emulator to finish booting...
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe disconnect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe disconnect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
error: device not found
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe disconnect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell getprop dev.bootcomplete
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 logcat -v time
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
[android] Attempting to unlock emulator screen
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell input keyevent 82
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell input keyevent 4
[android] Giving the system some time to settle before creating initial snapshot...
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 logcat -c
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe -s localhost:50835 shell log -p v -t Jenkins "Creating snapshot..."
[android] Creating snapshot...
$ C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk/platform-tools/adb.exe connect localhost:50835
[android] Emulator is ready for use (took 331 seconds)
[Gradle] - Launching build.
[workspace] $ cmd.exe /C '"C:\Users\jenkins\.jenkins\jobs\Toasty\workspace\gradlew.bat calabashDebug && exit %%ERRORLEVEL%%"'
:compileDebugNdk UP-TO-DATE
:preBuild
:preDebugBuild
:checkDebugManifest
:prepareDebugDependencies
:compileDebugAidl UP-TO-DATE
:compileDebugRenderscript UP-TO-DATE
:generateDebugBuildConfig UP-TO-DATE
:mergeDebugAssets UP-TO-DATE
:generateDebugResValues UP-TO-DATE
:generateDebugResources UP-TO-DATE
:mergeDebugResources UP-TO-DATE
:processDebugManifest UP-TO-DATE
:processDebugResources UP-TO-DATE
:generateDebugSources UP-TO-DATE
:compileDebugJava UP-TO-DATE
:preDexDebug UP-TO-DATE
:dexDebug UP-TO-DATE
:processDebugJavaRes UP-TO-DATE
:validateDebugSigning
:packageDebug UP-TO-DATE
:assembleDebug UP-TO-DATE
:calabashDebug
2014-04-25 08:24:36 - JDK found on PATH.
2014-04-25 08:24:36 - JDK found at: C:\Program Files\Java\jdk1.8.0
2014-04-25 08:24:36 - Android SDK found at: C:\AndroidSDK\adt-bundle-windows-x86_64-20140321\adt-bundle-windows-x86_64-20140321\sdk
2014-04-25 08:24:37 - c:/Ruby193/bin/ruby.exe -S cucumber --format html --out C:\Users\jenkins\.jenkins\jobs\Toasty\workspace\build\reports\calabash\Debug\report.html -v MAIN_ACTIVITY=com.example.toasty.MainActivity APP_PATH="C:/Users/jenkins/.jenkins/jobs/Toasty/workspace/build/apk/workspace-debug-unaligned.apk" TEST_APP_PATH="test_servers/3ad00ebd6d3858b2667e3d4fef0e19e7_0.4.21.apk"
*** WARNING: You must use ANSICON 1.31 or higher (https://github.com/adoxa/ansicon/) to get coloured output on Windows
Code:
  * features/support/env.rb
  * features/support/app_installation_hooks.rb
  * features/support/app_life_cycle_hooks.rb
  * features/support/hooks.rb
  * features/step_definitions/calabash_steps.rb

Features:
  * features/my_first.feature
Parsing feature files took 0m0.009s

2014-04-25 08:24:38 - First scenario in feature - reinstalling apps
2014-04-25 08:24:38 - connected_devices: ["emulator-5556", "emulator-50834", "localhost:50835"]
2014-04-25 08:24:38 - connected_devices: ["emulator-5556", "emulator-50834", "localhost:50835"]
2014-04-25 08:24:38 - connected_devices: ["emulator-5556", "emulator-50834", "localhost:50835"]
:calabashDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':calabashDebug'.
> Process 'command 'cmd'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

I am using the Jenkins Android Emulator Plugin to start an android virtual device using the following configuration:

*

*Run emulator with properties

*Show emulator window

*Use emulator snapshots

Why are there mutiple devices ("emulator-5556", "emulator-50834", "localhost:50835") started by the emulator plugin?
FWIW, I am unable to get the Jenkins Android Emulator Pluginb to work on Centos 6 either. So I am giving up on this promising looking plugin for now.
$ /var/lib/jenkins/tools/android-sdk/platform-tools/adb connect localhost:41704
$ /var/lib/jenkins/tools/android-sdk/platform-tools/adb -s localhost:41704 shell getprop dev.bootcomplete
error: device offline
$ /var/lib/jenkins/tools/android-sdk/platform-tools/adb disconnect localhost:41704
$ /var/lib/jenkins/tools/android-sdk/platform-tools/adb connect localhost:41704
[android] Timed-out after waiting 180 seconds for emulator
$ /var/lib/jenkins/tools/android-sdk/platform-tools/adb disconnect localhost:41704
[android] Stopping Android emulator

A: Yes this happens sometimes. I had to manually write a script that handled the opening and closing of emulator for every job.
# record screen
recordScreen=true

# kill emulator or not
qemu=`netstat -pltn | grep :5554 | awk '{print $7}' | head -1`
IFS='/' read -ra PIDS_EMU <<< "$qemu"
emu_pid=${PIDS_EMU[0]}
if [ -z "$emu_pid" ]
then
      echo "No pending emulator"
else
      kill -9 $emu_pid
fi

# open emulator
/opt/android-sdk/emulator/./emulator -skin 720x1280 -prop persist.sys.language=en-prop persist.sys.country=US -avd hudson_en-US_320_720x1280_Google_Inc._Google_APIs_27_x86_qa_testing_avd_27 -no-window &

The path to the emulator might be different.
recordScreen is a variable used from jenkins parameter in job
# close emulator or not
qemu=`netstat -pltn | grep :5554 | awk '{print $7}' | head -1`
IFS='/' read -ra PIDS_EMU <<< "$qemu"
emu_pid=${PIDS_EMU[0]}
if [ -z "$emu_pid" ]
then
      echo "No pending emulator"
else
      kill -9 $emu_pid
fi


text:
Q: Is there something like .NET's data annotations in rails? I was looking for something similar to .net's data annotations in rails, something like this.
What I want to achieve by this is: I have some fields (they could be nil also) for which I want to check the length and if the length exceeds I want to display an error message.
I want to club all the error messages related to, say all blog posts (which again have many separate fields) and then display them at once.

A: Rails uses ActiveRecord validations.  In many cases the default validations are easy to set up.  But if you want/or need customized validations that can all be done as well.   Read the documentation here:
http://guides.rubyonrails.org/active_record_validations.html
In your case this type of validation is built in to rails so it's simple as adding 1 line to your model:
class MyModel
  validates :my_field_name, length: { maximum: 3 }, allow_blank: true
end

This will validate the maximum length of your field.  You can also customize the validation error message:
class MyModel
  validates :name, presence: {message: "Title can't be blank." }, uniqueness: {message: "Title already exists."}, length: { maximum: 5, message: "Must be less than 5 characters"}
end


text:
Q: How to forecast low values in data more accurately than the higher values? I have a scenario where I have to forecast small values in data more accurately than the higher values. I have data set as below
start_time          count

2019-12-14 10:00:00 20
2019-12-14 11:00:00 15
2019-12-14 12:00:00 3
2019-12-14 13:00:00 5
2019-12-14 14:00:00 10
2019-12-14 15:00:00 13
2019-12-14 16:00:00 7
2019-12-14 17:00:00 17
2019-12-14 18:00:00 5
2019-12-14 19:00:00 4
2019-12-14 20:00:00 10
2019-12-14 21:00:00 10
2019-12-14 22:00:00 10
2019-12-14 23:00:00 4

I have to forecast low values like 3,4,5 etc... more closely/accurately than other higher values like 10,14,17 etc...
I have tried ARIMA model with all different variations of P,D,Q values. However, I don't get the best match. Over all forecasting performs good but the models fail in predicting lower values or sudden drop in value.
What model should I use to solve my problem?
Thank you


text:
Q: Create Feature to Upload Site Template File (.stp) in MOSS Following on from this question, I have created a feature to upload an site template file as part of an automated build of a SharePoint site.  However, while the feature deploys the .stp file correctly to the hive, and the solution appears in the CAS | Operations | Solution Management page, the site template does not appear in the site template gallery as expected.  I have given the contents of the feature.xml and elements.xml files below; can anyone spot where I am going wrong?
feature.xml
<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="59627434-4B75-4f9c-B830-E6E34007DA70"
          Title=" Team Site Template"
          Description="UKTI Connect Team Site Template"
          Version="12.0.0.0"
          Hidden="FALSE"
          Scope="Web"
          DefaultResourceFile="core"
          xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>
    <ElementFile Location="TeamSiteTemplate.stp" />
  </ElementManifests>
</Feature>

elements.xml
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="TeamSiteTemplate" Url="_catalogs/wt" RootWebOnly="TRUE" >
      <File Url="TeamSiteTemplate.stp" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE">
        <Property Name="LanguageDisplay" Value="English" />
        <Property Name="Version" Value="3" />
      </File>
  </Module>
</Elements>

Thanks, MagicAndi

A: This elements.xml works:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Module Name="TeamSiteTemplate" List="111" Url="_catalogs/wt">
        <File Url="TeamSiteTemplate.stp" Type="GhostableInLibrary">
            <Property Name="LanguageDisplay" Value="English" />
            <Property Name="Version" Value="3" />
        </File>
    </Module>
</Elements>

There are minor differences but the one that probably solves the problem is the inclusion of the List attribute.
To explain, in %CommonProgramFiles%\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL\XML\ONET.XML see the line containing the words sitetemplategalleryList. This shows Type="111" which corresponds to List="111" in elements.xml.
Also note that I set the feature to Site scope as Colin suggested.

A: Have you tried setting the scope of the feature to Site?


text:
Q: Removing background with Open CV is not precise and some of pictures could not be done properly I am trying to remove background from images using OpenCV. Majority of operations are succesfull but some pictures cant be processed properly. Any help or suggestion will be appreciated.
my code:
import os
import numpy
import cv2
import os
import glob
img_dir = r"C:\Users\kaan\Documents\Plant_Seedlings_Classification-master\Plant_Seedlings_Classification-master\data\osmancik"
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
    img = cv2.imread(f1)
    img = cv2.resize(img, (640, 480))
    data.append(img)

data2 = []
arr = numpy.array(data2)

for pict in data:

    gray_img = cv2.cvtColor(pict, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    img_contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
    img_contours = sorted(img_contours, key=cv2.contourArea)

    for i in img_contours:
        if cv2.contourArea(i) > 100:
             break
    mask = np.zeros(img.shape[:2], np.uint8)
    cv2.drawContours(mask, [i],-1, 255, -1)
    new_img = cv2.bitwise_and(pict, pict, mask=mask)
    name=randomString()+".jpg"
    path = r"C:\Users\kaan\Documents\Plant_Seedlings_Classification-master\Plant_Seedlings_Classification-master\segmentated\osmancik2"
    cv2.imwrite(os.path.join(path , name), new_img)

Image:

This is a good example:

This is a bad example:

A: Use HSV filtering.

*

*Change image colors from BGR to HSV (Hue Saturation Value).

*Filter a certain range of saturation and hue.

Refer to this page for code https://pythonprogramming.net/color-filter-python-opencv-tutorial/


text:
Q: IF statements depending on widget configuration tkinter Can I create an if statement whose condition depends on the text of a button?
For example:
if widget.config(text=2):
     btn.config(font=font2)

A: .config() is only to set value.
To get value you have .cget()
if widget.cget("text") == "2":

or dictionary
if widget["text"] == "2":

text is string so you have to compare with string "2" or you have to convert string to integer
if int(widget["text"]) == 2:

EDIT: cget() doc shows it returns strings but for int and float it doesn't convert value to string.


text:
Q: Is constructor delegation the same as calling the constructor? If we have
class A {
private:
public:
  A(int a, int b) {std::cout << "You passed two numbers!;}
};

and I wish to create another constructor where the value of a is assumed 0 and we pass the value of b, will these two produce the same result:
// First variant
A(int b) : A(0, b) {}
// Second variant
A(int b) {A(0, b);}

I'm asking since in one of my codes I have
A(int minPrice, int maxPrice) {
  if (minPrice < 0 || maxPrice < 0)
    throw std::range_error("Illegal price");
  A::minPrice = minPrice;
  A::maxPrice = maxPrice;
}

and this produces an issue when I use the second variant; namely, when I call A(0, maxPrice) from inside that new one-parameter constructor.


text:
Q: Can discriminative models be sampled from if we extract vectors within the hypothesis? Generative models are useful because we can sample vectors from them.
Discriminative models supposedely don't have this feature. But what's stopping us from sampling vectors that are "within the hypothesis"? Imagine we draw a circle around the cat vectors. And we can then randomly sample points within this circle to "generate" sample vectors of a cat.
So, by this technique: discriminative models can "generate" samples. I don't know if this technique is valid though

A: Do you know what we call the outputs of a model that provides us with the encoded vector and the radius of the circle (ellipsoid, technically) we can draw around the vectors and still get correctly generated samples?
We call them the 'mean' and 'standard deviation' (respectively).