create double view with same url alias for different theme

Question: In my drupal. I created a two theme one for desktop and another for mobile using Mobile switch I change the theme. Now I Created a View as a page for desktop with alias "xxx/yyy" and for mobile also I created a view as a page with same alias "xxx/yyy"(some modification Done). While switching the theme from desktop to mobile, the desktop view is appear. How to differentiate?
Comment: Do you prefer developing solution or solution that can do it in views?
Comment: developing solution
Answer: ok
create a menu with hook_menu
then with checking condition you want load your views in callback of your menu
Something like below
<code>/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['myurl'] = array(
    'title' => 'title',
    'page callback' => 'myfunction_callbackfuction',
    'access callback' => TRUE,
  );

  return $items;
}

function myfunction_callbackfuction() {
  $view = views_get_view('view_name');
if($mycondtion)
  $view->set_display('page1');
else
  $view->set_display('page2');

  $view->pre_execute();
  $view->execute();
  print $view->render();
}
</code>
Comment: is it any hook function to disable the particular view.
Comment: @vinox you can create 2 master views without any page or block
Answer: I achieve this by using
<code>$view_name = 'my_views_name';
$display_id = 'my_views_display_id';
print views_embed_view($view_name , $display_id);
</code>


Snowflake SQL - Sum with one-to-many joins

Question: I am trying to write a query that shows when an item on an order was entered or "keyed" in, and then when that item was billed. In certain cases, one item will have multiple billing dates. Because of there being multiple billing dates, I am getting duplicate results of the SALES_ORDER_ITEM_QUANTITY AND KEYED_GSAR fields.
Below is the query that I am trying to use. It is filtered on one order to illustrate the problem I am having.
vwith sales_orders as (
    select
        O.SALES_ORDER_ITEM_CREATE_DATE,
        O.SALES_ORDER_ID,
        O.MATERIAL_ID,
        O.SALES_ORDER_ITEM_ID,
       sum(distinct o.gsar) as keyed_sales,
       sum(distinct o.sales_order_item_quantity) as SALES_ORDER_ITEM_QTY
    from EDP.RPT_SALES.SALES_ORDERS O
    where O.FISCAL_YR_ID IN (2022,2023)
        AND O.WW_CHANNEL IN ('RENOVATION','INSTALLATION')
        and o.sales_order_id = '0306231843'

        GROUP BY
        O.SALES_ORDER_ITEM_CREATE_DATE,
        O.SALES_ORDER_ID,
        O.MATERIAL_ID,
        O.SALES_ORDER_ITEM_ID
)

,billing as (
    select
        B.BILLING_DOC_DATE,
        B.SALES_DOC_ID,
        B.MATERIAL_ID,
        B.SALES_DOC_ITEM_ID,
        sum(B.BILL_QTY) as BILL_QTY,
        sum(B.GSAR) as GSAR
    from EDP.RPT_SALES.BILLING B
    where b.fiscal_yr_id IN (2022,2023)
        AND b.WW_CHANNEL IN ('RENOVATION','INSTALLATION')

        group by
        B.BILLING_DOC_DATE,
        B.SALES_DOC_ID,
        B.MATERIAL_ID,
        B.SALES_DOC_ITEM_ID
)

SELECT

O.SALES_ORDER_ITEM_CREATE_DATE,
LTRIM(O.SALES_ORDER_ID,'0') SALES_ORDER_ID,
LTRIM(O.MATERIAL_ID,'0') MATERIAL_ID,
O.SALES_ORDER_ITEM_ID,
O.SALES_ORDER_ITEM_QTY,
KEYED_SALES,
B.BILLING_DOC_DATE,
B.BILL_QTY,
B.GSAR BILLED_SALES

FROM sales_orders O
LEFT JOIN billing B ON O.SALES_ORDER_ID = B.SALES_DOC_ID AND O.MATERIAL_ID = B.MATERIAL_ID AND O.SALES_ORDER_ITEM_ID = B.SALES_DOC_ITEM_ID

This order has one material on it, 128470. There was a quantity of 40 ordered for a value of $7,783.60. This material was billed on 4 separate dates, as seen in the BILLING_DOC_DATE column. The SALES_ORDER_ITEM_QUANTITY and KEYED_SALES values are getting duplicated 4 times. Below are the results I am getting:

SALES_ORDER_ITEM_CREATE_DATE
SALES_ORDER_ID
MATERIAL_ID
SALES_ORDER_ITEM_ID
SALES_ORDER_ITEM_QTY
KEYED_SALES
BILLING_DOC_DATE
BILL_QTY
BILLED_SALES

2023-03-31
306231843
128470
20
40
7783.60
2023-03-31
31
6032.29

2023-03-31
306231843
128470
20
40
7783.60
2023-03-23
5
972.95

2023-03-31
306231843
128470
20
40
7783.60
2023-04-05
3
58.77

2023-03-31
306231843
128470
20
40
7783.60
2023-03-29
1
194.59

Below are the desired results

SALES_ORDER_ITEM_CREATE_DATE
SALES_ORDER_ID
MATERIAL_ID
SALES_ORDER_ITEM_ID
SALES_ORDER_ITEM_QTY
KEYED_SALES
BILLING_DOC_DATE
BILL_QTY
BILLED_SALES

2023-03-31
306231843
128470
20
40
7783.60
2023-03-31
31
6032.29

2023-03-31
306231843
128470
20
0
0
2023-03-23
5
972.95

2023-03-31
306231843
128470
20
0
0
2023-04-05
3
58.77

2023-03-31
306231843
128470
20
0
0
2023-03-29
1
194.59
Answer: I suggest you need a "row number" in the billing data to distinguish which row to output the sales data so that you can avoid repeats. Whilst here, I also suggest you don't use sum(distinct ...) unless you have a legitimate reason to omit some data. Given you are summing sales info from a single table it seems very unlikely that  you need sum(distinct ...). i.e. If an order had 2 entries of qty = 20 then the total order qty = 40 isn't it?
vwith sales_orders AS (
        SELECT O.SALES_ORDER_ITEM_CREATE_DATE
            , O.SALES_ORDER_ID
            , O.MATERIAL_ID
            , O.SALES_ORDER_ITEM_ID
            , sum(o.gsar) AS keyed_sales
            , sum(o.sales_order_item_quantity) AS SALES_ORDER_ITEM_QTY
        FROM EDP.RPT_SALES.SALES_ORDERS O
        WHERE O.FISCAL_YR_ID IN (2022, 2023) AND O.WW_CHANNEL IN ('RENOVATION', 'INSTALLATION') AND o.sales_order_id = '0306231843'
        GROUP BY O.SALES_ORDER_ITEM_CREATE_DATE
            , O.SALES_ORDER_ID
            , O.MATERIAL_ID
            , O.SALES_ORDER_ITEM_ID
        )
    , billing AS (
        SELECT B.BILLING_DOC_DATE
            , B.SALES_DOC_ID
            , B.MATERIAL_ID
            , B.SALES_DOC_ITEM_ID
            , sum(B.BILL_QTY) AS BILL_QTY
            , sum(B.GSAR) AS GSAR
            , row_number() OVER (
                PARTITION BY B.SALES_DOC_ID
                , B.MATERIAL_ID
                , B.SALES_DOC_ITEM_ID ORDER BY B.BILLING_DOC_DATE
                ) AS rn
        FROM EDP.RPT_SALES.BILLING B
        WHERE b.fiscal_yr_id IN (2022, 2023) AND b.WW_CHANNEL IN ('RENOVATION', 'INSTALLATION')
        GROUP BY B.BILLING_DOC_DATE
            , B.SALES_DOC_ID
            , B.MATERIAL_ID
            , B.SALES_DOC_ITEM_ID
        )

SELECT O.SALES_ORDER_ITEM_CREATE_DATE
    , LTRIM(O.SALES_ORDER_ID, '0') SALES_ORDER_ID
    , LTRIM(O.MATERIAL_ID, '0') MATERIAL_ID
    , O.SALES_ORDER_ITEM_ID
    , CASE WHEN b.rn = 1 THEN O.SALES_ORDER_ITEM_QTY ELSE 0 END AS SALES_ORDER_ITEM_QTY
    , CASE WHEN b.rn = 1 THEN O.KEYED_SALES ELSE 0 END AS KEYED_SALES
    , B.BILLING_DOC_DATE
    , B.BILL_QTY
    , B.GSAR BILLED_SALES
FROM sales_orders O
LEFT JOIN billing B ON O.SALES_ORDER_ID = B.SALES_DOC_ID AND O.MATERIAL_ID = B.MATERIAL_ID AND O.SALES_ORDER_ITEM_ID = B.SALES_DOC_ITEM_ID

Comment: Thank you. I agree on not using sum(distinct). I did not think about that. The row number addition gave me the result that I was looking for.


Views templates: How to print file fields

Question: I am creating a template for my table style view. I have several fields most of which are excluded from display. Inside my template I want to print those excluded from display fields. After some search I found that you can access all fields including those excluded by using:
$view->result[$row_count]->

Now the field I want to print is a file. This is the structure that dpm returns me:

field_field_programme (Array, 1 element)

0 (Array, 2 elements)
    rendered (Array, 3 elements)
        #theme (String, 9 characters ) file_link
        #file (Object) stdClass
            fid (String, 4 characters ) 1011
            display (String, 1 characters ) 1
            description (String, 0 characters )
            uid (String, 1 characters ) 1
            filename (String, 10 characters ) seminar3.pdf
            uri (String, 40 characters ) public://seminaria/programmes/seminar3.pdf
            filemime (String, 15 characters ) application/pdf
            filesize (String, 6 characters ) 218882
            status (String, 1 characters ) 1
            timestamp (String, 10 characters ) 1333973478
            rdf_mapping (Array, 0 elements)
        #access (Boolean) TRUE
    raw (Array, 11 elements)
        fid (String, 4 characters ) 1011
        display (String, 1 characters ) 1
        description (String, 0 characters )
        uid (String, 1 characters ) 1
        filename (String, 10 characters ) seminar3.pdf
        uri (String, 40 characters ) public://seminaria/programmes/seminar3.pdf
        filemime (String, 15 characters ) application/pdf
        filesize (String, 6 characters ) 218882
        status (String, 1 characters ) 1
        timestamp (String, 10 characters ) 1333973478
        rdf_mapping (Array, 0 elements)

It is not as simple as using $field->content. How can I print my file? Do I need to create a link and add the information above? What code can I use so depending on the filemime the icon will change?
In other views I have created the output of files is:

With the information I get from the file I could create such a link. I am guessing length is the filesize? Maybe there is an api function that constructs file links?
Answer: Using  this seems to do exactly what I want
<?php print $view->style_plugin->rendered_fields[$row_count]['field_programme']; ?>

which is extremely useful since it can be used even for fields that have been excluded from the display of the view.


Managing module library dependencies with composer

Question: I've found Dependencies in a custom module with drupal-composer, How can I include a third party library in my custom module without using Composer Manager and How to manage contrib modules composer dependencies on drupal 8 which are releated to my question, but no longer seem to apply since Drupal 8.1 and the deprecation of Composer manager.
Also popular guides such as The definitive introduction to D8 and Composer appear to no longer apply as they also mention composer manager.
The other solution opposed to composer manager, alter the core composer.json file feels like too much core hacking and would probably break with every Drush update of Drupal core(?).
More specifically, I am attempting to update Views vCards from Drupal 7 to 8. I have created my composer.json file as follows:
{
  "name": "drupal/views_vcards",
  "description": "Allows creation of vCards using the fields provided by the Views module.",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "homepage": "https://drupal.org/project/views_vcards",
  "require": {
    "maennchen/zipstream-php": "0.3.*"
  }
}

But if I put a composer.json file in my module folder, how do I make Drupal aware that that file is there, and how do I make sure the required zipstream-php library is downloaded?
Simply running composer update from the Drupal root does update a lot of Drupal dependencies, but it does not include the composer.json files that are in the modules folders. I also don't assume I should be calling composer install from inside all modules with dependencies.
How do I make Drupal aware of a module's dependency without using composer manager and/or hacking core?
UPDATE:
The composer merge plugin used by core appears to have support a wildcard path:
{
    "require": {
        "wikimedia/composer-merge-plugin": "dev-master"
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "composer.local.json",
                "extensions/*/composer.json" // < ---- THIS LINE
            ],
            "require": [
                "submodule/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-dev": true,
            "merge-extra": false
        }
    }
}

Why doesn't core merge modules/*/composer.json, that would solve everything right?
Update 2:
THe reasoning for not supporting this is covered in this issue (which also has been quiet for some time now).
Comment: Editing the main composer file is the corrected way.
Comment: If you let composer manage all of your dependencies (core included) then your issue will disappear. See https://packagist.org/packages/drupal/core
Comment: Here is an example composer file I wrote for another question: http://drupal.stackexchange.com/a/187097/40011
Comment: Thanks for the reply @Eyal. So managing all contrib modules via the `composer.json` file is the new recommended way and drush for downloading and installing modules is getting replaced? Obviously will composer automatically resolve nested dependencies and indeed also download my dependencies.
Answer: New method using drupal-scaffold for greatest flexibility
For Drupal 8.4.0 and greater using drush >9.0.0, drush make is deprecated and you should use a full-composer work flow as detailed in the drupal.org documentation links below. Those links do recommend using a composer project, but this may not work for everyone's web server setup. The following is step-by-step how to setup composer.json manually for detail explanation. The instructions regarding adding modules manually can still be done.
# Initialize composer. Stability alpha is important for custom modules that may be source managed outside of packagist or drupal.org
composer init --name myvendor/mysite --stability=alpha --license=GPLv2
composer config repositories.drupal composer https://packages.drupal.org/8
composer config discard-changes true

Then you need to add to composer.json manually the following based on your preferences because there is no way to do so automatically with composer as-is. These will configure drupal-scaffold to install your modules where you want them (as opposed to in vendor/ or a directory chosen by some other developer). Change 'webroot' to 'www' or 'public' or what your host is.
    "extra": {
        "installer-paths": {
            "webroot/core": ["type:drupal-core"],
            "webroot/modules/contrib/{$name}": ["type:drupal-module"],
            "webroot/modules/custom/{$name}": ["type:drupal-custom-module"],
            "webroot/themes/contrib/{$name}": ["type:drupal-theme"],
            "webroot/themes/custom/{$name}": ["type:drupal-custom-theme"],
            "webroot/profiles/{$name}": ["type:drupal-profile"],
            "webroot/libraries/{$name}": ["type:drupal-library"]
        },
        "patches": {}
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold"
    }

Now you can install some dependencies. Note that composer must be able to use scripts and plugins for this to work.
composer require composer/installers:^1.4.0 drupal-composer/drupal-scaffold:^2.3.0 cweagans/composer-patches:^1.6.2

Run the drupal-scaffold script once (or on your build server as needed):
composer drupal-scaffold

Drupal core, modules, themes, etc... can be installed as per the instructions below without the drupal-merge-plugin.
composer require drupal/core:~8.5.1 drupal/views_vcards

Older method using drupal-merge-plugin or working with core directly
For Drupal 8.1.0 and greater, you can use composer to require Drupal modules directly. The documentation around Using Composer in a Drupal project and Using Composer to install Drupal packages through Drupal.org has been updated to take advantage of drupal.org's packagist. I find it works well already in a deployment scenario.
composer config repositories.drupal composer https://packages.drupal.org/8
composer require drupal/views_vcards

For development, I think that manually adding in the dependency with composer require works fine. The merge approach works too with the drupal-merge-plugin and I use this for my drush make work flow.
composer config repositories.drupal composer https://packages.drupal.org/8
composer require mile23/drupal-merge-plugin
composer update

Update 2016.06.22
I ran into an issue using drush make, which added the traditional Drupal version tags and drupal.org packagist URLs using semver. To that end, I needed to switch to using the stabler packagist at https://packagist.drupal-composer.org, which still supports the traditional Drupal version tags.
Also note that the build server or machine requires an exorbitant amount of memory to do a composer update (or require), which is necessary in all scenarios where running composer update on a similar development machine is not possible in your build process.
Update 2016.09.23

Added link to Using Composer to install Drupal packages through Drupal.org.
Added onto the development section about how I use it with drush make.

Update 2018.03.30

Noticed an up vote. This is fairly old so decided to clarify about more recent development and setting up your site directly with composer since drush make has been (sadly) deprecated for a while.
Comment: I am still very used to using drush to download and install modules, but that will be entirely replaced with composer?
Comment: That's how drupalci is doing it now, but before that, you could use the merge plugin directly. The patch I wrote for drupalci initially was https://www.drupal.org/files/issues/2597778-composer-contrib-18.patch. This was committed, but now no longer in the code base as it's simplified to use the packagist and do everything from composer iirc. I also do the following with TravisCI: http://cgit.drupalcode.org/xero/tree/.travis.yml#n40. It will depend on your work flow.
Comment: Maybe worth adding a blurb about Asset Packagist here for 3rd-party libraries with Composer. This methodology is being adopted by a number of Drupal distros and several contrib modules are now using it as well.  I've just contributed some documentation to officialize this solution https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#third-party-libraries and https://www.drupal.org/docs/develop/using-composer/managing-dependencies-for-a-contributed-project#third-party-libraries


'ERROR: relation does not exist at character', error in celery with django

Question: I have a model called UserApp, of which I make a query from an asynchronous task with Celery, but I get the following error from the output of the docker compose.

postgres_1     | ERROR:  relation "users_userapp" does not exist at
  character 536
celery_1       | django.db.utils.ProgrammingError: relation
  "users_userapp" does not exist

This is the code of the task:
<code>@app.task(bind=True, default_retry_delay=50, max_retries=10, ignore_result=False)
def send_reset_password_email_task(self, muser):
    user = UserApp.objects.get(pk=muser.get('id'))
    print("send_reset_password_email_task user: ",user)
</code>
that query from the views runs without problems, in the same way if I call the task synchronously without the delay from the view, it also runs without problems, I have already run the migrations and the problem is not fixed either.
I would really appreciate the help.
Comment: Did you restart celery after adding model/running migrations?
Comment: yes, I rebuilt all the services with the docker compose included the app with django
Comment: did you added `UserApp` to `INSTALLED_APPS` ?
Comment: @JPG yes, even in the views the query works well
Answer: I found the problem, it was due to a bad configuration in the docker compose file, this was my file.
<code>version: '2'

volumes:   postgres_data_develop: {}   postgres_backup_develop: {}

services:   postgres:
    build: ./compose/postgres
    volumes:
      - postgres_data_develop:/var/lib/postgresql/data
      - postgres_backup_develop:/backups
    environment:
      - POSTGRES_USER=cxc_web
    ports:
      - "5432:5432"

  django:
    build:
      context: .
      dockerfile: ./compose/django/Dockerfile-dev
    command: python /app/manage.py runserver_plus 0.0.0.0:8000
    depends_on:
      - postgres
    environment:
      - POSTGRES_USER=cxc_web
      - USE_DOCKER=yes
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    links:
      - postgres

  redis:
    image: "redis:alpine"

  #celery   celery:
    build:
      context: .
      dockerfile: ./compose/django/Dockerfile-dev
    command: celery -A config.settings worker -l info
    #command: ./celery/run_celery.sh
    volumes:
      - .:/app
      #- .:/code
    depends_on:
      - postgres
      - redis   celery-beat:
    build:
      context: .
      dockerfile: ./compose/django/Dockerfile-dev
    command: celery -A config.settings beat -l info
    volumes:
      - .:/app
    depends_on:
      - postgres
      - redis
</code>
due to the configuration of 'environment: - POSTGRES_USER = cxc_web', in the django service the app was connected to the 'cxc_web' database, while the other services were connected to the database with the service's default name, which in this case is called postgres. so to the two celery micerservicios also add 'environment: - POSTGRES_USER = cxc_web', and fix the problem.


Optimize SQL Query having SUM and COUNT functions

Question: I have the following query which takes too long to retrieve around 70000 records. I noticed that the execution time is proportional to the number of the records retrieved. I need to optimize this query so that the execution time is not proportional to the number of records retrieved. Any idea?
;WITH TT AS (
      SELECT TaskParts.[TaskPartID],
      PartCost,
      LabourCost,
      VendorPaidPartAmount,
      VendorPaidLabourAmount,
      ROW_NUMBER() OVER (ORDER BY [Employees].[EmpCode] asc) AS RowNum
      FROM [TaskParts],[Tasks],[WorkOrders], [Employees], [Status],[Models]
      ,[SubAccounts]WHERE 1=1 AND (TaskParts.TaskLineID = Tasks.TaskLineID)
AND (Tasks.WorkOrderID = [WorkOrders].WorkOrderID)
AND (Tasks.EmpID = [Employees].EmpID)
AND (TaskParts.StatusID = [Status].StatusID)
And (Models.ModelID = Tasks.FailedModelID)
And (SubAccounts.SubAccountID = Tasks.SubAccountID)AND (SubAccounts.GLAccountID = 5))
SELECT  --*
    COUNT(0)--,
    SUM(ISNULL(PartCost,0)),
    SUM(ISNULL(LabourCost,0)),
    SUM(ISNULL(VendorPaidPartAmount,0)),
    SUM(ISNULL(VendorPaidLabourAmount,0))
    FROM TT

Comment: You are only selecting output from `TT`. Remove `TD0`, `TD1` and `TP1` as they are redundant.
Comment: Those tables are not the source of this issue. It's the query with COUNT and SUM
Comment: If you knew that you should have ommitted them from the start. Many people will simply move on. You are doing yourself a disservice by posting long queries.
Answer: As Lieven noted, you can remove TD0, TD1 and TP1 as they are redundant.
You can also remove the row_number column, as that is not used and windowing functions are relatively expensive.
It may also be possible to remove some of the tables from the TT CTE if they are not used; however, as table names have not been included with each column selected, it isn't possible to tell which tables are not being used.
Aside from that, your query's response will always be proportional to the number of rows returned, because the RDBMS has to read each row returned to calculate the results.
Comment: @mohammedn - Can you post an execution plan?
Comment: Thank you, Mark. It seems there is a join that causing this delay - the join with Models table. However, this table contains only round 7000 records, not sure yet why it take that much time.
Answer: Make sure that you have support index for each Foreign Key also most probably it is not the issue in this case but MS SQL optimization better works with inner joins.
Also I don't see any reason why you need RowNum if you need only totals.


Get indices for values of one array in another array

Question: I have two 1D-arrays containing the same set of values, but in a different (random) order. I want to find the list of indices, which reorders one array according to the other one. For example, my 2 arrays are:
ref = numpy.array([5,3,1,2,3,4])
new = numpy.array([3,2,4,5,3,1])

and I want the list order for which new[order] == ref.
My current idea is:
def find(val):
    return numpy.argmin(numpy.absolute(ref-val))

order = sorted(range(new.size), key=lambda x:find(new[x]))

However, this only works as long as no values are repeated. In my example 3 appears twice, and I get new[order] = [5 3 3 1 2 4]. The second 3 is placed directly after the first one, because my function val() does not track which 3 I am currently looking for.
So I could add something to deal with this, but I have a feeling there might be a better solution out there. Maybe in some library (NumPy or SciPy)?
Edit about the duplicate: This linked solution assumes that the arrays are ordered, or for the "unordered" solution, returns duplicate indices. I need each index to appear only once in order. Which one comes first however, is not important (neither possible based on the data provided).
What I get with sort_idx = A.argsort(); order = sort_idx[np.searchsorted(A,B,sorter = sort_idx)] is: [3, 0, 5, 1, 0, 2]. But what I am looking for is [3, 0, 5, 1, 4, 2].
Comment: Does it really matter which index you are getting if the element is repeated? Are you trying to do something more than `a[ind]` to get `b`?
Comment: That being said , yes there is a way using multiple argsorts. I'll write it up as soon as I get to an actual computer.
Comment: @Divakar. This is not the same question. It's asking to find the indices of a shuffle, not a subset. As such, there is a nice optimization possible using argsort which does not apply to the other question. I hope you support my bid to reopen.
Comment: @MadPhysicist Not sure what subset you are referring to. The searchsorted solution there gives the indices, which is the expected `order` in this question. Did you try that solution?
Comment: @Divakar I tried, and I got some multiple indices in `order` (see edit).
Comment: @Feodoran Your `new` would be A. Your `ref` would be B. Now, using the linked solution : `sort_idx = A.argsort(); order = sort_idx[np.searchsorted(A,B,sorter = sort_idx)]`. Does that answer your question? If it doesn't, please do explain how/why it doesn't. Would be happy to re-open otherwise.
Comment: @Divakar. The solutions to the other question work here just fine, no argument there. This question has an additional rule though, that the arrays are guaranteed to be the same size. This leads to a solution that does not apply to the other question. I would like to record this solution and I think that it's existence indicates that this is not exactly the same question.
Comment: @MadPhysicist Hmm good point. Would love to see an optimized version for such a case (if there's any). Re-opened.
Comment: @Divakar as already mentioned, yes I tried. I added what I actually get and I need to the question.
Comment: @Divakar. Not sure about optimized , but the indices will be unique, which seems to be a concern.
Answer: Given ref, new which are shuffled versions of each other, we can get the unique indices that map ref to new using the sorted version of both arrays and the invertibility of np.argsort.
Start with:
i = np.argsort(ref)
j = np.argsort(new)

Now ref[i] and new[j] both give the sorted version of the arrays, which is the same for both. You can invert the first sort by doing:
k = np.argsort(i)

Now ref is just new[j][k], or new[j[k]]. Since all the operations are shuffles using unique indices, the final index j[k] is unique as well. j[k] can be computed in one step with
order = np.argsort(new)[np.argsort(np.argsort(ref))]

From your original example:
>>> ref = np.array([5, 3, 1, 2, 3, 4])
>>> new = np.array([3, 2, 4, 5, 3, 1])
>>> np.argsort(new)[np.argsort(np.argsort(ref))]
>>> order
array([3, 0, 5, 1, 4, 2])
>>> new[order]  # Should give ref
array([5, 3, 1, 2, 3, 4])

This is probably not any faster than the more general solutions to the similar question on SO, but it does guarantee unique indices as you requested. A further optimization would be to to replace np.argsort(i) with something like the argsort_unique function in this answer. I would go one step further and just compute the inverse of the sort:
def inverse_argsort(a):
    fwd = np.argsort(a)
    inv = np.empty_like(fwd)
    inv[fwd] = np.arange(fwd.size)
    return inv

order = np.argsort(new)[inverse_argsort(ref)]

Comment: @Feodoran. The inversion function would work just fine if you replaced `argsort` with the appropriate call to `lexsort`.
Comment: Idea seems correct. To optimize it further, we could use [`argsort_unique`](https://stackoverflow.com/a/43411559/) to get `k`.
Comment: @Divakar. I added it to the answer.
Comment: @Feodoran. I see the purpose of your edit. I clobbered it, but will update myself.
Comment: Nice, thank you. I was a litte worried at first about calling three times `argsort`. But the `inverse_argsort` optimizes this quite well, more than twice as fast.
Comment: Can this be extended to a multi-dimensional version? In the sense that the elements of `ref` and `new` are not scalars but arrays as well. So 1 axis needs to be reordered, the others are kept fixed. For example in 2D, such that: `new[order,:] == ref`.
Comment: @Feodoran. I would imagine so. `np.argsort` has an `axis` parameter to tell you which dimension to sort on. The default is the last one (`-1`).
Comment: The problem is: `numpy.sort(a, axis=0)` sorts each column independently, thus mixing the rows. Accordingly `argsort(a, axis=0)` returns a 2D array, but I need a 1D here. (One could ask now how exactly the different columns should be compared and ordered. But the how does not really matter here, as long as it is consistent.)
Comment: @Feodoran. I see the problem. According to [this Q/A](https://stackoverflow.com/q/18920010/2988730), you can use [`np.lexsort`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html).
Comment: Yes, thank you! Replacing `argsort(a)` with `lexsort(a.T, axis=0)` (both calls) is what I needed.
Comment: @Feodoran. `lexsort(a.T, axis=0)` should be the same thing as `lexsort(a, axis=1).T`. Not sure if that helps you any, but it might.
Comment: No, `lexsort(a, axis=1)` throws some error. And the final `.T` does not really matter since the output is 1D.
Comment: @Feodoran. I just realized what `np.lexsort(a.T)` does. You are absolutely correct.


Server 2008 TS Licensing Diagnosis has not discovered any license servers

Question: I have installed Terminal Services and Terminal Services Licensing on a 2008 SP2 Domain Controller.  I have an Open License for Terminal Services and I have successfully Activated the Licensing server and all looks good in the TS Licensing Manager.  TS Cal Availability is Available and when I log users on TS Cals In Use shows the correct figure.  The Server is also showing as Activated.
However, if I open Server Manager, Expand Roles, Terminal Services, Terminal Services Configuration and click on Licensing Diagnosis I get the following warning:
The Terminal Server is within its grace period, but the terminal server has not discovered any license servers.
I have tried changing License Server Discovery Mode from Automatic to the FQDN of the server.  When I click Check Names I get a message stating it is a valid license server, however the warning message still remains.  Even after a reboot it is still there.
I have also tried uninstalling Terminal Services and TS Licensing and reinstalling but I still get the same message.  I cannot see anything obvious in the event viewer.  Could someone please help me with this?
Thanks in advance.
Answer: This may sound silly but I know this has caused panics in my environments before. Make sure you are logged into the terminal server as a domain user with proper privs (or launch the mmc as a domain user). The licensing diagnosis will not complete the queries properly if logged in using a local account on the TS box.
Comment: I am logging on as a domain admin (the server is a DC).
Answer: Have you done this.
Comment: Thanks for the tip, I have just tried that and the server is correctly listed.  This is definitely a strange one.
Answer: http://social.technet.microsoft.com/Forums/en-US/winserverTS/thread/4fa27bdd-0b9e-440f-a7c7-146a7484a028


Can't create "Share" menu in popup menu on Android

Question: I have an android app that has a gridview in it.  The gridview items contain among other things, a button to show context sensitive menus.  So, I implemented a popup menu that comes up when they touch the button in the gridview item.
This menu contains 3 items:

Edit Item
Delete Item
Share Item

I have successfully implemented the edit and delete menu items.  The problem is with the "Share Item" menu item.  It is a ShareActionProvider.  I previously implemented these menu choices as an ActionMode (menu items across the top).  But now that the menu is a popup, I'm not sure how to implement the "Share Item" menu option.
Here is my popup_menu.xml:
<code>     <?xml version="1.0" encoding="utf-8"?>
      <menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <group android:id="@+id/group_edit_mode">
        <item
            android:id="@+id/MenuItemEdit"
            android:title="@string/item_option_edit"
            app:showAsAction="withText|ifRoom" />

        <item
            android:id="@+id/MenuItemDelete"
            android:title="@string/delete"
            app:showAsAction="withText|ifRoom" />

        <item
            android:id="@+id/MenuItemShare"
            android:title="@string/share"
            app:showAsAction="ifRoom"
            app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>
    </group>
</menu>
</code>
Here is the popup menu code:
<code>                PopupMenu popupMenu = new PopupMenu(MINMainActivity.getSharedInstance(), optionButton);
            MenuInflater inflater = popupMenu.getMenuInflater();
            inflater.inflate(R.menu.gridview_edit_menu_single_item, popupMenu.getMenu());
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
            {
                @Override
                public boolean onMenuItemClick(MenuItem item)
                {
                    boolean choiceHandled = false;
                    int itemID = item.getItemId();
                    switch (itemID)
                    {
                        case R.id.MenuItemEdit:
                            MINPageTypeGridFragment.launchAlbumItemDetails(mFragment, albumItem, mPageItem.pageConfigFileName);
                            mFragment.currentMode = MINPageTypeGridFragment.MODE_STANDARD;
                            choiceHandled = true;
                            break;
                        case R.id.MenuItemDelete:
                            MINPageTypeGridFragment.deleteItem(mFragment, mAlbum, albumItem);
                            mFragment.currentMode = MINPageTypeGridFragment.MODE_STANDARD;
                            choiceHandled = true;
                            break;
                        case R.id.MenuItemShare:
                            choiceHandled = true;
                            mFragment.currentMode = MINPageTypeGridFragment.MODE_STANDARD;
                            break;
                    }
                    return choiceHandled;
                }
            });
            popupMenu.show();
</code>
Answer: This was WAY overthought.  I just kept it as a button and created a chooser.
<code>public void onShareClick(MINAlbumItem albumItem)
{
    List<MINAlbumItem> albumItemsArray = new ArrayList<MINAlbumItem>();
    albumItemsArray.add(albumItem);

    // Creates intent and loads data from items array
    Intent intent = mFragment.Share(albumItemsArray);
    MINMainActivity.getSharedInstance().startActivity(Intent.createChooser(intent, MINMainActivity.getSharedInstance().getResources().getString(R.string.send_to)));
}
</code>


perl fork vs. thread for shared data structures

Question: I am writing a script where I need to share data structures among multiple processes. Currently I am forking, which worked great when I only needed to share simple variables (i.e. $var, @arr, %hash). However more recently I've been trying to share more complex variables, such as a hash of hashes, and I've been running into a lot of trouble. I've tried using IPC::Shareable, DBM::Deep, and forks::shared, but they all seem to have issues sharing more complex data structures, like a hash of hashes. What I'm wondering is for a situation like mine, would it be better to use forks or threads? I like the fork syntax because it seems easy to use, but if I'm jumping through a lot of unnecessary hoops when thread would be a lot simpler, I'd definitely like to switch.
UPDATE
Share means the separate processes need to both read and write to the data structures.
I am running Perl 5.8 on Centos5.5
Comment: Does "share" mean multiple threads/processes all _updating_ the same structures or just reading from?
Comment: Sorry, "share" means updating and reading.
Comment: You need to provide more context, such as OS and Perl version. Perl provides a poor emulation of posix processes on Win(32|64) platforms and it's not clear which OS you are targeting.
Comment: There is no reason whatsoever to use threads on a POSIX platform. The threads implementation on a POSIX OS clones the whole Perl interpreter providing a poor implementation of processes. You are far better of with traditional IPC.
Comment: @chansen, so using DBM::Deep and forking would be a better solution than threading?
Comment: @srchulo, yes! There might be better modules on CPAN that serves your purpose depending on the number of nodes.
Comment: "You are far better of with traditional IPC." (limited interaction through channels) ...even when using threads.
Comment: I made a comment based on his. I made the same comment in my answer. You are usually far better off with a design that limits interaction to communication channels, regardless of whether you use threads or processes.
Answer: You provided absolutely no information about your sharing patterns, so I'll assumes you're using a worker model (which is what you really should be using), which means the data is shared via a message queue.
If so, the answer is "it doesn't matter". Use you choice of use forks; or use threads;, and use Thread::Queue::Any as your inter-task communicate channel.
Comment: But Thread::Queue::Any requires you to be adding variables to a queue, what if I just wanted any of the threads to be able to access it without having to add it to a queue? Like it was just a regular hash.
Comment: Like I said, you did not provide any usage patterns.


delphi - get form class from a frame code

Question: How can I get the classtype of the owner form of a frame from the frame code, and to convert that type to TFormClass?
I know that I need to register the form class, so I can get it with GetClass, but there I get stuck.
Comment: I don't understand. `Owner.ClassType` doesn't work?
Comment: @NGLN, Owner is Not necessarily a TForm.
Answer: The class type of the host form is obtained like this:
HostFormClassType := TFormClass(GetParentForm(Self).ClassType);

Here when I write Self I take that to be your frame. Although you said "owner", I suspect that what you really mean is the form on which the frame resides. That's usually the same thing as the frame's owner, but not always.
There's no need to register anything or call GetClass.
The only slight wrinkle with this is that GetParentForm could return something derived from TCustomForm rather than TForm. So the cast in the above code has potential to be incorrect. You would deal with that by including a runtime test.
var
  ClassType: TClass;
....
ClassType := GetParentForm(Self).ClassType;
Assert(ClassType.InheritsFrom(TForm));
HostFormClassType := TFormClass(ClassType);


Strat tremolo bar has tightening issues

Question: I got a standard American strat from 2015. When I tighten the trem bar, the bar stops tightening right over the strings. However when I loosen it, one turn and it flops around all over the place. What could I do?
Answer: I see two courses of action...

You could just take the damn thing off altogether, as I did 40 years ago ;-) or
Get a roll of plumber's PTFE tape from a hardware/DIY store & wrap it round the thread until you achieve just the right resistance.
PTFE is "Teflon" so it will never stick or jam. It is so thin you could probably get 5 - 10 wraps before it's too thick to screw in, so you will have a lot of room for fine adjustment.
Added bonus, it will never leak ;-)

For the plumbing junkies out there, PTFE is polytetrafluoroethylene
After comments:
Don't use any kind of sticky tape. It will come back to haunt you.
There's a really specific reason to use PTFE, & it's because it never changes state, doesn't get sticky, doesn't dry out.
Comment: #2 is a clever solution, and I don't know why I never thought of it. Probably because I too settled on #1 long ago ;)
Comment: holy crap tape worked.
it wasnt teflon, it was this matte scotch tape but it works exactly how i wanted it to
Comment: And I thought it stood for 'Plumber's Tape For Everything...
Comment: I settled on #1 but as the son of a plumber, #2 is never too far away in my head for 'threaded things'.
Comment: Amazing what 30 pence-worth of tape can do ;-)
Comment: Ahh - I only just noticed your edit - You shouldn't use any kind of sticky tape, it will come back to haunt you. There's a really specific reason to use PTFE, & it's because it never changes state, doesn't get sticky, doesn't dry out.
Answer: If yours has a blind hole - which doesn't go all the way through - you can use a small coil spring - 5mm or 6mm - depending on the diameter of the vib. arm. It will produce tension as it gets tightened onto. Or even a small cylinder of rubber in the hole. It is about the only part of Strats that, in my opinion,, never got sorted. All the ones I've used had a terrible fit between the thread in the vib. and the thread on the bar itself. If I played Strats regularly, I reckon I'd have put helicoils in.
Comment: Although it was probably lost on a guitar that old, most strats come with that spring in a plastic baggie in the case candy.
Comment: @PeteCon - interesting. Never having had a new Strat, I didn't know. But probably lost or eaten by the dog in the first five minutes!
Comment: Probably different for a one-off on a guitar, but I used to work with a lot of aluminium structures with helicoils; great while they work, but if anyone ever cross-threads one, you rupture the helicoil & end up with a stuck bolt in a spinning structure that then needs to be drilled or sawn out.
Comment: @Tetsujin - true - but if one crossthreads the original bridge, it's just as problematic. Which is probably why the thread is so sloppy - to stop that happening..!
Comment: Very probably. tbh, I't's not a problem I've really had to suffer. I think I started removing the trem & locking the bridge down in the 80's, about the same time everybody started getting into those huge swoop-dives; I decided enough was enough  ;)
Answer: I haven't had a strat in a few years, but if memory serves me I had a similar problem. On the Stew Mac website, I purchased a small spring to go into the assembly. It provided enough resistance to position it the way I liked. I hope that helps.
Here's a link:
https://www.stewmac.com/Hardware_and_Parts/Bridges_and_Tailpieces/Bridges_and_Tailpieces_for_Electric_Guitar/Tremolo_Parts/Trem_Arm_Tension_Spring.html

Strat tremolo bar has tightening issues


ANOVA or multiple t-tests when comparing pre-existing group means?

Question: I understand that Anova is preferred over multiple t-tests, but what exact is multiple t-tests?
Examples involving taking groups from the population (with the same population mean):

We have groups taken from a population, then tested with different treatment per group, then comparing the effect of the treatment between each pair of groups. E.g. students from a school are randomly split into 3 groups, each takes a different vitamin pill and we compare the fitness level between group 1 & 2, 2 & 3, 3 & 1.
You have two or more groups, and you are comparing multiple parameters. E.g. the you have two groups of students, one taken a vitamin pill and the other a placebo but we are comparing the fitness level, height, weight, fat content etc between the groups. This also require multiple t-tests and would be best to use Anova with some post-test correct method.

A different example involving comparing existing groups:

We take 5 different species of animals, subject them with the same treatment, and compare their response with each other. E.g. Sheep, cows, horses, chicken and mice were given a chemical injection and we recorded their change in fitness level (in the same manner).

If I want to compare the result in pairs (e.g. sheep and cows, cows and horses, horse and chicken, chicken and mice, etc) using t-test, is this still "multiple t-tests" (they don't have a common population mean...). Do I still have to use Anova?
Comment: When would it be useful to test for differences between the responses of different species? Wouldn't the thing of interest be whether each of the species responded? The latter question would not require any inter-species comparison.
Answer: The difference between your animal and your vitamin example is that one involved random assignment of participants to groups and the other did not. This has implications for causal inference, but it is not especially related to how you might analyse the data.
A standard approach when you have three or more groups and a numeric dependent variable is to first test the null hypothesis that all group means are equal. ANOVA provides a significance test for this. Then, if the ANOVA is significant then this is followed up by some procedure to understand the pattern of group means (e.g., post hoc tests, contrasts and so on).
The rationale for this approach is that the overall ANOVA provides some initial overall check of group mean differences before you commence examination of the group mean differences.
Furthermore, there is a difference between performing all possible pairwise comparisons using a t-test versus using common post-hoc tests (e.g., Tukey's). Post-hoc tests generally have some built-in component to protect against type-1 errors.
That said, you don't have to perform an ANOVA before performing follow-up tests. In fact, if there are particular comparisons that interest you, then you might want to perform those first, or you might argue that you have no interest in the overall ANOVA test.
The main thing is that you have a rationale for how you are doing your inference.


Suppose $f: G \to H$ is a homomorphism, Show that $f^{-1}(f(U)) = U \cdot \ker(f).$

Question: Please critique my proof:

Let $f: G \to H$ be a group homomorphism and let $U \leqslant G.$ Show that $f^{-1}(f(U)) = U \cdot \ker(f).$

$(i) \hspace{1mm} f^{-1}(f(U)) \subseteq U \cdot \ker(f):$ Let $a \in f^{-1}(f(U)).$ Then $f(a) \in f(U) \Rightarrow$ There exists $u \in U$  such that $f(u) = f(a).$ Let $v = u^{-1} a$, then $a = u v$. This shows $v \in \ker(f)$ since $f(v) = f(u^{-1} a) = f(u^{-1}) f(a) = f(u)^{-1} f(a) =  f(u)^{-1} f(u) =  1_H.$ Thus $a = uv \in U \cdot \ker(f).$
$(ii) \hspace{1mm} f^{-1}(f(U)) \supseteq U \cdot \ker(f):$ Now assume that $a \in U \cdot \ker(f).$ Then $a = uu'$ for $u \in U$ and $u' \in \ker(f).$ Thus $f(uu') = f(u)1_H = f(u) \in f(U)$ and so $uu' = a \in f^{-1}(f(U)).$ Combining $(i)$ and $(ii)$ completes the proof.
Comment: In (i) why is $a\in U$?
Comment: I think I made a mistake, now I am not sure how to continue.
Answer: There exists $u \in U$ such that $f(u) = f(a).$ Let $v = u^{-1} a$, then $a = u v$. $f(v) = f(u^{-1} a) = f(u^{-1}) f(a) = f(u)^{-1} f(a) = 1_H$. So $v \in \ker(f)$.


Capturing an hlist's ToList evidence as an implicit class parameter

Question: I'm trying to use shapeless's hlist to construct introspectable URL templates, but I'm having trouble with traversing my HList. The following doesn't compile:
import shapeless.{::, HList, HNil}
import shapeless.LUBConstraint._
import shapeless.ops.hlist.ToTraversable._

import scala.util.Try
import shapeless.ops.hlist._

object Path {
  def /(s: String) = Path(PathLiteral(s) :: HNil)

  def param[T](name: String) = PathParameter(name)
}

sealed trait PathSegment[+T]
case class PathLiteral(value: String) extends PathSegment[String]
case class PathParameter[+T](name: String) extends PathSegment[T]

case class Path[L <: HList : <<:[PathSegment[_]]#λ](segments: L)
                                                   (implicit ev: ToList[L, PathSegment[_]])
{
  def /(literal: String) = Path(PathLiteral(literal) :: segments)

  def /[T](param: PathParameter[T]) = Path(param :: segments)

  override def toString: String = s"Path(${segments.toList.reverse})"
}

object Test extends App {

  import Path.param
  val myPath = Path / "v1" / "pets" / param[String]("name") / "pictures"
  println(myPath)

}

It seems to me like the ToTraversable._ import covers the HNil case and the case of having the tail of an HList and a new head with the same Least Upper Bound. Obviously I'm either missing an import or misunderstanding everything.
I'm not sure if caching the evidence in the class as an implicit parameter is kosher; I'm doing it because

I don't want hlist details to leak into the external API
I need it for a nice toString
Comment: what's the problem?
Comment: It doesn't compile
Answer: The reason this doesn't work is the implicit which can prove:
ToList[PathLiteral :: L, PathSegment[_]] given

ToList[L, PathSegment[L]]
L <: HList

is this implicit def's type signature from hlists.scala:
implicit def hlistToTraversable[H1, H2, T <: HList, LubT, Lub0, M[_]]
  (implicit
    tttvs  : Aux[H2 :: T, M, LubT],
    u      : Lub[H1, LubT, Lub0],
    cbf    : CanBuildFrom[M[Lub0], Lub0, M[Lub0]]) : Aux[H1 :: H2 :: T, M, Lub0]

actually needs to know the type of the head of the list as well as the new item (H1 and H2), so it can't be constructed from what's available inside my class.
Some workarounds:

build List manually alongside the HList
case class Path[L <: HList](segments: L, segmentsList: List[PathSegment[_]]) {
  def /(literal: String) = Path(PathLiteral(literal) :: segments, PathLiteral(literal) :: segmentsList)
  def /[T](param: PathParameter[T]) = Path(param :: segments, param :: segmentsList)
  override def toString: String = s"Path(${segmentsList.reverse})"
}

push implicit parameters out to Path's methods
def printPath[L <: HList](path: Path[L])
                         (implicit ev: ToList[L, PathSegment[_]]) =
path.segments.toList.reverse.collect {
  case PathLiteral(value) => URLEncoder.encode(value, "UTF-8")
  case PathParameter(name) => s"<$name>"
}.mkString("/")

printPath(Path / "v1" / "pets"  / param[String]("name") / "pictures")
// v1/pets/<name>/pictures


Differentiation with respect to complex matrix

Question: I want to differentiate $f(X,Y) = \Vert XYA-b \Vert^2_2 $ with respect to $X$ and $Y$, $X$ and $Y$ are matrices with complex variable elements. In real cases, I know how to differentiate there is online tools such as http://www.matrixcalculus.org/#example-collapse7 ,But, I do not know how much differences exist between complex and real cases?
Answer: $
\def\bb{\mathbb}
\def\p#1#2{\frac{\partial #1}{\partial #2}}
$Denote the transpose, complex, and hermitian conjugates of $X$ as $(X^T,X^*,X^H)$ respectively. And denote the trace/Frobenius product using a colon
$$A:B = \sum_{i=1}^m\sum_{j=1}^nA_{ij}B_{ij} \;\doteq\; {\rm Tr}(A^TB)$$
This product is also defined for vectors by considering them as rectangular matrices. The cyclic property of the trace permits terms in such a product to be rearranged in many equivalent ways. For example
$$\eqalign{
&A:BC = B^TA:C = AC^T:B = I:A^TBC = I:BCA^T \\
&B:C = B^T:C^T = C:B = C^T:B^T \\
}$$
A useful guide is that the quantity on either side of the colon must have exactly the same dimensions.
The Frobenius norm of $X$ can be written using the Frobenius product as
$$\big\|X\big\|^2_F = X^*:X$$
The last tool is the $\bb{CR}$-calculus
(aka Wirtinger derivatives), wherein the real and imaginary components of a variable are treated independently under differentiation.
Write the function using the above ideas, and calculate its real Wirtinger derivative.
$$\eqalign{
 f &= (XYA-B)^*:(XYA-B) \\
df &= (XYA-B)^*:dX\,YA \\
   &= (XYA-B)^*A^TY^T:dX \\
\p{f}{X} &= (XYA-B)^*A^TY^T \\
}$$
Analogous calculations yield the gradient wrt the complex component of $X$
$$\eqalign{
\p{f}{X^*}   &= (XYA-B)A^HY^H \\
}$$
and wrt the components of $Y$
$$\eqalign{
\p{f}{Y}   &= X^T(XYA-B)^*A^T \\
\p{f}{Y^*} &= X^H(XYA-B)A^H \\
}$$
Comment: Thank you. It seems that complex and real matrix derivative have difference.


How to add item into a paragraphs

Question: I'm trying to create Paragraphs programatically, to store an Indesign File with the images linked to it, so I have my paragraph type with some fields

field_indesign_file : (limited to one value)
field_indesign_image : (illimited number of images)

Currently the creation is OK :
$paragraph = Paragraph::create([
  'type' => 'indesign',
  'field_indesign_file' => [
    'target_id' => $indesign->id(),
  ],
  'field_indesign_image' => [
    'target_id' => ${'image'.'3'}->id(),
  ],
]);

but I don't know in advance how many pictures I'll have attached to the indesign file, so Id' like to be able to add other values to the field_indesign_image.
I tried using
$paragraph->field_indesign_image[LANGUAGE_NONE][1]['value'] = [
        'target_id' => ${'image'.'1'}->id()
    ];
and
$paragraph->field_indesign_image->appendItem(
      [
        'target_id', ${'image'.'3'}->id()
      ]
    );
but none of this method worked, I didn't find a lot of documentation and sometimes answers to other topic are a bit too complicated for me to understand since I'm a beginner at drupal 8.
Answer: Finally I used a dynamic array
$tabImage[]["target_id"]
and inserted it
'field_indesign_rendition' => $tabImage,

How to add item into a paragraphs


clicar em um botao e aparecer a hora dentro de uma div

Question: Estou criando um sistema de ponto eletrônico simples, e estou tentando colocar a hora dentro de uma determinada div, no momento em que o usuario clicar no link entrar, a hora que ele clicou neste link aparecer dentro de uma div. O codigo do meu botao estar assim:
Estou usando o Html5 e CSS, de preferencia nessas linguagem, mas pode se em JaVASCRPIT, grato.

Hora da Entrada

  Entrar

Answer: A ação só pode ser feita com Javascript o código fica assim

    Hora da Entrada

    <button onclick="pegaData()" >Entrar</button>

Hora da Entrada

        Entrar


Drupal 7 EVA fields not rendered on unpublished nodes

Question: In a node type with 3 EVA fields, if I unpublish the node, the node view tab shows only the pink watermark "Unpublished" and the EVA fields are not rendered at all. The EVA related view does not have any publish filter nor any permission that prevents unpublished content to be rendered. All modules are updated to latest stable version. Any idea?
Answer: Solved using the View Unpublished module. This is not related to EVA module but it is related to the drupal unpublished nodes built in user permissions


Let $f$ be continuous on the real numbers. Let $c$ be in real number with $f(x)=c$ for all $x$ in $\mathbb{Q}$. Show that $f(x)=c$ on $\mathbb{R}$.

Question: Can someone solve this question?

Let $f$ be continuous on $\mathbb{R}$. Let $c$ be in real number with $f(x)=c$ for all $x$ in $\mathbb{Q}$.
  Show that $f(x)=c$ for all $x$ in $\mathbb{R}$.

thank you
Comment: What is the definition of continuity?  How is the density of $\mathbb{Q}$ in $\mathbb{R}$ useful?
Comment: [Related](http://math.stackexchange.com/q/344821/28900).
Answer: You could look at it with sequences, but there is actually a cleaner (but more abstract) way to look at it.
Since $f$ is continuous and $\{c\}$ is closed, $f^{-1}(c)$ is a closed set. But that closed set contains $\Bbb Q$. Therefore... (what can you say about the closure of a dense subset of $\Bbb R$?)
Comment: i need more explain not clear to me
Comment: A subset $D$ of a set $X$ is said to be dense in $X$ if the closure of $D$ is equal to $X$.
Answer: Hint: use limits, the density of $\Bbb Q$, and the fact $f$ is continuous.
Comment: Definition, property, definition, respectively.
Comment: how we can use limits, the density of Q, and the fact f is continuous.
Answer: Let $x\in \mathbb R$. Recall a very basic fact: If $f$ is continuous, and $p_n\to x$ then $f(p_n)\to f(x)$.
Now, can you explain why you can find a sequence of rational numbers $(p_n)$ such that $p_n \to x$?
With such a sequence, express $f(x)$ as $\lim_{n\to \infty} f(p_n) $. What do you know about $f(p_n)$? What does that tell you about the limit you just wrote? So, what is the value $f(x)$?
Answer: For any $x\in\Bbb R$, you can find $\left(x_n\right)_{n\in \Bbb N} \in \Bbb Q ^\Bbb N$ so that $x_n \underset{n\to+\infty}{\longrightarrow}x$
The fact that $f$ is continuous tells you that $f$ and $\lim\limits_{n\to+\infty}$ commute, i.e. $f\left(\lim\limits_{n\to+\infty}x_n\right)=\lim\limits_{n\to+\infty}f\left(x_n\right)$
So you have: $f(x)=f\left(\lim\limits_{n\to+\infty}x_n\right)=\lim\limits_{n\to+\infty}f\left(x_n\right)=\lim\limits_{n\to+\infty}c=c$


FreeBSD Established Connections Maxing out at 300

Question: We've previously had issues in our environment where it seemed we were reaching FreeBSDs max connection limit. We took action demonstrated by http://nginx.org/en/docs/freebsd_tuning.html and bumped up our connections limit to 500: kern.ipc.somaxconn: 500
We're still having issues where we expect to see additional connections from clients to this particular server and we are not, they're missing.
We don't know whether this is an application issue or a networking issue. But I was wondering if there is some other limit we're hitting now, maybe with max number of established connections?
Here's some graphs showing our connection behavior which looks strangely like it's limited at 300 connections:

Approximate number of missing commands on our server ^
EDIT:
Additional details about the application: The application is a tclsh (tcl shell) listening on a specific tcp port using the socket application to receive connections. Maybe this is some tcl-based limitation or a socket application limit?
Troubleshooting Details:
When I run nmap to basically "ping" the desired port over and over again
for i in {1..600}; do nmap -p 2069 serverIP; done

I seem to get the following with netstat:
netstat -Lan | grep 2069
tcp4  193/0/128      *.2069
tcp4  193/0/128      *.2069
tcp4  193/0/128      *.2069
tcp4  193/0/128      *.2069

This seems to mean that I am actually maxing out kern.ipc.somaxconn defaults. But we have already set that value to much higher than the default.
Even when I monitor established connections using:
netstat -an | grep 2069 | wc -l

I only get a grand total of 192 connections on 2069. Meaning it's not accepting more on that particular port.
Comment: I would use a benchmarking tool like apachebench (ab) to first determine if there is actually a limit you are hitting.  I would also take tcpdumps of the traffic during this time to see what's actually happening.  You'll have to determine the cause before you can find a proper solution.
Comment: I'm just wondering if there is any other inherit limits with max number of free connections or some other kind of network/tcp limits I might be hitting. Debugging this particular application is not very easy like it would be with apache as it is an in-house custom piece of software that infrastructure team does not have ownership of.
Comment: It's most likely application scalability issue not connected to kernel.
Comment: I suspect this, but I'm not familiar enough with kernel limits to definitively say so. Any good methods of proving this? How can I easily open additional established connections and prove it to be an application issue?
Comment: Additional details about the application: The application is a tclsh (tcl shell) listening on a specific tcp port using the socket application to receive connections. Maybe this is some tcl-based limitation or a socket application limit?
Answer: Seems like it was actually an application limit. The process listening on the 2069 socket was built with a max number of 192 listen connections.
I'm assuming a lot of applications are built like with these limits in place and its likely that somaxconn just increases total allowable listening sockets vs what the application is actually built for.
Answer: File handles come to my mind. First check with ulimit -n (or, depending on the shell, limit -n) if it returns 1024. If it does, bump up the file handle limit with ulimit -n 16384, limit -n 16384 or so. See if that helps.
Comment: Doesn't look like a file handle limit. Looks like a connections per socket limit.


Adicionar Texto Em textbox em determinada posição C#

Question: Olá, estou desenvolvendo um software odontológico o qual uma das funções é de selecionar um dente em um button e adicionar o nome deste dente em uma textbox. Até ai sem problemas, mas a questão é que essa textbox é referente a observações, e gostaria que o nome de cada dente selecionado, fosse adicionado na textbox em linhas diferentes e não lado a lado. Então conforme cada button referente a cada dente é selecionado vai adicionando o nome dos dentes um em cada linha.
Por exemplo, quando clico em button1 é adicionado o texto "Bot1" na textbox e assim por diante, o problema é que caso eu clique em mais de um button o texto deve ir para linhas diferentes e não na mesma. É isso que eu gostaria mas não consigo desenvolver uma logica para fazer isso alguém tem alguma ideia?
segue o evento click que estou usando nos buttons:
private void button1_Click(object sender, EventArgs e)
    {
        string Texto = txtObservacao.Text;
        txtObservacao.Text += "Terceiro Molar Inf.Direito (48):";
        if (btnMolar48.BackColor == Color.FromArgb(150, Color.LightSeaGreen))
        {
            btnMolar48.BackColor = Color.Transparent;
            txtObservacao.Text = Texto.Replace("Terceiro Molar Inf.Direito (48):", "");
        }
        else
        {
            btnMolar48.BackColor = Color.FromArgb(150, Color.LightSeaGreen);
        }
    }

    private void btnMolar47_Click(object sender, EventArgs e)
    {
        string Texto = txtObservacao.Text;
        txtObservacao.Text += "\n" + "Segundo Molar Inf.Direito(47):";
        if (btnMolar47.BackColor == Color.FromArgb(150, Color.LightSeaGreen))
        {
            btnMolar47.BackColor = Color.Transparent;
            txtObservacao.Text = Texto.Replace("Segundo Molar Inf.Direito(47):", "");
        }
        else
        {
            btnMolar47.BackColor = Color.FromArgb(150, Color.LightSeaGreen);
        }
    }`

Obrigado.
Answer: Existem, basicamente, dois tipos de quebras de linha CR (carriage return - \n)  e LF (line feed - \r).
Você pode ler um pouco sobre isso aqui em Qual a diferença entre carriage return e line feed?
Possivelmente você está usando o tipo o errado, para evitar esse tipo estresse e até mesmo para ter completa certeza de que seu código funcionará mesmo em outras máquinas é possível usar o Environment.NewLine.
Exemplo:
textBox.Text = "Linha 1" + Environment.NewLine + "Linha 2";

Comment: Tem também os dois juntos, que é o `\r\n`. Só não sei o nome dele. E se não me engano, o `Environment.NewLine` usa este valor mencionado.
Comment: É a junção dos dois (seria CRLF). O `Environment.NewLine` usa o caracter adequado de acordo com a plataforma que está sendo usada (o Windows usa ambos)
Answer: Consegui resolver meu problema utilizando System.Environment.NewLine.
string Texto = txtObservacao.Text;
            txtObservacao.Text += System.Environment.NewLine;
            txtObservacao.Text +=  "Segundo Molar Inf.Direito(47):";
            if (btnMolar47.BackColor == Color.FromArgb(150, Color.LightSeaGreen))
            {
                btnMolar47.BackColor = Color.Transparent;
                txtObservacao.Text = Texto.Replace("Segundo Molar Inf.Direito(47):", "");
            }
            else
            {
                btnMolar47.BackColor = Color.FromArgb(150, Color.LightSeaGreen);
            }
Peço perdão se não fui claro na minha questão a cima, mas quem respondeu, meu sincero obrigado!
Answer:  private void button1_Click(object sender, EventArgs e)
 {
 int h =3;

Button newButton = new Button();
    Button[] buttonArray = new Button[8];
for (int i = 0; i <= h-1; i++)
{
  buttonArray[i] = new Button();
 buttonArray[i].Size = new Size(20, 43);
  buttonArray[i].Name= ""+i+"";
  buttonArray[i].Click += button_Click;//function
  buttonArray[i].Location = new Point(40, 20 + (i * 20));
  panel1.Controls.Add(buttonArray[i]);

}  }

Comment: O que o seu código faz? Ele resolve o problema da pergunta? Se sim, tem como explicar-nos como ele faz isso?


Webpack dev server not serving output

Question: I have an application that's structured like this:
- root
  - app/
  - config/
  - css/
  - js/
  - public/
  - package.json
  - webpack.config.js

The React app is in the app folder and I'm publishing to the public folder. Here is my webpack configuration:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

var ExtractTextPlugin = require("extract-text-webpack-plugin");

var extractSass = new ExtractTextPlugin(
    "../css/style.css", {
        allChunks: true
    });

module.exports = {
    context: path.join(__dirname, "public"),
    devtool: debug ? "inline-sourcemap" : null,
    entry: {
        withify: '../app/main.jsx',
        fbauth: '../app/fbauth.jsx',
        fbuser: '../app/fbuser.jsx',
        fontawesome: 'font-awesome-webpack!../node_modules/font-awesome-webpack/font-awesome.config.js',
        styles: './css/style.scss'
    },
    output: {
        path: './js',
        filename: '[name].js'
    },
    resolve: {
        alias: {
            config: path.join(__dirname, 'config', process.env.NODE_ENV || 'development')
        }
    },
    module: {
        loaders: [
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015', 'stage-0'],
                    plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
                }
            },
            {
                test: /\.scss$/,
                loader: extractSass.extract(["css", "sass"])
            },
            {
                test: /\.(eot|woff|woff2|ttf|svg|png|jpg)?(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
                loader: 'url'
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "file-loader"
            }]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        }),
        extractSass
    ],
    externals: {
        fs: '{}',
        tls: '{}',
        net: '{}',
        console: '{}'
    }
};

Here is how I'm trying to start the app with npm run dev:
"scripts": {
  "dev": "./node_modules/.bin/webpack-dev-server --content-base public --inline --hot"
},

However, when my index.html tries to access the withify.js file that should be available in memory in the development server I'm getting a 404; what did I do wrong here?

  <title>Withify Application</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

  <link type="text/css" rel="stylesheet" href="/css/style.css">

Answer: Ok well a couple things:
Context is the folder where you tell webpack where to look for your entries.  So currently you are telling webpack to look into the public folder, but all of your entries live in "/app"
So your context would be something like:
context: path.join(_dirname, 'app')

This tells webpack look into root/app and find the entries which should now look like:
entry: [
        withify: 'main.jsx',
        fbauth:  'fbauth.jsx',
        fbuser:  'fbuser.jsx',
       ]

And your output will be something like this:
output:[
        path: path.join(__dirname, 'public', 'js')
        filename: '[name].js'
       ]

I think that should fix your issues as long as you are pulling everything from your public folder!
EDIT:
Try setting this as well in your output:
output:[
        path: path.join(__dirname, 'public', 'js'),
        filename: '[name].js',
        publicPath: '/js/'
       ]

Comment: Unfortunately, that results in the same error. I wonder why it won't serve the file via the `webpack-dev-server`?
Comment: Can you see withify.js inside your /public/js folder?
Comment: No, it doesn't produce any output, but that's not surprising because that's what it's supposed to do; it should be serving the file from memory.
Comment: Err duh, you're right.  I forgot I have mine setup to actually write my files to the public folder to render routes server-side.  The only thing I can think of is do you have a "/js" directory in your public folder?
Comment: Is it not working after setting the `publicPath` and a global path? I think the output files should be working with this. However, I am not sure your WebpackDevServer is serving your CSS. Are you getting them?
Comment: This post has nothing to do with CSS.  You can add this `` in your html file and server css that way, you can do it with webpack as well but again, has nothing to do with this post.

Webpack dev server not serving output


optimal subset / joint distribution prediction with machine learning

Question: How can I find the optimal subset of classes for a given entity?
For context, say that we have some customers and data about these customers transactions, and a set of possible products to advertise to them. And the objective would be to find the best subset of products to advertise to a customer, such that the joint probability of purchasing all the products is maximized.
Multi-label classification is an option to this problem, but to my understanding, the classical multi-label classification using sigmoid and log-loss over multiple classes is optimizing each class independently. I want to optimize jointly given the data.
I have seen joint optimization of sentences in Language translation using RNN's, where beam search is used to select the joint optimal sequence from a set of different sequence predictions. But here, we feed in the predictions back into the model in a natural way, thus getting a probability estimate conditoinal on the previous class prediction as well as the data up to that point.
Is a similar approach common for non-sequence models, where we can get a class probability estimate conditional on other class predictions as well as the data?
Some Resources:
https://www.depends-on-the-definition.com/guide-to-multi-label-classification-with-neural-networks/
https://guillaumegenthial.github.io/sequence-to-sequence.html
https://guillaumegenthial.github.io/image-to-latex.html
Comment: You could tackle this in two separate steps: a predictive modelling step in which you would regress the probability of purchase against all your available features/predictors, and an optimisation step which would use the trained model from step 1 as the objective function to a maximisation problem. Does that makes sense?
Comment: I am not sure if I understand completely. Do you mean one model for each product in the set of possible products, and then select the highest scoring products for that customer? That is an option, but I don't think that tackles the problem of each suggestion being independent of the other suggestions? Or did I misunderstand?
Answer: Try rulebased learning. https://cran.r-project.org/web/packages/arules/arules.pdf shows the vignette of the R-package
Comment: Thanks, I have some familiarity with market basket analysis from reading "Elements of Statistical Learning", and it is relevant. to the context I provide. But I would be interested in knowing if there are some ways of finding a joint optimal solution using known classification techniques.


Como listar os depedentes de um determinado funcionário com Laravel?

Question: Olá, acontece que estou dando meus primeiros passos no Laravel. Criei um banco de dados com duas tabelas (dependentes e funcionários), criei o crud de cada uma e exibir todo o sistema no html (bootstrap). O problema é que não estou conseguindo criar uma página em que, quando clicado no botão do funcionário, vai para a lista de dependentes desse usuário. A relação é de 1 para N.
Usando o Tinker eu consigo listar, mas gostaria de exibir ele no sistema, no html (como faço com a lista geral de dependentes e de funcionários).
Achei isso na documentação mas não obtive muitos resultados no projeto: https://laravel.com/docs/5.3/eloquent-relationships#querying-relations
namespace App;

use Illuminate\Database\Eloquent\Model;

class Funcionario extends Model {

    protected $fillable= [

        'codigo',
        'nome',
        'sexo'

    ];

    public function todosDependentes(){

        return $this->hasMany('App\Dependente', 'funcionario_id', 'id');

    }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class Dependente extends Model{
    protected $fillable = [

        'funcionario_id',
        'nome',
        'dataNascimento'

    ];

    public function funcionario(){

        return $this->belongsTo('App\Funcionario',  'id', 'funcionario_id');
    }

}

Comment: editei a postagem
Comment: Foi sim, muito obrigado!
Comment: Posta os dois `Models` na sua pergunta!!!
Comment: A resposta feita te esclarece, sim não e porque?
Answer: No seu Model Funcionario faça isso:
public function todosDependentes(){
    $this->hasMany('App\Dependente');
}

No seu Model Dependente faça isso:
public function funcionario(){
    return $this->belongsTo('App\Funcionario');
}

Quando você passar o objeto funcionario para a sua view pelo controller...
public function dependentes($id){
    $funcionario = App\Funcionario::find($id);
    return view('sua_view', compact($funcionario);
}

Você poderá listar os dependentes da seguinte forma para mostra o id dos dependentes por exemplo:
@foreach($funcionario->todosDependentes as $dependente)

{{ $dependente->id }}

@endforeach

Comment: Desculpa pelo feedback tardio, só agora pude testar. Funcionou muito bem, fico imensamente grato! Achei estranho porque da mesma forma que você fez eu tinha feito mas sempre dava erro de "Variável não declarada" na view, mas acredito que o problema era no foreach(). Mais uma vez, muito obrigado!
Comment: De nada @Ramones que bom que funcionou!


TextView content inside a Table Row gets cut off

Question: Firstly, I did a Google search and looked at StackOverFlow questions related to text being cut off for TextView. They did not help to solve the problem at hand, though they provided better understanding of certain things.
Here is my problem.
I am using TableLayout to display records with two text fields. Each row has two TextView cells. layout_width is set to wrap_content for all cells. But, even though the text is displayed in multiple lines, every line in that multi-line text is cut off at the end.
e.g.
   <?xml version="1.0" encoding="utf-8"?>
   </TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content">
   <TableRow>
        <TextView
            android:text="Notes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/visitation_notes" />
        <TextView
            android:text="Need to visit again. Visit till the doctor understands the importance of the Test. The problem is, it is very difficult to get appointment for the visit. Still, we need to keep trying till the point reaches to him/her."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/visitation_notes_value"
            android:textAlignment="viewStart"/>
   </TableRow>
   </TableLayout>

produced the view

Notes.Need to visit again. Visit till the doctor understands
  the importance of the Test. The problem is, it is very difficult
  to get appointment for the visit. Still, we need to keep trying
  till the point reaches to him/her.

with the text written in bold getting cut off.
If I use LinearLayout in place of TableLayout, it works fine. But, the problem with that is I can't have second column of each row starting at same position(with no hardcoding).
Please help me how to make sure TextView content won't get cut off.
Here is the screenshot of view produced for example given above.
Comment: Attach screenshot
Comment: I've attached screenshot now. Please check now.
Comment: What is width and height of TableRow? I tried your code and its working fine for me
Comment: Oh, I'm not sure what am I missing. For row also, width is set to match_parent and height is set to wrap_content.
Comment: I don't understand why the question is down voted. I did go through a plethora of questions on the same topic and found code snippets as answers with not enough explanation. As this is my first question, I'd be grateful if I get a feedback on what else I might've done before asking the question.
Answer: Do this
<TableRow>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Note" />

    <TextView
        android:layout_weight="3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:text="Need to visit again. Visit till the doctor understands the importance of the Test. The problem is, it is very difficult to get appointment for the visit. Still, we need to keep trying till the point reaches to him/her." />

</TableRow>

Comment: Thank you for your help. It does work. But, please help me why it works. As far as I know, `layout_weight` property helps us to divide extra space left after determining how much space each `View` takes in `LinearLayout`. I don't understand how this works when we set `layout_width=wrap_content` and the content size exceeds screen size in case of `TextView`.
Comment: you can adjust size using ems attribute . and if you set width=0dp still it work but you have to manage layout_weight value.
Comment: you can fix the width of textview by using ems.
Comment: Thank you. I ended up setting `layout_width = 0' for both `TextView`s and `layout_weight = 1` for first view and `layout_weight = 3` for the second(for better view). But, can you help me understand why my original code does not work ?
Answer: I got the truncated TextView inside a TableRow element issue resolved with the following code:
<TableRow>

    <TextView
        android:layout_gravity="right"
        android:text="Address: "
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingRight="10dp"
        android:text="123 W. Abc St., San Diego CA 90333"/>

</TableRow>

Comment: This works, would be worth to mention that layout_weight combined with wrap_content is what's making it work.
Answer: TableRow is a subclass/descendant of LinearLayout, so this is actually a problem of different default behavior in TableRow versus its superclass. If you have a horizontally-aligned LinearLayout containing multiple TextViews, Lint will generate a warning to explicitly turn the baselineAligned attribute on/off. But TableRow has the same ambiguity, without the convenient Lint warning.
So the layout error you're seeing is due to TableRow trying - and failing - to guess what you want the baseline alignment behavior to be. Add the android:baselineAligned attribute to each relevant TableRow and your layout should display correctly.
<?xml version="1.0" encoding="utf-8"?>
   </TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content">
   <TableRow
        android:baselineAligned="false">
        <TextView
            android:text="Notes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/visitation_notes" />
        <TextView
            android:text="Need to visit again. Visit till the doctor understands the importance of the Test. The problem is, it is very difficult to get appointment for the visit. Still, we need to keep trying till the point reaches to him/her."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/visitation_notes_value"
            android:textAlignment="viewStart"/>
   </TableRow>
   </TableLayout>

Answer: Try this code and suits for all devices
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bgcolor"
android:background="#ffffff"
android:orientation="horizontal"
android:padding="10dip" >

<LinearLayout
    android:id="@+id/llAvailableBookings"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center|top"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="25dip"
        android:gravity="center"
        android:textSize="24.5sp"
        android:visibility="gone" />

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:stretchColumns="*" >

        <TableRow>

            <TextView
                android:id="@+id/visitation_notes"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Notes" />

            <TextView
                android:id="@+id/visitation_notes_value"
                android:layout_width="1dp"
                android:layout_height="wrap_content"
                android:singleLine="false"
                android:text="Need to visit again. Visit till the doctor understands the importance of the Test. The problem is, it is very difficult to get appointment for the visit. Still, we need to keep trying till the point reaches to him/her."
                android:textAlignment="viewStart" />
        </TableRow>
    </TableLayout>
</LinearLayout>

Comment: @SatishThulva the main use of layout_weight is to split the section into number of parts, if you make your table row layout_width=1 the child layouts(Textview) will split the weight 1 in to two equivalent parts. which means if you given your child layout width 0dp then the parent layout weight 1 will automatically split the textviews into equivalent values(0.5 weight and 0.5 weight), i think now you can Upvote HsRaja answer.
Comment: Thanks for the reply. But, is n't singleLine deprecated ? Moreover, if it can be done, I prefer not to hardcode 0dp and 1dp for view width. Anyway, I tried the above code and the view doesn't look nice. It has hardly one word on each line.
Comment: Which device are you using for simulation?
Comment: I'm using Nexus 4. Does it make a difference ?
Comment: I updated my code please check with that and tested in all devices its perfect..Thanks in advance
Comment: Sometimes it may vary based on the device
Comment: Thanks again for your efforts. It does work. But, can you please explain why it works and why my method does n't work ?
Comment: oh great..according to my knowledge most of the table layouts are completely based on weight concepts and i think you did some slight mistake somewhere and i cannot able to find clearly what's exact problem in that part of code which you posted.....If you like my answer please vote for it...Thanks in advance
Comment: I can accept only after I receive a logical explanation of why the solution works. I need to figure out what went wrong with my approach too.
Comment: @SatishThulva you did not post entire xml code if you post means we can find what's your problem
Comment: @HsRaja : I left out the `TableLayout` element enclosing the `TableRow`elements which also has `layout_width` set to `match_parent`. I thought that won't create a problem. Nonetheless, I updated the question with full code.
Comment: @BKumar : Thank you for your comment. I learnt what `layout_weight` does. According to the docs, it helps us to divide **extra** space left after determining how much space each `View` takes in `LinearLayout` and I know that `TableRow` extends `LinearLayout`. So, if I set `layout_width = 0` and `layout_weight = 1` for both `TextView` elements, it produces a view with both `TextView`s taking half the space of row. This is what I did in the end.  The answer is also achieving desired effect using only `stretchColumns`, I believe. Can you help me understand why my original code doesn't work ?


Dropdown fica em branco com Bootstrap

Question: Após aplicação do Bootstrap o dropdown ficou em branco , não sei como proceder.
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>POP ART</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="../Home/css/CSS.css" rel="stylesheet">

                <form id="search-form" class="form-inline" role="form" method="post" action="//www.google.com/search" target="_blank">

                    <input type="text" class="form-control search-form" placeholder="">
                     <button type="submit" class="btn btn-primary search-btn" data-target="#search-form" name="q">
                    </button>

                        <nav1>

Sobre

                                      <button class="dropbtn">Artistas</button>

                                        Andy Warhol
                                        Yayoi Kusama
                                        Roy Lichtenstein
                                        Robert Rauschenberg
                                        Charles Fazzino
                                        Romero Britto

Eventos

Você Pop-Artista!

Quem Somos

                        </nav1>

O que é
Pop Art?

Saiba mais

O que é
Pop Art?

Saiba mais

O que é
Pop Art?

Saiba mais

OS ARTISTAS E SUAS OBRAS

                        ‹
                        ›

SOBRE

O Pop Art

ARTISTAS

Andy Warhol

Roy Lichtenstein

Robert Rauschenberg

Yayoi Kusama

Charles Fazzino

Romero Britto

EVENTOS

VOCÊ POP ARTISTA!

QUEM SOMOS

                        <form id="search-form" class="form-inline" role="form" method="post" action="//www.google.com/search" target="_blank">

                            <input type="text" class="form-control search-form" placeholder="">
                             <button type="submit" class="btn btn-primary search-btn" data-target="#search-form" name="q">
                            </button>

© Alunos, 2017

Comment: Vc tem que colocar o bootstrap e o jquery no  da página.
Answer: Partindo do principio que o bootstrap é o 3.3.7 a solução é a seguinte, fiz fiddle, faltam apenas adicionar algumas classes a determinados elementos.
https://jsfiddle.net/vg9zxcad/
NOTA: o html precisa de algumas alterações para ficar correctamente formatado:

 mudar para

<nav1>...</nav1> dever ser mudada para

- as tags form estão abertas e não fechadas

Dropdown fica em branco com Bootstrap


Expected a string but was BEGIN_OBJECT at line 1 column 2305 path $.items[0].author

Question: Hello there I have a little problem here.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected a string but was BEGIN_OBJECT at line 1 column 2305 path
  $.items[0].author

they say the error is here
rssObject = new Gson().fromJson(s,RSSObject.class);

I get json from this url:
loadRSSAsync.execute("http://primariagarleni.ro/category/uncategorized/feed/json");

I made this script to get json information from my wordpress.
Here is the function that return the infromations:
private void loadRSS() {
        AsyncTask<String,String,String> loadRSSAsync = new AsyncTask<String, String, String>() {

            ProgressDialog mDialog = new ProgressDialog(MainActivity.this);

            @Override
            protected void onPreExecute() {
                mDialog.setMessage("Asteptati...");
                //mDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                String result;
                HTTPDataHandler http = new HTTPDataHandler();
                result = http.GetHTTPData(params[0]);
                Log.v(TAG, "result=" + result);
                Log.v(TAG, "result=" + result);
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                mDialog.dismiss();
                rssObject = new Gson().fromJson(s,RSSObject.class);

                FeedAdapter adapter = new FeedAdapter(rssObject,getBaseContext());
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        };
        String RSS_to_Json_API = "https://api.rss2json.com/v1/api.json?rss_url=";
        StringBuilder url_get_data = new StringBuilder(RSS_to_Json_API);
        String RSS_link;
        RSS_link = "http://primariagarleni.ro/category/uncategorized/feed/atom";
        url_get_data.append(RSS_link);
        loadRSSAsync.execute("http://primariagarleni.ro/category/uncategorized/feed/json");

}

This String RSS_to_Json_API = "https://api.rss2json.com/v1/api.json?rss_url="; was the old method, but doesn't work very good because don't update the content on time.
RSSObject class
package com.gireada.garleni;
/*
 * Created by Gireada on 8/24/2017.
 */

import java.util.List;

public class RSSObject
{
    public String status;
    public Feed feed;
    public List<Item> items;

    public RSSObject(String status, Feed feed, List<Item> items) {
        this.status = status;
        this.feed = feed;
        this.items = items;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Feed getFeed() {
        return feed;
    }

    public void setFeed(Feed feed) {
        this.feed = feed;
    }

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }
}

Item.class
package com.gireada.garleni;

/*
 * Created by Gireada on 8/24/2017.
 */

import java.util.List;

public class Item
{
    public String title;
    public String pubDate;
    public String link;
    public String guid;
    public String author;
    public String thumbnail;
    public String description;
    public String content;
    public Object enclosure;
    public List<String> categories;

    public Item(String title, String pubDate, String link, String guid, String author, String thumbnail, String description, String content, Object enclosure, List<String> categories) {
        this.title = title;
        this.pubDate = pubDate;
        this.link = link;
        this.guid = guid;
        this.author = author;
        this.thumbnail = thumbnail;
        this.description = description;
        this.content = content;
        this.enclosure = enclosure;
        this.categories = categories;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getGuid() {
        return guid;
    }

    public void setGuid(String guid) {
        this.guid = guid;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Object getEnclosure() {
        return enclosure;
    }

    public void setEnclosure(Object enclosure) {
        this.enclosure = enclosure;
    }

    public List<String> getCategories() {
        return categories;
    }

    public void setCategories(List<String> categories) {
        this.categories = categories;
    }
}

Comment: You declare `author` as a String, but the json is returning something like this: `"author" : { ... }` containing other informations and not just a string!
Comment: Need more info. What is "s" variable? What is RSSObject class?
Comment: `author` is JSONObject instead of JSONArray
Comment: hello there s variable is returned from AsyncTask, i edit my post.
Comment: @Gireada show the code for your Item class.
Comment: @LeoAso i edit my post and put my Item class
Comment: System.out.println(String.format("The s string is : %s", s)); before the line with the error would give some uiseful diagnostic information at the console.
Comment: https://pastebin.com/sdu4wmb5 here is the result. It's http://primariagarleni.ro/category/uncategorized/feed/json this
Comment: @LucaNicoletti i can edit the string and delete the author? What did you think?
Comment: @LucaNicoletti thanks now it's work
Answer: Just as @Luca Nicoletti pointed out, you are using item.author as a String, when it is actually a JSONObject in the API response.
Change Author to a class with a name field and you should be fine.