text:
Q: How to fix this database schema to avoid inconsistency? I'm stuck on an issue of database design.  How do I fix this schema to avoid problems with consistent data down the road?
Let's consider three objects:
(django model definitions below)

*

*TaskType

*TaskGroup

*

*foreignkey to TaskType

*TrainingTask

*

*foreignkey to TaskType

*foreignkey to TaskGroup

The problem (at least I think this is a problem) is that if I have a TrainingTask, then it could potentially have inconsistent values for TaskType (via the direct foreign key and indirectly via the fk to TaskGroup).
And some "facts" about these objects:
TaskTypes hold meta information about TrainingTasks.  TaskGroups are for grouping tasks of the same type.  Elsewhere in my application I want to be able to take a TaskGroup and say "give me a random TrainingTask from this TaskGroup".

*

*There can be lots of TrainingTasks for a TaskType.

*All the TrainingTasks in a group should have the same type

*There can be lots of TaskGroups for a TaskType

*TrainingTasks with the same TrainingType can be in different TaskGroups

Also, I am doing all this in Django, and TrainingTask is a subclass of Task (using Multi Table Inheritance), and thus TrainingTask inherits the fk to TaskType from Task.  I would like to keep this structure so that whether I have a Task or TrainingTask in hand I can inquire of it what its TaskType is, e.g. task.task_type or trainingtask.task_type.  The relevant model definitions are:
from somewhere import Task

class TaskType(models.Model):
    ...fields...

class TaskGroup(models.Model):
    task_type = models.ForeignKey(TaskType)

class TrainingTask(Task):
    group = models.ForeignKey(TaskGroup)
    #task_type = models.ForeignKey(TaskType)  # FK to TaskType is contained in Task class

The current design "feels wrong" because of the multiple paths from TrainingTask to TaskType.  I know I can add a model level integrity check when I save a TrainingTask, which is better than nothing, but it stills seems like it could be better.  As a practical matter it also complicates using automatic fixtures like django-autofixture.
Is my feeling that "this is wrong" misguided?  Or, if not, how do I fix this schema, considering the "facts" given above (especially "All the TrainingTasks in a group should have the same type", which seems to me to preclude eliminating the fk from TaskGroup to TaskType).

A: The only thing that feels wrong to me is:

*

*If it is the case that EVERY TrainingTask MUST have a TaskGroup, and their task_type's must be the same

*Then you can get rid of the TrainingTask.task_type altogether since it will have access to that through TrainingTask.group.task_type.

Otherwise,

*

*If TrainingTask can exist WITHOUT a TaskGroup,

*Then that would seem to me to be a sound way to do it.

If the second case is true, then to ensure there are no "inconsistent values  for TaskType", you can override the save() method of both TaskGroup and TrainingTask, so that if their task_type is changed, either remove all related Groups/Tasks or change the task_type of the related Groups/Tasks to the same one.


text:
Q: Android webapp :: landscape display fullscreen I have a small problem. I'm developing a webapp for android and I have been searching tirelessly to find a solution to display a fullscreen mediaplayer when turning the device to landscape (no address bar, just the media).
Much of the stuff out there suggest VideoView which is for native android apps only, however there is not much content on webapp media players and switching to fullscreen. Does anyone know of a solution, or what might work?
Any info sent across is much appreciated and I do apologize if a question has already been answered surrounding this subject.

A: If you are developing a web application that's designed specifically for the WebView, you can create interfaces between your JavaScript code and client-side Android code.
See this:

http://developer.android.com/guide/webapps/webview.html#BindingJavaScript

You can create a class that would detect the screen rotation and if the device is in landscape mode calls a javascript function that would change the mediaplayer to fullscreen.

A: Just write down in manifest file in Application tag

android:theme="@android:style/Theme.NoTitleBar"

I think it will be helpful for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OrmLite Complex query on 3 tables using QueryBuilder I am trying to do a query on three tables by using QueryBuilder from OrmLite.
My problem is that my final query returns no results, while doing the query only for Info, InfoFenomeno or Instruccion do return results.
public List<PasoInstruccion> consultar(Request request) {

    InfoRequest infoRequest = (InfoRequest) request;

    ArrayList<PasoInstruccion> pasos = new ArrayList<>();
    List<PasoInstruccion> pasosResult = null;

    try {
        QueryBuilder<Info, Long> infoQuery = LocalDBHelper.getInstance(context).getInfoDao().queryBuilder();

        QueryBuilder<InfoFenomeno, Long> fenomenoQuery = LocalDBHelper.getInstance(context).getInfoFenomenoDao().queryBuilder();
        fenomenoQuery.where()
                .eq(InfoFenomeno.COLUMN_FENOMENO, infoRequest.getFenomeno());

        infoQuery.join(fenomenoQuery);

        QueryBuilder<Instruccion, Long> instruccionQuery = LocalDBHelper.getInstance(context).getInstruccionDao().queryBuilder();
        instruccionQuery.where()
                .eq(Instrucciones.COLUMN_NIVEL_AFECTACION, infoRequest.getNivelAfectacion())
                .and()
                .eq(Instrucciones.COLUMN_CATEGORIA_INFO, infoRequest.getCategoria())
                .and()
                .eq(Instrucciones.COLUMN_AMBIENTE_INFO, infoRequest.getSituacion());

        QueryBuilder<PasoInstruccion, Long> pasoInstruccionQuery = LocalDBHelper.getInstance(context).getPasoInstruccionDao().queryBuilder();

        instruccionQuery.join(infoQuery);

        pasoInstruccionQuery.join(instruccionQuery);

        pasosResult = pasoInstruccionQuery.query();

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return pasosResult;
}

The structure on the DB is like this (simplified):
public class Info {

@DatabaseField(id = true, columnName = Infos.COLUMN_ID)
private long id;

@DatabaseField(columnName = Infos.COLUMN_NOMBRE)
private String nombre;

@ForeignCollectionField(eager = true, columnName = Infos.COLUMN_FENOMENO)
private ForeignCollection<InfoFenomeno> infoFenomenos;

@ForeignCollectionField(eager = true, columnName = Infos.COLUMN_INSTRUCCION)
private ForeignCollection<Instruccion> pInstrucciones;

}

public class InfoFenomeno {

@DatabaseField(generatedId = true, columnName = InfoFenomeno.COLUMN_ID)
private long id;

@DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = InfoFenomeno.COLUMN_INFO)
private Info info;

@DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = InfoFenomeno.COLUMN_FENOMENO)
private Fenomeno fenomeno;

}

public class Instruccion {

@DatabaseField(generatedId = true)
private long id;

@DatabaseField(columnName = Instrucciones.COLUMN_NIVEL_AFECTACION)
private String nivelAfectacionString;

@DatabaseField(columnName = Instrucciones.COLUMN_CATEGORIA_INFO)
private String categoriaInformacionString;

@DatabaseField(columnName = Instrucciones.COLUMN_AMBIENTE_INFO)
private String ambienteInformacionString;

@ForeignCollectionField(eager = true)
private ForeignCollection<PasoInstruccion> pPasosInstruccion;

@DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = Instrucciones.COLUMN_INFO)
private Info info;

}

public class PasoInstruccion {

@DatabaseField(id = true, columnName = PasoInstrucciones.COLUMN_ID)
private long secuencia;

@DatabaseField(columnName = PasoInstrucciones.COLUMN_NOMBRE)
private String nombre;

@DatabaseField(columnName = PasoInstrucciones.COLUMN_INSTRUCCION, foreignAutoRefresh = true, foreign = true)
private Instruccion instruccion;

}

Values in InfoRequest parameter are right.
May be that I am not using QueryBuilder the right way?
EDIT: SQL Statement
SELECT `pasoInstrucciones`.* FROM `pasoInstrucciones` INNER JOIN `instrucciones` ON `pasoInstrucciones`.`_instruccion` = `instrucciones`.`id` INNER JOIN `infos` ON `instrucciones`.`_info` = `infos`.`_id` INNER JOIN `infoFenomeno` ON `infos`.`_id` = `infoFenomeno`.`_info` WHERE ((`instrucciones`.`_nivelAfectacion` = 'BAJO' AND `instrucciones`.`_categoriaInfo` = 'ANTES' ) AND `instrucciones`.`_ambienteInfo` = 'HOGAR' ) AND (`infoFenomeno`.`_fenomeno` = 6 )

Thanks in advance.


text:
Q: C lang: Palindromes using pointers I am having trouble fixing this code and just not having luck with it. I have to use pointer instead of integers to keep track of the position of the array. I keep getting segmentation fault, so I am going out of bounds of the array. Can someone please explain what I am doing wrong. I tried multiple ways to as *(msg + (*count)++) and msg[(*count)++]
Edit: Please ignore printf("%d", *(count++)). I was testing what was the value.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

#define N 50

int main()
{
    int i, j, *count;    char ch, msg[N], msg1[N];    bool flag = true;
    count = 0;
    // Getting user-defined input
    printf("Enter a massage: ");

     printf("%d", *(count++));
    ch = getchar();
    while(ch != '\n' || *count == N) {
;
        msg[(*count)++] = ch;  //msg[(*count)++]
        ch = getchar();
     } // end of while loop

    // Printing user-defined input
    printf("User-defined input: ");
    for(count = 0; *(msg+ *count); count++)
       printf("%c", *(msg+ *count));
    printf("\nNumber of characters is %d\n", *count);

    // Sanitiazation of the msg array (i.e., removing special characters)
    i = 0;
    for(j = 0; msg[j]; j++) {
       if(isalpha(msg[j]))
              msg1[i++] = tolower(msg[j]);
    } // end of for loop

   // Palindrome test
   for(j = 0; msg1[j]; j++) {
      if(msg1[j] != msg1[i-j-1]) {
      flag = false;
      continue;
      }
    } // end of for loop

   // Printing final decision
   if(flag)
      printf("Palindrome\n");
   else
      printf("Not palindrome\n");

   return 0;
} // end of main


text:
Q: changing html cell colour back to default automatically I have a html table where the cell colours are changed dependent of data pulled in from mysql using php and the colours update on the table without having to refresh the page however the issue im currently having is the cells start off grey but when the value has stopped being pulled into the html the cell doesnt go back to grey any help on how i can do this?
Sorry i should have included the css
current code is as followed:
css:
table, td, th {
border: 1px solid black;
cellpadding: 2;
cellspacing: 2;
width: "100%";
height: "100%";
text-align: center;
vertical-align: middle;
font-size: 48px;
background-color: #8F8F8F;
}

html:
$(document).ready(function() {
    for (var i = 0; i < 10; i++) {
        var row = $('<tr>').appendTo("#zoning tbody");
        for (var j = 1; j < 11; j++) {
            $(`<td class='${i * 10 + j}'>${i * 10 + j}</td>`).appendTo(row);
        }
    }

    $.get('php/beacon.php', function(response) {
        console.log(response);
        var row;
        response.forEach(function(item, index) {
            console.log(item);
            $(`td.${item.beacon}`).css('background-color', item.location);
        });
    });

    function upateTable() {
        $.get('php/beacon.php', function(response) {
            response.forEach(function(item, index) {
                console.log(item);
                $(`td.${item.beacon}`).css('background-color',
item.location);
            });
        });
    }
    var updateTableInterval = setInterval(upateTable, 15000);
});

A: Maybe have a default class that's a grey background, then make a reset function that brings all cells back to this default color before you get the answer you your query to PHP?

A: Nowhere in your code do you set the colour to Grey. Your best bet is to include code in the updateTable() function.
You can use a jquery filter to pull out all the non-grey cells and turn them grey before recolouring based on your ajax as you do there.
$('td').filter(function() {
     return $(this).css('background-color') != '#8F8F8F';
}).css('background-color','#8F8F8F');

Alternatively using classes I would recommend:
In your line where you set the background color to also set a class which is used to flag the coloured cells
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');

then later you can simply uncolour all of the flagged cells
$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');


text:
Q: Joomla configuration.php database settings running under Azure and MySql-In App I'm running Joomla under Azure using the MySQL In-App option for the database. Everything has gone well, but I have been unable to get the database config variables in JConfig to pull dynamically from the MYSQLCONNSTR_localdb environment variable.
I've tried the MS suggested solution posted here https://blogs.msdn.microsoft.com/azureossds/2016/12/09/mysql-in-app-configuration-for-php-content-management-systems/, and have tried various ways of extracting the information from the environment variable and setting the variables to the results, all with no success. The only thing that seems to be working is hard-coding the host address which is .. problematic.
An example might be something like this:
class JConfig {
...
$hostVar = getenv("MYSQLCONNSTR_localdb");
$hostArray = array();
foreach( explode( ';', $hostVar ) as $substr )
    {
    $asplode = explode('=', $substr);
    $hostArray[ $asplode[0] ] = $asplode[1];
    }
public $host = $hostArray['Data Source'];
...

So far all variations from the hard-coded address have been 'Error.' on the front end.

A: I moved the assignment to the constructor of the JConfig class.
With this I'm able to dockerize it nicely.
class JConfig {

  public $smtpuser;
  public $smtppass;
  public $smtphost;
  public $host;
  public $user;
  public $password;
  public $db;
  function __construct() {
    $this->smtpuser = getenv('SMTP_USER');
    $this->smtppass = getenv('SMTP_PASSWORD');
    $this->smtphost = getenv('SMTP_HOST');
    $this->host = getenv('JOOMLA_DB_HOST');
    $this->user = getenv('JOOMLA_DB_USER');
    $this->password = getenv('JOOMLA_DB_PASSWORD');
    $this->db = getenv('JOOMLA_DB_NAME');
  }


text:
Q: Opening a window in a horizontal split of a vertical split I want have both NERDTree and TagList open at the same time, but I don't need for them to have the whole height of the screen. Instead I would like to have them split horizontally within a single vertical split.
More specifically, I want to be able to open one, say NERDTree, and have it take up the full height of the screen. Then when I open TagList, to have it horizontally split with the already open NERDTree window.
Is there a way to do this? Possibly even a non 'specific to these two plugins' way?

A: NERDTree and Taglist aren't going to open inside splits.
Let's say you have a split buffer on the left (for eg. source code), and Taglist on the right.
You can put this in a function, and invoke it with a mapping:
NERDTree    " open NERDTree
wincmd J    " move NERDTree to the very bottom
wincmd k    " move the cursor to the above split (the source code buffer)
wincmd H    " move the split to the very left
wincmd l    " move the cursor back to the NERDTree split
resize 20   " resize the split height to 20
exe 'vertical resize ' . g:NERDTreeWinSize    " reset the split width

This is pretty dodgy, but it works. You'll see a brief visual glitch while the split jumps around the screen.

A: Horizontal split:
:split

Vertical split:
:vsplit

Then when you have split your screen how you prefer, open nerdtree inside the desired frame.
(Or you can use abbreviation :sp :vsp like suggested by @Vivek Pandey).

A: I've posted a solution in a duplicate post here:
NERDTree & TList in
It involves editing the 'taglist.vim' script a bit to add a new split option when opening.


text:
Q: HP Pavilion 15-P055 J1R84EA BeatsAudio I just installed Ubuntu 14.04 on the laptop in the title. It has BeatsAudio, but does not work in Ubuntu. It does work in Windows 8. I found this tutorial https://www.reddit.com/r/linux/comments/17sov5/howto_beats_audio_hp_laptop_speakers_on/ but I can not see any codec called "IDT". I can only see Realtec, so I can not see any of those pins metioned in the tutorial.
What could be the problem?
Thank you.

A: Open a terminal and try to launch alsamixer. Check if there is any option which contains the words "enhancement", "BeatsAudio" or "Equalizer". You can use M to enable/disable. I hope this helps.


text:
Q: Change value of property based on path in typescript I have an object that has a structure like the following:
{
 "Configuration" :
 { "ImportPath" : "C:\\Temp",
   "ImportSettings" : { "Style" : "Flat" }
 }
}

The I have a function that takes this object as a parameter and the JSON Path of the property. So in case of the ImportStyle the path would be:
"Configuration.ImportSettings.Style"

How can I change the value of the property based on the given path?
Something like:
public static ChangeProperty(config : any, path : string, newValue : string) : boolean{
     config[path] = newValue;
}


text:
Q: How to add payment conditions to AR outstanding items in a report on Exact Online? I am using Invantive Control to create an Excel report with some outstanding invoices information from Exact Online.
I have created a model with the block designer and I have the outstanding invoices information I need. Now I also want to know the payment condition of the account which is in debt, but there is no information on the payment condition on the AROutstandingItems table.
This is the query I have so far:
select division_code
,      division_name
,      number_attr
,      outstandingitems_ar_account_code_attr
,      outstandingitems_ar_account_name
,      description
,      invoicedate
,      duedate
,      currency_code_attr
,      invoiceamtfc
,      outstandingamtfc
,      invoiceamtdc
,      outstandingamtdc
from   aroutstandingitems
order
by     division_code
,      outstandingamtdc desc

How can I add the payment condition to my report?

A: Payment conditions are referenced from the account on the outstanding items. In order to get the (sales) payment conditions on an account, there are several options.

*

*Join the Accounts table and get the payment condition from there (from the field salespaymentcondition_code_attr and salespaymentcondition_description).
The SQL would look like this then:
select ...
,      act.salespaymentcondition_code_attr
from   aroutstandingitems aom
join   exactonlinexml..accounts act
on     aom.outstandingitems_ar_account_code_attr = act.code_attr

*Use an Excel function to get the payment condition: I_EOL_ACT_SLS_PAY_CODE.
The formula has two parameters: division_code and account_code_attr. The first is optional.
A valid call to the formula would thus be: =I_EOL_ACT_SLS_PAY_CODE(,"22") for the payment condition code for account with code 22 in the current Exact Online company. You can incorporate that in your SQL like this:
select ...
,      '=I_EOL_ACT_SLS_PAY_CODE("' + division_code + '", "' + outstandingitems_ar_account_code_attr + '")'
       pcn_code
from   aroutstandingitems

That would result in your model on sync receive the formula for retrieving the payment condition code. Remember to check the check box 'Formula' to ensure that the SQL outcome is treated as an Excel formula.

*The same as above, but then using column expressions:
select ...
,      '=I_EOL_ACT_SLS_PAY_CODE("$C{E,.,.,^,.}";"$C{E,.,.,^+3,.}")'
       pcn_code
from   aroutstandingitems

Remember to check the check boxes 'Formula' and 'Column expression' to ensure that the SQL outcome is treated as an Excel formula with $C column expressions.
The recommended option is to use column expressions, since these work across the widest range of deployment scenarios such as accountancy with hundreds of companies and the formulas are upgrade safe. SQL statements may need to be adapted with new releases of the Exact Online data model of Invantive.


text:
Q: Refresh BindingSource correctly I have a master-detail grid view on windows forms. I a very simple Repository (repo in code) that queries the database to get back DataTables.
At first I load the Data and define a relation like u see in the LoadData() method. Next, After I edit my Master table I want to refresh the view datasource. That's the unimplemented RefreshData(); method. If I'm refreshing after Edit I need the bindingsource not to lose the "current" row.
Here is the code:
    public void LoadData()
    {
        //define the Bindingsource and 2 Datatables.

        binder = new BindingSource();
        tbTaxPayers = repo.GetTaxPayersDataTable(-1);
        tbLinkedOrganizations = repo.GetTaxPayersLinkedOrganizations();

        //create a dataset to define the relation so that the view can pick it up
        ds = new DataSet();
        ds.Tables.Add(tbTaxPayers);
        ds.Tables.Add(tbLinkedOrganizations);
        ds.Relations.Add("LinkedOrganizations", tbTaxPayers.Columns["CLI_ID"], tbLinkedOrganizations.Columns["LCC_CLI_ID_PARENT"]);

        //set datasource to the main table.
        binder.DataSource = tbTaxPayers;
        view.LoadData(binder);
    }

    public void RefreshData()
    {
       // how to refresh without overhead ? and without losing focus if I just edit ?
    }

EDIT:
By doing the next code it works but I have to create a new DataSet with every refresh. And it smells to me cause it almost a duplicate of my LoadData() method.
public void RefreshData()
    {
        tbTaxPayers = repo.GetTaxPayersDataTable(-1);
        tbLinkedOrganizations = repo.GetTaxPayersLinkedOrganizations();
        ds = new DataSet();
        ds.Tables.Add(tbTaxPayers);
        ds.Tables.Add(tbLinkedOrganizations);
        ds.Relations.Add("LinkedOrganizations", tbTaxPayers.Columns["CLI_ID"], tbLinkedOrganizations.Columns["LCC_CLI_ID_PARENT"]);
        binder.DataSource = tbTaxPayers;
    }


text:
Q: displaying sum of all the fetched filed in mongodb-nodejs driver I have these following collections:
masters collection:
{
    "_id": ObjectId("5e3171af6dd4b53168f8a7b6"),
    "status": ["active"],
    "category": ["isDealer"],
    "mappedCustomers": [
        ObjectId("5e1ee75ba102a4638d195c15"),
        ObjectId("5e1ee75ba102a4638d195c16")
        ObjectId("5e1ee75ba102a4638d195c17")
    ],
    "phoneNo" : ########9,
    "name": "dealer 3",
    "dealerSAPCode": 63547860
}

orders collection:
{
    "_id" : ObjectId("5e26be38c13b7149d0a95555"),
    "frequency" : "FR",
    "orderCreatedBy" : ObjectId("5e1ee75ba102a4638d195c15"),
    "submittedTo" : ObjectId("5e3171af6dd4b53168f8a7b6"),
    "orderCreatedForDate" : ISODate("2020-01-31T18:30:00Z"),
    "totalOrder" : [
        {
            "tradeCopies" : 110,
            "subscriptionCopies":7,
            "freeCopies" : 0,
            "institutionalCopies" : 0,
            "_id" : ObjectId("5e293708683f4234a4a49e7c"),
            "publicationCode" : "TOI",
            "publicationName" : "Times of India",
            "editionName" : "chennai city",
            "productCode" : "TCE1"
        },
        {
            "tradeCopies" : 120,
            "subscriptionCopies":10,
            "freeCopies" : 0,
            "institutionalCopies" : 0,
            "_id" : ObjectId("5e293708683f4234a4a49e7b"),
            "publicationCode" : "ET",
            "publicationName" : "Economic Times",
            "editionName" : "chennai city",
            "productCode" : "ECE1"
        }]
},
{
    "_id" : ObjectId("5e26be38c13b7149d0a9890v1"),
    "frequency" : "FR",
    "orderCreatedBy" : ObjectId("5e1ee75ba102a4638d195c16"),
    "submittedTo" : ObjectId("5e3171af6dd4b53168f8a7b6"),
    "orderCreatedForDate" : ISODate("2020-01-31T18:30:00Z"),
    "totalOrder" : [
        {
            "tradeCopies" : 190,
            "subscriptionCopies":20,
            "freeCopies" : 3,
            "institutionalCopies" : 0,
            "_id" : ObjectId("5e293708683f4234a4a49e7c"),
            "publicationCode" : "TOI",
            "publicationName" : "Times of India",
            "editionName" : "chennai city",
            "productCode" : "TCE1"
        },
        {
            "tradeCopies" : 130,
            "subscriptionCopies":10,
            "freeCopies" : 2,
            "institutionalCopies" : 1,
            "_id" : ObjectId("5e293708683f4234a4a49e7b"),
            "publicationCode" : "ET",
            "publicationName" : "Economic Times",
            "editionName" : "chennai city",
            "productCode" : "ECE1"  }
            ]
},
{
    "_id" : ObjectId("5e27f736a42d441fe8a8957d"),
    "frequency" : "FR",
    "orderCreatedBy" : ObjectId("5e1ee75ba102a4638d195c15"),
    "submittedTo" : ObjectId("5e3171af6dd4b53168f8a7b6"),
    "orderCreatedForDate" : ISODate("2020-01-24T18:30:00Z"),
    "totalOrder" : [
    {
        "tradeCopies" : 210,
        "subscriptionCopies":14,
        "freeCopies" : 0,
        "institutionalCopies" : 0,
        "_id" : ObjectId("5e293708683f4234a4a49e7c"),
        "publicationCode" : "TOI",
        "publicationName" : "Times of India",
        "editionName" : "chennai city",
        "productCode" : "TCE1"
    },
    {
        "tradeCopies" : 310,
        "subscriptionCopies":17",
        "freeCopies" : 0,
        "institutionalCopies" : 0,
        "_id" : ObjectId("5e293708683f4234a4a49e7b"),
        "publicationCode" : "ET",
        "publicationName" : "Economic Times",
        "editionName" : "chennai city",
        "productCode" : "ECE1"
    }]
},
{
    "_id" : ObjectId("5e26be38c13b7149d0a9890h"),
    "frequency" : "FR",
    "orderCreatedBy" : ObjectId("5e1ee75ba102a4638d195c16"),
    "submittedTo" : ObjectId("5e3171af6dd4b53168f8a7b6"),
    "orderCreatedForDate" : ISODate("2020-01-24T18:30:00Z"),
    "totalOrder" : [
    {
        "tradeCopies" : 100,
        "subscriptionCopies":20,
        "freeCopies" : 4,
        "institutionalCopies" : 1,
        "_id" : ObjectId("5e293708683f4234a4a49e7c"),
        "publicationCode" : "TOI",
        "publicationName" : "Times of India",
        "editionName" : "chennai city",
        "productCode" : "TCE1"
    },
    {
        "tradeCopies" : 90,
        "subscriptionCopies:10,
            "freeCopies" :3 ,
    "institutionalCopies" : 1,
    "_id" : ObjectId("5e293708683f4234a4a49e7b"),
    "publicationCode" : "ET",
    "publicationName" : "Economic Times",
    "editionName" : "chennai city",
    "productCode" : "ECE1"  }]
}

This is a sample of 4 documents from the orders collection with different dates(orderCreatedForDate)
Documents 1 and 2 are created for tomorrow's orderorderCreatedForDate : ISODate("2020-01-31T18:30:00Z") by different customers (orderCreatedBy).
Documents 3 and 4: "_id":ObjectId("5e27f736a42d441fe8a8957d"),orderCreatedForDate : ISODate("2020-01-24T18:30:00Z") was created on D-7th]
I need to do several things.

*

*I need to show the sum of all {tradeCopies:300,subscriptionCopies:27,freeCopies,institutionalCopies } against the productCode for  all the mappedCustomers in the masters collection

*I need to also show the sum of {tradeCopies,subscriptionCopies,freeCopies,institutionalCopies } for D-7th day in the above case where orderCreatedForDate:ISODate("2020-01-24T18:30:00Z")
This is the output I want:
{
    "totalOrder": [
        {
            "productCode": "TCE1",
            "tradeCopies": 300,
            "subscriptionCopies": 27,
            "freeCopies": 3,
            "institutionalCopies": 0,
            "publicationCode": "TOI",
            "publicationName": "Times of India",
            "editionName": "chennai city",
            "previousWeekCopies": [{
                "tradeCopies": 310, "subscriptionCopies": 34,
                "freeCopies": 4, "institutionalCopies": 1,
            }]
        },
        {
            "productCode": "ECE1",
            "tradeCopies": 250,
            "subscriptionCopies": 20,
            "freeCopies": 2,
            "institutionalCopies": 1,
            "publicationCode": "ET",
            "publicationName": "Economic Times",
            "editionName": "chennai city",
            "previousWeekCopies": [{
                "tradeCopies": 400, "subscriptionCopies": 27,
                "freeCopies": 3, "institutionalCopies": 1,
            }]
        }
    ]
}

Please have a look at this if this can be achieved.

A: You can do this with the aggregation pipeline.  Here is the code exported for Node:

    [
      {
        '$match': {
          '$or': [
            {
              'orderCreatedForDate': new Date('Fri, 31 Jan 2020 05:00:00 GMT')
            }, {
              'orderCreatedForDate': new Date('Fri, 24 Jan 2020 05:00:00 GMT')
            }
          ]
        }
      }, {
        '$unwind': {
          'path': '$totalOrder',
          'includeArrayIndex': 'string'
        }
      }, {
        '$group': {
          '_id': {
            'productCode': '$totalOrder.productCode',
            'date': '$orderCreatedForDate'
          },
          'tradeCopies': {
            '$sum': '$totalOrder.tradeCopies'
          },
          'subscriptionCopies': {
            '$sum': '$totalOrder.subscriptionCopies'
          },
          'freeCopies': {
            '$sum': '$totalOrder.freeCopies'
          },
          'institutionalCopies': {
            '$sum': '$totalOrder.institutionalCopies'
          },
          'productCode': {
            '$last': '$totalOrder.productCode'
          },
          'publicationName': {
            '$last': '$totalOrder.publicationName'
          },
          'editionName': {
            '$last': '$totalOrder.editionName'
          },
          'publicationDate': {
            '$last': '$orderCreatedForDate'
          }
        }
      }, {
        '$sort': {
          'publicationDate': 1
        }
      }, {
        '$group': {
          '_id': '$_id.productCode',
          'tradeCopies': {
            '$last': '$tradeCopies'
          },
          'previousTradeCopies': {
            '$first': '$tradeCopies'
          },
          'subscriptionCopies': {
            '$last': '$subscriptionCopies'
          },
          'previousSubscriptionCopies': {
            '$first': '$subscriptionCopies'
          },
          'institutionalCopies': {
            '$last': '$institutionalCopies'
          },
          'previousInstitutionalCopies': {
            '$first': '$institutionalCopies'
          },
          'freeCopies': {
            '$last': '$freeCopies'
          },
          'previousFreeCopies': {
            '$first': '$freeCopies'
          },
          'productCode': {
            '$last': '$productCode'
          },
          'publicationName': {
            '$last': '$publicationName'
          },
          'editionName': {
            '$last': '$editionName'
          },
          'publicationDate': {
            '$last': '$publicationDate'
          }
        }
      }, {
        '$project': {
          'productCode': 1,
          'publicationName': 1,
          'editionName': 1,
          'publicationDate': 1,
          'tradeCopies': 1,
          'subscriptionCopies': 1,
          'institutionalCopies': 1,
          'freeCopies': 1,
          'previousWeekCopies': [
            {
              'tradeCopies': '$previousTradeCopies',
              'subscriptionCopies': '$previousSubscriptionCopies',
              'freeCopies': '$previousFreeCopies',
              'institutionalCopies': '$previousInstitutionalCopies'
            }
          ]
        }
      }
    ]

Let's take a look at what is happening in each stage:

    [{$match: {
      $or: [ {orderCreatedForDate: ISODate('2020-01-31T05:00:00.000+00:00')},
      {orderCreatedForDate: ISODate('2020-01-24T05:00:00.000+00:00')}]
    }},

We begin by matching for orders that have the dates we care about.
    {$unwind: {
      path: "$totalOrder",
      includeArrayIndex: 'string'
    }},

Then we unwind the totalOrder array.  This creates a document for every order.

    {$group: {
      _id: {productCode: "$totalOrder.productCode", date: "$orderCreatedForDate"},
      tradeCopies: {
        $sum: "$totalOrder.tradeCopies"
      },
      subscriptionCopies: {
        $sum: "$totalOrder.subscriptionCopies"
      },
      freeCopies: {
        $sum: "$totalOrder.freeCopies"
      },
      institutionalCopies: {
        $sum: "$totalOrder.institutionalCopies"
      },
      productCode: { $last: "$totalOrder.productCode"},
      publicationName: { $last: "$totalOrder.publicationName"},
      editionName: { $last: "$totalOrder.editionName"},
      publicationDate: { $last: "$orderCreatedForDate"}
    }},

Then we group the documents by product code and date.  This allows us to generate the sums we need.

    {$sort: {
      publicationDate: 1
    }},

Then we sort our documents so we know that the older documents are first.

    {$group: {
      _id: "$_id.productCode",
      tradeCopies: {
        $last: "$tradeCopies"
      },
      previousTradeCopies: {
        $first: "$tradeCopies"
      },
      subscriptionCopies: {
        $last: "$subscriptionCopies"
      },
      previousSubscriptionCopies: {
        $first: "$subscriptionCopies"
      },
      institutionalCopies: {
        $last: "$institutionalCopies"
      },
      previousInstitutionalCopies: {
        $first: "$institutionalCopies"
      },
      freeCopies: {
        $last: "$freeCopies"
      },
      previousFreeCopies: {
        $first: "$freeCopies"
      },
      productCode: { $last: "$productCode"},
      publicationName: { $last: "$publicationName"},
      editionName: { $last: "$editionName"},
      publicationDate: { $last: "$publicationDate"}
    }},

Next we group our documents together by product code so we can create a single document for each product code.

    {$project: {
      productCode: 1,
      publicationName: 1,
      editionName: 1,
      publicationDate: 1,
      tradeCopies: 1,
      subscriptionCopies: 1,
      institutionalCopies: 1,
      freeCopies: 1,
      previousWeekCopies: [{
        tradeCopies: "$previousTradeCopies",
        subscriptionCopies: "$previousSubscriptionCopies",
        freeCopies: "$previousFreeCopies",
        institutionalCopies: "$previousInstitutionalCopies"
      }
        ]
    }}]

Finally, we project the fields we need in the format we need them.
Here are some screenshots so you can see visually what is happening in each stage.

For more on how to use the aggregation pipeline with Node.js, see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-analyze-data-using-the-aggregation-framework.  I also highly recommend MongoDB University's free course on the aggregation pipeline:  https://university.mongodb.com/courses/M121/about


text:
Q: How to allow both anonymous and authenticated access to the Azure Web App I have a Asp.Net Core Razor Pages web app that has some pages Azure AD authenticated and some unauthenticated/anonymous. It works perfectly when I run in the debug mode in Visual Studio. When I publish the same on the Azure Web App I can either make the entire web app Authenticated or Unauthenticated. Is there a way to allow both at the same time?

A: From the azure portal, we can see that azure webapp does not support simultaneous settings. But we can set it from the code, and Noah Stahl and Tiny Wang are correct.
Phenomenon:
Create a simple application that does not include login, or simply put an index.html file, we can set it on the portal to perform the third-party login function.
As you can see, you can only choose one, Authenticated or Unauthenticated. And if you choose Authenticated, you can also choose one of the providers. This function is the simplest function in the portal.
Suggestion:
If you want to achieve multiple third-party logins, you still need to start from the code level so that you don't need to set up on the portal. It should be too simple on the portal.
You can refer below official doc:
Facebook, Google, and external provider authentication in ASP.NET Core

When you implement it, you can still access other resources in the unlogged state. When you need to log in, all supported third-party buttons will appear on the login page. Click the button to log in.
The option setting in the portal is a restriction on the current global access to the entire website.


text:
Q: iOS UIButton Touch Drag Enter not working as expected? I'm trying to create a button which will trigger an action when the user's touch is brought anywhere into the button (whether they touch down inside, or drag from outside to inside the button). Essentially, I need to create a way to trigger the action whenever a finger is inside of the button.
"Touch drag enter" combined with "touch down inside" sounds like it would do the job, but it seems to be working differently than what I need.
Also, I'd prefer if it can be done in storyboard rather than hard code (like touchesBegan/moved), but if there is no other way that's okay.

A: Touch drag enter will only gets called, when u start the touch inside the control and drag it outside the bounds of the control and then drag it back inside the control, without leaving the touch. So you need to subclass your button and achieve the required functionality.

A: Either you will have to bind all the events one by one with the method you are intending to invoke on button press from IB.
OR
You can try register your button for UIControlEventAllTouchEvents inside your code. Here is an example that might be helpful
[_btnRoundRect addTarget:self action:@selector(btnPressedAction) forControlEvents:UIControlEventAllTouchEvents];

- (void)btnPressedAction{
    NSLog(@"Bttn pressed");
}

A: When setting the connection in IB Touch Down should be what you're looking for. Any time the user's finger hits the button the action will be called.

A: Just had this problem and although I see this question is old, I guess someone might find it as well...
My solution was to use touchesBegan, touchesMoved, touchesEnded and touchesCancelled.
I disabled my buttons although you can turn them into UIViews I guess... then in touchesBegan I use .point(inside:) on all touch events and check on all buttons, calling the buttonDown function on the ones that are touched.
Then on touchesMoved I check again but using both the current touch position and the previous one to see if the touch entered a new button. Basically if a button is touched by the old one and not the new one I call the buttonUp funcion for that button. If it's the other way around I call the buttonDown funcion
Last, on the touchesEnded and touchesCancelled I just see what button is being touched and call the buttonUp function.
I've tested it with multitouch on a real device and in Mac Catalyst and both seem to work fine. It was a quick solution that didn't make it necessary to change anything else from the regular "buttons with target/actions" solution I had before...
Example:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) {
                    keyDown(b)
                }
            }
        }
    }

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) && !b.point(inside: touch.previousLocation(in: b), with:nil) {
                    keyDown(b)
                } else if b.point(inside: touch.previousLocation(in: b), with:nil) && !b.point(inside: touch.location(in: b),with:nil) {
                    keyUp(b)
                }

            }
        }
    }

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) {
                    keyUp(b)
                }
            }
        }
    }
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) {
                    keyUp(b)
                }
            }
        }
    }


text:
Q: Adding and removing class rules in jQuery Validate how we use addclassrules and removeclassrules in jquery plugin .
with an examples.
$('#form').validate({
});

if ($(this).attr("san") != "") {
    jQuery.validator.addClassRules("san" , { required: true });
    $.validator.addMethod("san", function() {
        required: true
    }, "Please enter your name");
}
else if ($(this).attr("san") == "") {
    jQuery.validator.removeClassRules("san");
}

A: Your code makes very little sense as you've posted it...
if ($(this).attr("san") != "") {
    jQuery.validator.addClassRules("san" , { required: true });
    $.validator.addMethod("san", function() {
        required: true
    }, "Please enter your name");
}
else if ($(this).attr("san") == "") {
    jQuery.validator.removeClassRules("san");
}

*

*$(this) does not represent anything in the context of your code.

*There is no such thing as removeClassRules() in the jQuery Validate plugin.

*You're using the .addMethod() method improperly.  This method is for creating new rules (methods) from scratch.  You must only put valid jQuery/JavaScript inside the function(){}.  required: true; inside of a function(){} is totally meaningless, and a syntax error.

*You're assigning the required rule to a class called san using addClassRules().  This seems unnecessary.  The whole purpose of the addClassRules() method is to combine multiple standard rules into one (called a compound rule) and assign that compound rule to a class.  Then the rules can be applied to input elements simply by using the class.

*You're trying to add a method called san, create a class rule called san, while you have an attribute called san.  Again, none of this makes any sense.

Quote OP:

"how we use addclassrules and removeclassrules in jquery plugin . with an examples."

You start by reading the documentation and looking at the posted examples.  As you can see, there is no such thing as a removeclassrules method.
Then when asking a question here, you would clearly describe what you want it to do, what's going wrong, and include enough code for a self-contained example, including the relevant HTML markup.
See:  How to create a Minimal, Complete, and Verifiable example

A:
You just add required set to false in elseif condition.

if ($(this).attr("san") != "") {
    jQuery.validator.addClassRules("san" , { required: true });
    $.validator.addMethod("san", function() {
        required: true
    }, "Please enter your name");
} else if ($(this).attr("san") == "") {
    jQuery.validator.addClassRules("san" , { required: false });
}

A: You can do validation like this also
jquery:

function test()
{
if ($("#txtText").val().trim() == "") {
                $("#txtText").focus();
                ValidateMessage("Please enter title.");
                return false;
            }
}
  function ValidateMessage(Message) {
            $("#pErrorMessage").html(Message);
            $("#dialogValidation").dialog('open');
        }

HTML

A: //this code is for setting the rules
$.validator.addClassRules({
location_name:{
location_name:true,
maxlength:30,
alphabates:true
}
});
//this code is for displaying the which validation message you want.
 $.validator.addMethod(
    "location_name", //name of a virtual validator
    $.validator.methods.required,
    "Please enter the city"
    );

location_name will be your class name for which you want to give validation.


text:
Q: Why does the uploadprogress for Alamofire never reach a completion of 1.0 during upload? I am able to successfully upload files using alamofire.  However, I am trying to track the progress of the upload.  What I am finding is that, although the upload is successful, as I can see my files successfully uploaded on to the server, the progress tracker never reaches 1.0.  It tends to end between 8.00 - (under 1.0) but never reaching 1.  This presents problems as I need to handle the completion of the file upload.
 Alamofire.upload(
        multipartFormData: { multipartFormData in
            for(key, value) in sendParamters{
                multipartFormData.append((value.data(using: .utf8)!), withName: key)
            }

            for fileURL in arrayURLToUpload{
                print("fileURL: \(fileURL)")
                multipartFormData.append(fileURL, withName: "file[]")
            }
    },
        to: UPLOAD_URL,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }

                /**TRACK PROGRESS OF UPLOAD**/
                upload.uploadProgress { progress in
                    print(progress.fractionCompleted) // NEVER REACHES 1.0

                    var progress = progress.fractionCompleted

                }
                /***/

            case .failure(let encodingError):
                print(encodingError)
            }
        }
    )

console:
 0.041737145652041
 0.521714320650513
 0.772137194562759

A: You just need to change the postition of
upload.uploadProgress { progress in
                print(progress.fractionCompleted) // NEVER REACHES 1.0

with
  upload.responseJSON { response in
            debugPrint(response)
        }

This is the correct usage:
Alamofire.upload(
        multipartFormData: { multipartFormData in
            for(key, value) in sendParamters{
                multipartFormData.append((value.data(using: .utf8)!), withName: key)
            }

            for fileURL in arrayURLToUpload{
                print("fileURL: \(fileURL)")
                multipartFormData.append(fileURL, withName: "file[]")
            }
    },
        to: UPLOAD_URL,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):

             /**TRACK PROGRESS OF UPLOAD**/
                upload.uploadProgress { progress in
                    print(progress.fractionCompleted)
                }
                /***/

                upload.responseJSON { response in
                    debugPrint(response)
                }

            case .failure(let encodingError):
                print(encodingError)
            }
        }
    )


text:
Q: How do you compute the stress-energy tensor for electromagnetism + gauge fixing term? I want to compute the stress-energy tensor for the following Lagrangian:
$$\mathcal{L} = -\frac{1}{4} F_{\mu \nu} F^{\mu \nu} - \frac{1}{2\xi} (\nabla_\mu A^\mu)^2$$
but I'm struggling with the gauge-fixing term. When taking variations with respect to the metric, it seems that it will involve many terms, some of then not clearly covariant. I am only interested in its value in Minkowski, but that is also hard to find.
By stress-energy tensor I mean the Hilbert one, defined as:
$$T_{\mu \nu} = \frac{-2}{\sqrt{-g}} \frac{\delta S}{\delta g^{\mu \nu}}$$
My attempt
I have attempted to include an auxiliary field, such that
$$\mathcal{L}' = -\frac{1}{4} F_{\mu \nu} F^{\mu \nu} + B \nabla_\mu A^\mu + \frac{\xi}{2} B^2$$
which becomes the original one after finding and imposing the equations of motion for $B$. But is it true that the two stress energy tensors are going to be the same? What I find is that
$$T_{\mu \nu} = \eta_{\mu \nu} \mathcal{L} + F_{\alpha \mu} F_{\beta \nu} g^{\alpha \beta} + \frac{4}{\xi} \partial_\alpha A^\alpha \partial_{(\mu} A_{\nu)} + \frac{2}{\xi} \partial_{(\mu} \left(\partial_\alpha A^\alpha \right) A_{\nu)} - \frac{1}{\xi} \eta_{\mu \nu} \partial_\rho(A^\rho \partial_\alpha A^\alpha)$$
in Minkowski, and after getting rid of the auxiliary field. Can this be correct? What if I integrate by parts the first term involving the auxiliary field, so that I get:
$$\mathcal{L}' = -\frac{1}{4} F_{\mu \nu} F^{\mu \nu} - \nabla_\mu B A^\mu + \frac{\xi}{2} B^2 = -\frac{1}{4} F_{\mu \nu} F^{\mu \nu} - \partial_\mu B A^\mu + \frac{\xi}{2} B^2 $$
given that $B$ is a scalar field. This seems to be giving me a different stress-energy tensor as well.

A: Well, it has been a week and I think I have convinced myself of the answer. Basically the solution was in the comments, but took me some time to understand. Indeed, as @marmot has said, the stress-energy tensor is an intrinsically off-shell object. Therefore, obtaining two seemingly different answer should not be a problem. Only when you project them on-shell (impose the equations of motion), you can expect to obtain a single, unique answer. .
The "two different" ways I propose of computing the tensor (i.e. with the Lagrangian $\mathcal{L'}$ containing $B \nabla_\mu A^\mu$ or, integrating by parts and using $\partial_\mu B A^\mu$), and the way that @Filipe Miguel explains (i.e. writing down the exact expression for the covariant derivative of $A^\mu$), end up giving the same answer after using the EOM.
Thank you very much everyone!


text:
Q: Spring Hibernate transaction management I have just started making a project using spring and hibernate. My DAO layer class extends HibernateDaoSupport. We are not using annotations.
Earlier, we were using struts, hence we used getTransaction, commit, rollback .. methods provided by Session class.
My requirement is very simple, for all DAO classes, if there is an exception, rollback otherwise commit. Please suggest a simplest way of introducing spring transaction management.

A: A few things are not clear from your question. My explanation follows based on below  assumptions -

*

*You are using spring to create a datasource and session factory

*You are using Java 5 or above and could use annotations.

Here is what your spring configuration would look like.
    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" value="jdbc:hsqldb:hsql://localhost:9001" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

<bean id="mySessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="mappingResources">
        <list>
            <value>product.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=org.hibernate.dialect.HSQLDialect
        </value>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="mySessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager"  />

Once this is set up, you could use spring transactional annotations on your DAO methods as shown below. Spring would take care of starting transactions, committing your transactions or rolling back your transactions when exceptions are thrown. If you have business services, you would ideally use transactional annotations on your services instead of DAOs.
@Transactional(propagation=Propagation.REQUIRED)
public class MyTestDao extends HibernateDaoSupport {
public void saveEntity(Entity entity){
    getHibernateTemplate().save(entity);
}
@Transactional(readOnly=true)
public Entity getEntity(Integer id){
    return getHibernateTemplate().get(Entity.class, id);
}
 }

Below code shows how transaction management could be achieve using spring's support for AOP rather than annotations.
    <!-- Define your 'myDatasource' bean and 'mySessionFactory' bean as shown in previous code snippet -->
<!--  Then follow the steps shown below -->

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />

<!-- this is the dao object that we want to make transactional -->
<bean id="testDao" class="com.xyz.daos.MyTestDao" />

<!-- the transactional advice  -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!-- all methods starting with 'get' are read-only -->
        <tx:method name="get*" read-only="true" />
        <!-- other methods use the default transaction settings (see below) -->
        <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>

<!-- ensure that the above transactional advice runs for any execution of
    a method in 'daos' package-->
<aop:config>
    <aop:pointcut id="allDaoMethods"
        expression="execution(* com.xyz.daos.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethods" />
</aop:config>

For additional details, please see -
Spring Declarative Transactions


text:
Q: Migrate old JDBC program to use XA What would I need to do if I want to migrate a program that is using old JDBC interfaces to support XA? I mean detail steps I need to do in the code.
The program is running on a single DB but the new features require to introduce a new schema and some old features need to support transactions across 2 schemas. We are using JBOSS.
What is the minimum set of steps to migrate this?
Thanks.

A: You did not indicate which version of JBoss you are using. I am assuming JBoss 5.
The minimal set of steps:

*

*Get an XA compliant JDBC driver for your database.

*Create a XA data source (e.g. `*-ds.xml) file to include the XA data source properties. See this link for configuration elements. There are several of them and some of them may apply or may not apply in your situation.

*Update /conf/jbossts-properties.xml for XA Recovery module if needed.

*You may also need to grant special privileges on the database system tables.


text:
Q: Solving a variant of the knapsack problem In this my problem, we have a list of n elements ( n not fixed and known) , all positives, containing probably duplicates.
I have a target K ( positif as well)
I would like a way to figure out the sub-set of elements for which the sum is :
Either equal to K
Either the smallest greater than K
So for example :
1,5,5,5,6,50,51
K = 100
The sub-set would be 50,51
I would like to know how to solve this problem ensuring the best way on complexity?
On a second step , it would be better to have the sub-set with smallest numbers ( if many)
Thanks for your help!


text:
Q: Wi-Fi on fedora keeps reconnecting Here are logs of
sudo journalctl -fu NetworkManager

and
sudo journalctl -b -g wlo1

Video
Screenshot
Additional info:
wifi.scan-rand-mac-address is set to no
Sometimes nmcli dev wifi list prints empty list, and i have to restart it so it will show my wifis again

A: According to this your issue might be solved by changing PCI-e ASPM policy to performance which can be done by adding pcie_aspm.policy=performance to your kernel boot parameters in GRUB.


text:
Q: How do I restore the MySQL root user's privileges? I accidentally removed most of the privileges from my MySQL root user, including the ability to grant privileges. Is there some way I can restore this user to its original state?

A: You might still be able to do an UPDATE on table user in database mysql:
USE mysql;
UPDATE user SET Grant_priv='1' WHERE User='root';
FLUSH PRIVILEGES;

If step 3 doesn't work, restarting the MySQL server will have the same effect.  If step 2 doesn't work, you need to restore mysql.user from backup.  If you don't have a backup, make a backup, reinstall MySQL and then selectively restore your backup, leaving out tables within the mysql database.
UPDATE
You're getting Access Denied during the first step.  At this point, you're down to the alternative solutions with backups.  There's no way (that I know of or can easily imagine) that you're recovering those tables any other way.
UPDATE 2
The exact error message is basically saying that in addition to losing root's grant privileges, you've dropped root's access to the mysql DB.  Without having access to that DB and without having grant privileges, the only way I can see back is to somehow obtain a fresh copy of the mysql DB.
Any chance you have a replication slave set up?


text:
Q: Train Error with CNN in Tensorflow I'm trying to set up a CNN to classify images with two possible outputs and I'm using Tensorflow to do this. I followed the tutorials and then moved on to adapting the CNN they had used to my problem, but it hasn't worked out very well.
The first thing I changed was how the images for my problem were loaded in. I have another script that writes the location of all the images along with their expected output (separated by a space). I used some code I found elsewhere to load in the images, which gives out the batches (label_batch and image_batch). However, as this format is different from the tutorial, I don't know how to do the training loop. I've tried a variety of things from taking indexes of the batches to running sess.run() there and tried a bunch of things I found online, but so far nothing has helped.
Sorry if this is something very simple, I'm fairly new to this and just starting to feel my way through.
My Code:
#imports tensorflow
import tensorflow as tf
sess = tf.InteractiveSession()

#weight generation with small amount of noise in normal dist & slight + bias bc ReLU nuerons
def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

#bias generation with small amount of noise in normal dist & slight + bias bc ReLU nuerons
def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

#creates conv layer with stride 1 and 0 padding
def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

#creates max_pool layer thats 2x2
def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

#reads image file names and respective labels
def read_labeled_image_list(image_list_file):
    f = open(image_list_file, 'r')
    filenames = []
    labels = []
    for line in f:
    filename, label = line[:-1].split(' ')
    filenames.append(filename)
    labels.append(int(label))
    return filenames, labels

#image name to image
def read_images_from_disk(input_queue):
    label = input_queue[1]
    file_contents = tf.read_file(str(input_queue[0]))
    example = tf.image.decode_png(file_contents, channels=1)
    return example, label

# Reads paths of images together with their labels
image_list, label_list = read_labeled_image_list("images.txt")

images = tf.convert_to_tensor(image_list)
labels = tf.convert_to_tensor(label_list)

# Makes an input queue
input_queue = tf.train.slice_input_producer([images, labels], shuffle=True)

image, label = read_images_from_disk(input_queue)
image.set_shape([28,28,1])

#Image and Label Batching
image_batch, label_batch = tf.train.batch([image, label],batch_size=50, allow_smaller_final_batch = True)

#placeholder define vars?
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 2])

#conv layer 1, 5x5 patch with 32 features
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

#4D tensor, 2 and 3 is w and h, 4th is color channels
x_image = tf.reshape(x, [-1,28,28,1])

#sets up forward for x_image
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

#second conv layer, 64 feature extraction
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

#converts from feature to 1024
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

#prevents overfitting, disabled during testing (todo: potentially     remove for us, is complex)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

#softmax layer with 10 outputs
W_fc2 = weight_variable([1024, 2])
b_fc2 = bias_variable([2])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

#training: ADAM optimizer with overfitting help and logging every 100th     iteration
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.initialize_all_variables())

for i in range(20000):
  #What do I do here!?!??!
  #imgs, lbls = sess.run([image_batch, label_batch])
  #imgs = image_batch[i]
  #lbls = label_batch[i]
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={ x:imgs, y_: lbls, keep_prob: 1.0})
    print("step %d, training accuracy %g"%(i, train_accuracy))
  train_step.run(feed_dict={x: imgs, y_: lbls, keep_prob: 0.5})

#prints final accuracy, to be updated
print("test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

Update:
Tensorflow, train_step feed incorrect
I found this and attempted to implement the second answer but I get this error:
W tensorflow/core/framework/op_kernel.cc:936] Unimplemented: File system scheme Tensor("input_producer/Gather not implemented

When I tried the first solution, I got this:
Traceback (most recent call last):
  File "Tester.py", line 77, in <module>
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
  File "Tester.py", line 22, in conv2d
     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  TypeError: DataType uint8 for attr 'T' not in list of allowed values: float16, float32, float64

Update 2
So I realized x and y have to be equal to image_batch and label_batch respectively and it worked once I casted it to float32 using tf.cast(image_batch, tf.float32). However, now the train line still fails with this printed twice in a row:
 W tensorflow/core/framework/op_kernel.cc:936] Unimplemented: File system scheme Tensor("input_producer/Gather not implemented

A: cast the inputs of conv2d to tf.float32_ref, tf.float32


text:
Q: Am I deleting this pointer correctly? I have the following code:
LPWSTR pszDSPath = NULL;
pszDSPath = new WCHAR[  wcslen(pwszFilter)+
                        wcslen(wstrServer.c_str())+
                        wcslen(var.bstrVal) +
                        1
                     ];

// ....
// ....

if(pszDSPath)
{
    delete pszDSPath;
    pszDSPath = NULL;
}

Can the above code generate a memory leak? I'm not sure if I'm deleting pszDSPath correctly or not.

A: You are not using the correct delete.  There are two forms of new:  the scalar new that creates a single object (e.g. new int), and the array new that creates an array (e.g. new int[42]).
Likewise, there are two forms of delete:  delete and delete[].  If you use new, you must use delete to destroy the object and if you use new[] you must use delete[] to destroy the object.
Since you have used new[] to create the object pointed to by pszDSPath, you must use delete[] pszDSPath to destroy the object.
Note, however, that this would be made much easier if you just used a std::vector:
std::size_t n = wcslen(pwszFilter)+
                wcslen(wstrServer.c_str())+
                wcslen(var.bstrVal) +
                1;

std::vector<WCHAR> v(n);

// &v[0] can be used as you are using pszDSPath in your current code.

In C++, you should eschew manual memory management:  it is extraordinarily difficult to get right and it takes a lot of work.  There are library facilities in the C++ Standard Library, including containers like std::vector and std::map and smart pointers like std::auto_ptr, std::unique_ptr, and std::shared_ptr, that manage object lifetimes for you.  You shouldn't do more work than you have to:  if you think you have to write delete somewhere in your code, your code is probably wrong.
This principle of using containers to manage resource lifetimes is based on a design pattern called Scope-Bound Resource Management (SBRM) or Resource Acquisition is Initialization (RAII).
(std::unique_ptr is a part of C++0x designed to replace std::auto_ptr, and your compiler may not yet support it.  std::shared_ptr is also a part of C++0x, but it has been available for about a decade as a part of the Boost libraries (as boost::shared_ptr) and was included in C++ TR1.)

A: Use delete[] pszDSPath to avoid memory leaks when you have allocated an array beforehand.

A: Use delete[] to avoid undefined behavior.
However using delete in you case will almost never cause a memory leak alone - either it will just work or you'll get something much much worse than a memory leak. Don't risk - use delete[].


text:
Q: Filter pandas Dataframe based on max values in a column I have a DataFrame with repeating values in the index. I would like to filter this dataset down to only show me one instance of each index by selecting the row within the index with the greatest value in a different column. For example, my DataFrame looks like this:
df:
Product ID     Store     Sales
    1            A         50
    1            B        200
    1            C         20
    2            A        400
    2            B         10
    3            A        200
    4            A         50
    4            B        100
    4            C        500

I would like to filter this data down to this:
df2:
Product ID     Store     Sales
    1            B        200
    2            A        400
    3            A        200
    4            C        500

Any thoughts on how best to approach this issue in pandas?
Thanks very much for your time -

A: You can perform a groupby on 'Product ID', then apply idxmax on 'Sales' column.
This will create a series with the index of the highest values.
We can then use the index values to index into the original dataframe using iloc
In [201]:

df.iloc[df.groupby('Product ID')['Sales'].agg(pd.Series.idxmax)]
Out[201]:
   Product_ID Store  Sales
1           1     B    200
3           2     A    400
5           3     A    200
8           4     C    500


text:
Q: How to convert tensorflow model (say *.pb format) to armnn (*.armnn format) I want to convert tensorflow model to armnn. I tried to build armnn from scratch for linux.
I tried this link -> https://github.com/ARM-software/armnn/blob/branches/armnn_19_11/BuildGuideCrossCompilation.md but I didn't able to build armnn Converter object file.
Could anybody help me out to build it successfully.
Thank you

A: You can use armnn Converter for the same task. Converter can convert only limited layers
For tenserflow support you can go to below link and explore layers.
https://github.com/ARM-software/armnn/blob/branches/armnn_20_08/src/armnnTfParser/TensorFlowSupport.md
Below Url you can get source for armnn converter. You can build it independently
https://github.com/ARM-software/armnn/tree/branches/armnn_20_08/src/armnnConverter
For Conversion you can use command like below example
ArmnnConverter -f tensorflow-binary -m {pb_filename} -i {input_layers} -o
{output_layer} -s {input-size} -p {model_name_after_conversion}


text:
Q: AndroidRuntime: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{.../....MainActivity}: java.lang.ClassNotFoundException: I've been using cordova through Windows CLI for years without an issue. Since updating to cordova 8.0.0 no Android build will run on a device or emulator.
As far as I can tell I've now uninstalled and reinstalled everything. And now only testing with the helloworld default project and still getting the same issue. On launch it just displays that HelloWorld has stopped.
Every apk results in :

AndroidRuntime: java.lang.RuntimeException: Unable to instantiate
  activity
  ComponentInfo{com.example.hello/com.example.hello.MainActivity}:
  java.lang.ClassNotFoundException: Didn't find class
  "com.example.hello.MainActivity" on path: DexPathList[[zip file
  "/data/app/com.example.hello-ZStkpWQT_YEARbjw--2a6Q==/base.apk"]

Tried every related suggestion on here and still no joy.
Currently:
Cordova 8.0.0
Java JDK: 1.8.0.91
Gradle: 4.4
npm: 6.1.0
Android: 7.0.0
Android target: 26
hello\platforms\android\app\src\main\AndroidManifest.xml created by cordova
<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="com.example.hello" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />
</manifest>

Any suggestions would be greatly appreciated.
Thanks in advance.

A: just hit the file button Invalidate cashe and Restart, most of the time this do work fine

A: [SOLVED] With all the updates it seems the environment variables had got out of sync and there must have been some left overs from uninstalls that meant it looked like it was building correctly. Updated these and everything is working fine now.
Path:

C:\...\Android\Sdk
C:\...\Android\Sdk\emulator
C:\...\Android\Sdk\gradle\bin
C:\...\Android\Sdk\platform-tools
C:\...\Android\Sdk\tools\bin
C:\...\Android\Sdk\build-tools

Also see https://www.fiznool.com/blog/2017/05/30/a-guide-to-installing-cordova-on-windows-10/ which prompted me to investigate every element of the installs.


text:
Q: JQuery returns false after return true? I'm little confused by behaviour of my functions in JQuery. The thing is that is_airport function decides, whether the location is an airport using JSON of airports.
Everything seems to work correctly, JSON is correctly parsed etc. As you can see there is a loop which is used for detecting, whether the destination_id is in airports JSON keys. It is. It alerts 'OK' but returns false instead of true.
If there was an AJAX instead of each function, I would expect this behaviour because of async. But why it happens here?
function is_airport(destination_id){
    var json_storage = $("#locations-json");
    var airports = JSON.parse(json_storage.attr("data-airports"));
    $.each(airports,function(id,name){
        console.log(id,destination_id,name);
        if (id==destination_id){
            alert('ok');
            return true
        }
    });
    return false
}

$(document).ready(function () {
    console.log(is_airport(5));)}

Do you know where is the problem?

A: You return true from $.each loop, it acts as continue statement. Instead, set a flag to return:
function is_airport(destination_id) {
  var json_storage = $("#locations-json");
  var airports = JSON.parse(json_storage.attr("data-airports"));
  var toReturn = true; // flag variable
  $.each(airports, function(id, name) {
    console.log(id, destination_id, name);
    if (id == destination_id) {
      alert('ok');
      return toReturn = false; // break each loop btw...
    }
  });
  return !toReturn; // return !flag
}


text:
Q: Java applet no longer functional in Internet Explorer under Java 8u60 I maintain a few applets used for a website and Java 8u60 makes them just not fire. I'm not sure exactly what's going on.
Here is how I declare the tag for IE:
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
   <param name="code" value="com.mysite.myapplet" />
   <!-- other params -->
</object>

One detail: the applet must not fire on page load, but on a button click, so the above tag is generated by Javascript, which injects the HTML into a div's innerHTML property. Is there a workaround?

A: This is the workaround I found: use an APPLET tag.
"But all the doc says to use OBJECT for IE support?"
I know. But even Java's own deployJava.js outputs an APPLET tag.
Apparently this is a bug specifically introduced in 8u60 which makes injected HTML OBJECT tags inoperative.
So instead, inject this:
<applet code="com.mysite.myapplet">
    <param name="classid" value="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" />
    <!-- other params -->
</applet>

That should work. Applets that fire automatically on opening the page can be left as objects.


text:
Q: Navbar transpraent on scroll I'm trying to get my navbar to go transparent on scroll, nothing seem to be working. Her'es the code I've been using. Any suggestions?

//transparent scroll

$(document).ready(function(){

    $(window).scroll(function(){

    if($(window).scrollTop()>100)
    $(".navbar").css({"background-color" : "rgba(0,0,0,.5)"});

    else
    $(".navbar").css({"background-color" : "transparent"});

    });

});

CSS
/* navbar */
.navbar-default {
    background-color: $back-two;
    border-bottom: 0.5px solid #979797;
}

/* link */
.navbar-default .navbar-nav > li > a {
    color: $textcol;
    font-family: 'Montserrat';
    font-size: 15px;
}

//hover
.navbar-default .navbar-nav > li > a {
    border-bottom: 2px solid transparent;
    -webkit-transition: all 0.8s;
    -moz-transition: all 0.8s;
    transition: all 0.8s;
}

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    border-bottom: 2px solid $accent;
}

//focus
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    background-color: $back-two;
    border-bottom: 2px solid $accent;
}

.navbar-toggle {
    background-color: transparent;
}

HTML

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

                </button>
                Ross Finn

                        About

                        Work

                        Contact

A: Try it like this
$(window).scroll(function() {
    if ($(".navbar").offset().top > 100) {
        $(".navbar").css({
            "background-color": "rgba(0,0,0,.5)"
        });
    } else {
        $(".navbar").css({
            "background-color": "transparent"
        });
    }
});


text:
Q: Remove customer account from Softlayer Brand Account i have create the customer account under softlayer master Account using python client

User creation

import SoftLayer
client = SoftLayer.Client(
              username= username,
              api_key = apiKey,
             )
try:
   result = client['Brand'].createCustomerAccount(cust_account)
except SoftLayer.SoftLayerAPIError as e:
   print("Error: %s, %s" % (e.faultCode, e.faultString))

How to remove customer from master account,i have refer the api SoftLayer_Brand couldn't seen any method to remove customer account from master brand
Thanks in Advance

A: you need to submit a ticket. Only the softLayere's employees have the permissions to delete customer's account.


text:
Q: not able to draw image on canvas of surface view in Android I am drawing an image using drawbitmap method on a canvas of surface view which is an overlay surface on my camera preview.The image drawn is a portion of captured image to guide the user to capture next image with a proper overlap.Now when I am launching the activity as the application start activity i.e it is my first activity,it works fine and draws the image.But when I launch the same activity from some other activity or when i moves back from some other activity,the surface view is not showing image on image capture i.e drawbitmap do not renders the image.
Is there any difference between launching an activity from another activity and from the application launch.
Someone help here as i am not able to proceed...please its important


text:
Q: Network failure" to download PDF from chrome and Edge browser but it is working in IE and firefox In my current application, when I click PDF View button, that time PDF is opened in new window and after that we can download the PDF file. During download time it is throwing error for chrome and Edge browser but it is working for IE and Firefox. I searched google I have found similar type of issue fixed using browser content setting. If I applied same, that time PDF View option direct download the pdf file but expected Behavior is first we can view the pdf after that we download the pdf file.
type_parameter = "application/pdf; charset=UTF-8"

header = [("Content-Disposition", "filename=%s" % file_name),('Content-type',
'application/pdf; charset="UTF-8"')]

Could someone tell how to fixed this issue?
Image1:

Network Failed error:

thanks in advance
Python Code:
content = create_pdf_file()
type= "application/pdf"
h= [("Content-Disposition", "filename=%s" % file_name),('Content-type', 'application/pdf; charset="UTF-8"')]
self._ctx.iLib.forward("display", content, type, h)

display.tmpl:
#def __call__(data, Ctype="application/pdf", h=None)
*##slurp
    #set self.Ctype= Ctype
    #if not h
        #set h= []
    #end if
    #for name, value in h:
        #if name.lower() == 'content-type':
            #set self.Ctype= value
            #silent $headers.remove((name, value))
        #end if
    #end for
    #set self.h= h
    #return data

A: Change PDF MIME Type in Web Server or Response Headers from application/pdf to application/octet-stream
This problem is when is enabled gzip compression and/or HTTP/2
Enable http/2 for SSL connections is a hugely valuable performance setting. However http2 expects the reported size to match what the webserver reports for streamed content.


text:
Q: Change url new tab page default for Internet Explorer I am working with Internet Explorer. I know how to change the home page or default search engine by changing the registry, but I don't understand how some programs (e.g. Baidu PC Faster, Search Protect) change the URL of a new tab page. Homepage remains unique, new tab page doesn't read homepage
Does someone know how to do this?

A: To change the internet explorer default page you have to change the key [Start Page] in the path HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main
Use this code to do that
        RegistryKey myKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main", true);
        myKey.SetValue("Start Page", "www.google.com", RegistryValueKind.String);

A: You should change the HKLM\Software\Microsoft\Internet Explorer\AboutURLs\Tabs registry key.
RegistryKey myKey = Registry.LocalMachine.OpenSubKey(@"HKLM\Software\Microsoft\Internet Explorer\AboutURLs", true);
myKey.SetValue("Tabs", "www.YourURL.com", RegistryValueKind.String);


text:
Q: symfony 1.4: creating "Copy" action I need to create "Copy" action for model listing. It should take all values from some model, fill those to forms, you could edit just few fields and after pressing "save" it would create NEW model. At the moment i thought about merging Edit and New actions as so:
public function executeListCopy(sfWebRequest $request)
  {
  # EDIT
  # $this->offer = $this->getRoute()->getObject();
  # $this->form = $this->configuration->getForm($this->offer);

  # NEW
  # $this->form = $this->configuration->getForm();
  # $this->offer = $this->form->getObject();

  # COPY
  <..>
   }

EDIT section shows what commands symphony runs when i use edit button.
NEW same as edit just creates new model.
i commed up with this:
$this->form = $this->configuration->getForm($this->getRoute()->getObject());
$this->job_offer = $this->form->getObject();

And i failed. This gives model ID to the form and since id is predefined - it edits, not creates model.
How should i do it?

A: Here's an example:
//routing
job:
  class: sfDoctrineRouteCollection
  options:
    model: Job
    module: job
    object_actions: {copy: get, updatecopy: post}

Create 2 actions (based on edit and update)
class jobActions extends sfActions
{
  public function executeCopy(sfWebRequest $request)
  {
    $this->form = new JobCopyForm($this->getRoute()->getObject());

    $this->setTemplate('copy');
  }
  public function executeUpdatecopy(sfWebRequest $request)
  {
    $this->form = new JobCopyForm($this->getRoute()->getObject());

    $this->processForm($request, $this->form);

    $this->setTemplate('copy');
  }
}

copySuccess template is the same as editSuccess, exept that you need to tell the form where to send data:
<form action='<?php echo url_for('job_updatecopy', $form->getObject()) ?>' method='post'>

Create and configure form, override doSave
class JobCopyForm extends BaseJobForm
{
  public function configure()
  {
  }

  public function doSave($conn = null)
  {
    //update object values from form values
    $this->updateObject();
    //clone object
    $job = $this->getObject()->copy();
    //save a clone
    $job->save();

  }
}

Cheers!


text:
Q: Raspberry PI cross compilation linking error - unknown symbol _dl_hwcap I have successfully set up a cross-complation environment for my RPI under 64 Bit ubuntu. I can compile and run a personal project using gstreamer just fine.
Due to performance-issues with gstreamer, I want to work on a fork of omxplayer. I adapted it to my environment, and compilation of ffmpeg and omxplayer themselves work just fine.
However, linking an actual executable (ffmpeg, or omxplayer.bin) yields a linking error I have been unable to resolve.
You find the full output of the last failing linking-step with verbose flags here:
https://gist.github.com/deets/3bba7c94017405d28f81
The error message is
ffmpeg_compiled/usr/local/lib/libavcodec.so: undefined reference to `_dl_hwcap'
collect2: error: ld returned 1 exit status

The missing symbol to me suggests something with dynamic loading. Maybe the libc or libdl are botched? But how come these are working just fine if compiling another project?

A: Found the culprit. When setting up the crosscompilation-environment, make sure your copy of the RPI's libraries are correct. I had unresolved symbolic library links that needed fixing in my rsync'ed copy of the RPI's file-system.


text:
Q: How to create inner view dynamic in Xib Cell of tableView swift I have created custom Cell Xib for tableView and its working fine dynamically. If I set numberofRowsInSection return 2 count it will display two cells within tableView.
Actually I want to achieve list should append within same cell kind of tree view. screen shot attached.
ViewController:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, URLSessionDelegate {

    @IBOutlet weak var tableView: UITableView!
    let urlList = [
    ["The Swift Programming Language", "https://swift.org/documentation/"],
    ["Crossdomain.xml", "https://crossdomain.xml"]]

    var downloadTaskList: [DownloadTaskInfo]?

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        let nib = UINib.init(nibName: "DownloadEntryViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "DownloadEntryViewCell")
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 140

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return urlList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DownloadEntryViewCell", for: indexPath) as! DownloadEntryViewCell
        cell.footerLbl1.text = urlList[indexPath.row][0]
        cell.footerPrg1.progress = 0.0
        return cell
    }

}

Xib Code:
class DownloadEntryViewCell: UITableViewCell {
    @IBOutlet weak var rightView: UIView!
    @IBOutlet weak var leftView: UIView!

    @IBOutlet weak var fileNameLabel: UILabel!
    @IBOutlet weak var downloadURLLabel: UILabel!
    @IBOutlet weak var progressLabel: UILabel!
    @IBOutlet weak var individualProgress: UIProgressView!
    @IBOutlet weak var imgView: UIImageView!

    @IBOutlet weak var footerView: UIView!
    @IBOutlet weak var h1View: UIView!
    @IBOutlet weak var v1View: UIView!
    @IBOutlet weak var footerLbl1: UILabel!
    @IBOutlet weak var footerProgressLabel: UILabel!
    @IBOutlet weak var footerPrg1: UIProgressView!
    @IBOutlet weak var PinView1: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()

    }

}

A: in your xib cell add vertical stackView.
now create custom UiView in another .xib file for your footer list.
in tableview cellForRowAt  method do like below
var stackHeight:CGFloat = 0.0
    for i in 1...ChildView.count
    {
        let child_view = Bundle.main.loadNibNamed("ChildView", owner: self, options: nil)?.first as! ChildView
        child_view.lblProgress.text = "Swift_programimg"
        cell.stackviewOption.addArrangedSubview(child_view)
         stackHeight = stackHeight + 60.0
    }
    cell.stackviewOption.heightAnchor.constraint(equalToConstant: stackHeight).isActive = true

here ChildView is footerview .xib and stackviewOption is vertical stackview.
for loop for how many you want fotter.
here line cell.stackviewOption.heightAnchor.constraint(equalToConstant: stackHeight).isActive = true for set stackview height.

line stackHeight = stackHeight + 33.0 for add everytime childview height in total height of stackview.
Do the same logic for cell that should work.

A: Set your tableview height  in  heightforrowAt to  UITableView.automaticDimension .
Make your top view inside UIView (lets call it view1) . Set its height to 0 with priority to 750 , now child inside view1 will give the height to view1. Make outlet of bottom constraint of last child inside view1 .
Disabling of bottom constraints will help you in hiding view1 since we are first setting height to 0 and expecting child items to provide height . When we are disabling bottom constraint , child items will not able to provide . Hence view1 will collapse to define height 0 .
Now for every cellforrowatIndexpath method call pass some parameters to hide or show top view .
func configureUI(cellData:String? , showTopView:Bool){
    mBtmCnst.isActive = showTopView
}

Make sure to mark top view  view1 to cliptobounds true and  mBtmCnst to strong outlet .
Hope this helps you!


text:
Q: Vue is not working in IE11 (SCRIPT1002: Syntax error) I am trying to set up Vue.
It works in the Chrome browser but it doesn't work in IE11 browser.
IE11 browser print

SCRIPT1002: Syntax error
  bundle.js (5253, 1)

// bundle.js (5253, 1)
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vue */ \"./node_modules/vue/dist/vue.esm.js\");\n/* harmony import */ var vue_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vue-router */ \"./node_modules/vue-router/dist/vue-router.esm.js\");\n/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! moment */ \"./node_modules/moment/moment.js\");\n/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _entry_vue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./entry.vue */ \"./resources/vue/entry.vue\");\n/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../store */ \"./resources/store/index.js\");\n/* harmony import */ var _axios__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../axios */ \"./resources/axios/index.js\");\n/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../common */ \"./resources/common/index.js\");\n\n\n\n\n\n\n // input key event code\n\nvue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].config.keyCodes = {\n  \"ctrl\": 17,\n  \"arrow-keys\": [37, 38, 39, 40]\n}; // Moment\n\nvue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].config.$moment = moment__WEBPACK_IMPORTED_MODULE_2___default.a; // Axios\n\nvue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].prototype.$axios = _axios__WEBPACK_IMPORTED_MODULE_5__[\"default\"]; // CommonUtils\n\nvue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].prototype.$common = _common__WEBPACK_IMPORTED_MODULE_6__[\"default\"]; // VueRouter\n\nvue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].use(vue_router__WEBPACK_IMPORTED_MODULE_1__[\"default\"]);\nnew vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"]({\n  render: h => h(_entry_vue__WEBPACK_IMPORTED_MODULE_3__[\"default\"]),\n  store: _store__WEBPACK_IMPORTED_MODULE_4__[\"default\"]\n}).$mount(\"#app\");\n\n//# sourceURL=webpack:///./resources/vue/entry.js?");

I arranged this message.
eval("
__webpack_require__.r(__webpack_exports__);

/* harmony import */
var vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vue */ \"./node_modules/vue/dist/vue.esm.js\");

/* harmony import */
var vue_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vue-router */ \"./node_modules/vue-router/dist/vue-router.esm.js\");

/* harmony import */
var _entry_vue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./entry.vue */ \"./resources/vue/entry.vue\");

/* harmony import */
var _store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../store */ \"./resources/store/index.js\");

/* harmony import */
var _axios__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../axios */ \"./resources/axios/index.js\");

/* harmony import */
var _common__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../common */ \"./resources/common/index.js\");

// input key event code
vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].config.keyCodes = {
  \"ctrl\": 17,
  \"arrow-keys\": [37, 38, 39, 40]
};

// Axios
vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].prototype.$axios = _axios__WEBPACK_IMPORTED_MODULE_4__[\"default\"];

// CommonUtils
vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].prototype.$common = _common__WEBPACK_IMPORTED_MODULE_5__[\"default\"];

// VueRouter
vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].use(vue_router__WEBPACK_IMPORTED_MODULE_1__[\"default\"]);

_store__WEBPACK_IMPORTED_MODULE_3__[\"default\"].$app = new vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"]({

  el: '#page',
  render: h => h(_entry_vue__WEBPACK_IMPORTED_MODULE_2__[\"default\"]),
    store: _store__WEBPACK_IMPORTED_MODULE_3__[\"default\"]\n});

//# sourceURL=webpack:///./resources/vue/entry.js?
");

And this is my Vue setting
// package.json
/...
"devDependencies": {
    "@babel/core": "^7.8.3",
    "@babel/preset-env": "^7.8.3",
    "babel-loader": "^8.0.2",
    "cross-env": "5.2.0",
    "css-loader": "^2.1.1",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.4.3",
    "file-loader": "1.1.11",
    "vue-loader": "14.2.4",
    "vue-template-compiler": "2.6.11",
    "vue-template-loader": "^1.0.0",
    "webpack": "4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.8.2"
  },
  "dependencies": {
    "axios": "^0.19.2",
    "core-js": "^3.6.4",
    "moment": "^2.24.0",
    "promise.prototype.finally": "^3.1.2",
    "vue": "^2.6.10",
    "vue-infinite-loading": "^2.4.4",
    "vue-router": "^3.1.3",
    "vuex": "^3.0.1"
  }

// webpack.common.js
let path = require('path');
let glob = require('glob');

module.exports = {
    entry: getEntries(),
    output: {
        path: path.resolve(__dirname, "../web"),
        filename: '[name]/bundle.js'
    },
    resolve: {
        alias: {
            "vue$": "vue/dist/vue.esm.js"
        },
        extensions: ["*", ".js", ".vue", ".json"]
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.vue$/,
                loader: "vue-loader"
            },
            {
                test: /\.css/,
                use: ['vue-style-loader', 'css-loader']
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    }
};

function getEntries() {
    let entryPathList = glob.sync('./resources/vue/**/entry.js');
    let entry = {};

    for (let index in entryPathList) {
        let configPath = entryPathList[index];
        let parentPath = configPath.substring(0, configPath.lastIndexOf("/"));

        entry[parentPath] = configPath;
    }

    return entry;
}

// webpack.dev.js
const common = require('./webpack.common.js');

module.exports = Object.assign(common, {
    devServer: {
        noInfo: true,
        port: 9876,
    },
});

// entry.js
import Vue from 'vue';
import VueRouter from "vue-router";
import moment from "moment";
import Page from "./entry.vue";
import store from "../store";
import axios from "../axios";
import common from "../common";

// input key event code
Vue.config.keyCodes = {
    "ctrl": 17,
    "arrow-keys": [37, 38, 39, 40]
};
// Axios
Vue.prototype.$axios = axios;
// CommonUtils
Vue.prototype.$common = common;

// VueRouter
Vue.use(VueRouter);

new Vue({
    render: h => h(Page),
    store
}).$mount("#app");

The problem is working in the Chrome browser, but it is not working in IE11 browser.
Please help me. (ㅠㅠ)


text:
Q: Visual Studio possible corrupted project - not recognizing most of the code I have a big problem with a VS solution.  I was working on it a few months ago without any issues, then I left it dormant while working on other projects. Recently I opened it up again and found that it will not build and has errors in just about every file. It isn't recognizing the LINQ to SQL data context or most of the elements on the pages (web forms, by the way). It seems to be ignoring referenced projects and .dlls. A lot of things that are part of ASP.NET are also not recognized.
It's just a huge mess. Deleting all the temp files and the .suo file has not helped.  I tried creating a new .sln which also did not help.  I am not sure what to do at this point.  Any ideas?

A: This is not a good solution to the problem, but I ended up manually changing files to make the application a 'website' instead of a web application. Fortunately it was a smaller scale site. I have no idea why that fixed it, but it did.


text:
Q: Can you use Keep-Alive with a CONNECT request with an HTTP proxy? I know that with HTTP/1.1 proxies, it's possible to use Keep-Alive to keep a persistent connection with the proxy and from the proxy to the remote server, but I'm curious if/how that would work with an HTTPS connection. I know that to do this, the browser sends a CONNECT request to the proxy to establish a connection then begins communicating using HTTPS. I'm curious if it's possible to use Keep-Alive with HTTPS through an http proxy.

A: Simply put, CONNECT is always keep-alive.
In HTTP, "persistent connection" means a connection that persists after one request-response pair. But CONNECT establishes a tunnel through the proxy. The proxy cannot even see the requests and responses that are sent over this tunnel (because they are encrypted). So there is no way for this tunnel to not be persistent.
Of course, if the server (the target of CONNECT) decides to close the connection, then the tunnel is destroyed, too. So the server must support persistent connections (just as with a regular, non-TLS proxy).