text:
Q: Angular: manage the style of items with the disabled attribute In an application (angular 10), I put some form fields with the attribute disabled.
Everything works well, however no style appears on the elements of type select, unlike the input type fields. See below:

I would like to recover the applied style (background) of the input on the select elements.
How can I do that properly?
Here's my HTML code:

  <input [attr.aria-label]="page + '.birthDate' | translate" [type]="isBrowserOldSafari() ? 'text' : 'date'"
         name="birthDate" id="birthDate"
         placeholder="{{ page + '.birthDate' | translate }} {{ isBrowserOldSafari() ? '(JJ/MM/AAAA)' : '' }}"
         [class.js-date-placeholder]="!isBrowserOldSafari()" required formControlName="birthDate">
  {{ page + '.birthDate' | translate }} {{ isBrowserOldSafari() ? '(JJ/MM/AAAA)' : '' }}
    *
  {{ (birthDateError === "") ? ('error.required' | translate) : (birthDateError) }}

      <select [attr.aria-label]="page + '.profession' | translate" required formControlName="profession">
        <option value="" selected>{{ page + '.profession' | translate }}*
        </option>
        <option *ngFor="let profession of professions"
                [value]="profession.identifiant">{{ profession.libelle }}</option>
      </select>
      {{ 'error.required' | translate }}

      <select [attr.aria-label]="page + '.specialty' | translate" required formControlName="specialty">
        <option value="" selected>{{ page + '.specialty' | translate }}*
        </option>
        <option *ngFor="let specialty of specialties"
                [value]="specialty.identifiant">{{ specialty.libelle }}</option>
      </select>
      {{ 'error.required' | translate }}

Here's the ts (the form):
  protected buildForm(): void {
    this.form = this.formBuilder.group({
      // birthdate
        birthDate: [{value: '', disabled: true}, [Validators.required]],
        // select
        profession: [{value: '', disabled: true}, [Validators.required]],
        specialty: [{value: '', disabled: true}, [Validators.required]],
  }

Thanks for help

A: try something like this instead of disabled, in the components css,
 .filter__form select.ng-invalid {
    /* first all selects will have gray color */
      color: rgb(170, 169, 169) !important;
    }
    .filter__form select option[value=""] {
      display: none;
    /*with this value which has "" will not be display in options*/
    }
    .filter__form select option {
      color: #000;
    /* with this all options will have black color when user selects one */
    }

you will get something like this:
before user selects one: https://i.stack.imgur.com/na0bD.png
[and this when user selects one] 2: https://i.stack.imgur.com/V3GfO.png
i hope i understand the question


text:
Q: Flexible running window to count entrys within timerange I have some devices in the field, sending data by GSM by losing connection from time to time. As I have limited disk space, I tend to loose some data in the periods without connection so I like to evaluate the amount of pending data to get some insight of the situation.
If I reduces the table from my server to the columns I need, it looks like this:
Declare @table  as table(
timestamp datetime,
lastchanged datetime )
INSERT INTO @table
VALUES
('2019-04-01 12:27:23', '2019-04-01 12:26:17'),
('2019-04-01 12:27:23', '2019-04-01 12:25:47'),
('2019-04-01 12:27:23', '2019-04-01 12:26:17'),
('2019-04-01 12:27:23', '2019-04-01 12:26:03'),
('2019-04-01 12:27:23', '2019-04-01 12:26:20'),
('2019-04-01 12:28:23', '2019-04-01 12:25:52'),
('2019-04-01 12:28:23', '2019-04-01 12:26:22'),
('2019-04-01 12:28:23', '2019-04-01 12:26:18'),
('2019-04-01 12:28:23', '2019-04-01 12:25:54'),
('2019-04-01 12:29:23', '2019-04-01 12:25:47'),
('2019-04-01 12:29:23', '2019-04-01 12:26:17'),
('2019-04-01 12:29:23', '2019-04-01 12:25:47'),
('2019-04-01 12:29:23', '2019-04-01 12:25:45'),
('2019-04-01 12:30:23', '2019-04-01 12:26:17'),
('2019-04-01 12:30:23', '2019-04-01 12:25:47'),
('2019-04-01 12:30:23', '2019-04-01 12:26:17'),
('2019-04-01 12:31:23', '2019-04-01 12:26:03'),
('2019-04-01 12:31:23', '2019-04-01 12:26:20'),
('2019-04-01 12:31:23', '2019-04-01 12:25:52'),
('2019-04-01 12:31:23', '2019-04-01 12:26:22'),
('2019-04-01 12:31:23', '2019-04-01 12:26:18'),
('2019-04-01 12:31:23', '2019-04-01 12:25:54'),
('2019-04-01 12:32:23', '2019-04-01 12:25:47'),
('2019-04-01 12:32:23', '2019-04-01 12:26:17'),
('2019-04-01 12:32:23', '2019-04-01 12:25:47'),
('2019-04-01 12:32:23', '2019-04-01 12:25:45');

as the value of timestamp (first column) is createt at the server and lastchanged (second column) is a timestamp from the device, the differenc obviously is the delay by the sending process.
From every sensor from my device I get a separate entry, so I just need to count rows to get an idea of how many datapoints were stored on the device in a specific range of time (this varies, depending on the behavior of the device).
Now I like to group by timestamp to evaluate for each of this timestamps, how many datasets have been already created, but did not reach the server so fare.
So, for every timestamp I would like to know the amount of rows in the dataset, which have a timestamp in the future but a lastchanged in the past.
As my dataset is very big, I would like to avoid any fetching.
And yes, this should not be a in-time analysis, I just need it to understand the behavior of the device and adjust some parameters.
I already tryed this:
SELECT
    A.timestamp,
    COUNT(case when (A.timestamp < B.timestamp AND A.timestamp > B.lastchanged  ) then 1 else null end) AS CountPending
FROM @table A, @table B
GROUP BY A.timestamp
ORDER BY A.timestamp

and think that CTEs and subquerys will not help as I need to do the filtering and counting in one step. And as I understand, classical running windows in SQL just need a fixed amount of entry for the window-range, but in my dataset, this number is not constant at all.
Applied on the example from above, the result is just wrong:
2019-04-01 12:27:23.000 105
2019-04-01 12:28:23.000 68
2019-04-01 12:29:23.000 52
2019-04-01 12:30:23.000 30
2019-04-01 12:31:23.000 24
2019-04-01 12:32:23.000 0

A: As a possible Answer to my own question I would like to show a fetch-Option, that works and produces the output I am looking for. But as I need to work on a Azure Datewarehouse, fetching is not possible in a native way. As I integrated my table as an external resource on a classic SQL-Server on Azure and use the fetching that way, it needs 9 minutes for 80k rows and 391 distinct timestamps within that rows. So this is just not a good option.
But, a the working solution looks like (I focused on one day range an one ID only to reduce amount of data.)
CREATE TABLE #st
(
    [timestamp]   DATETIME,
    CountPending  INT
);

DECLARE
    @timestamp      DATETIME,
    @CountPending   INT = 0,
    @ID             INT,
    @Start          DATETIME,
    @Stop           DATETIME;

SET @troID = 127
SET @Start = CAST('2019-04-01T00:00:00' AS DATETIME)
SET @Stop = CAST('2019-04-02T00:00:00' AS DATETIME)

DECLARE c CURSOR
    LOCAL STATIC FORWARD_ONLY READ_ONLY
    FOR
    SELECT DISTINCT timestamp
    FROM test.SensorData
    WHERE @ID = @ID AND timestamp BETWEEN @Start AND @Stop;

OPEN c;

FETCH NEXT FROM c INTO @timestamp;

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @CountPending = (
        SELECT COUNT(*)
        FROM test.SensorData
        WHERE troID = @troID AND
            timestamp BETWEEN @Start AND @Stop AND
            @timestamp < timestamp AND @timestamp > lastchanged)

    INSERT #st([timestamp], CountPending)
        SELECT @timestamp, @CountPending;

    FETCH NEXT FROM c INTO @timestamp;
END

CLOSE c;
DEALLOCATE c;

SELECT [timestamp], CountPending
    FROM #st
    ORDER BY [timestamp];

A: This should translate into a subquery, something like this:
SELECT a.troID, a.timestamp, MAX(x.c)
FROM test.SensorData a
    CROSS APPLY
        (
        SELECT COUNT(*) c
        FROM test.SensorData b
        WHERE a.troID = b.troID
          AND a.timestamp < b.timestamp
          AND a.timestamp > b.lastchanged
        ) x
GROUP BY a.troID, a.timestamp

I would guess hashing on troId might help but would need to know more about your data, distribution and volumes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: google cloud http(s) load balancing with kubernetes The documentation here describes how to setup a http(s) utilisation based load balancer with kubernetes on google cloud platform.
The question is how it actually manages to do utilisation based load balancing. For example, with the following configuration:

*

*10 node instance group

*3 pod replication controller deployed to that instance group

*a NodePort service that exposes port X on every node in the instance group.

Assuming the LB will choose the least utilised of the 10 nodes, and route to it on port X, how is a pod chosen to service the request? Does the kubernetes service then select the pod based on some other balancing algorithm?
Clearly something interesting is happening, because most instances will not have a pod running (and therefore might be more likely to be least utilised).

A: As describe in this article:

GCE/AWS load balancers do not provide weights for their target pools.
  This was not an issue with the old LB kube-proxy rules which would
  correctly balance across all endpoints.
With the new functionality, the external traffic will not be equally
  load balanced across pods, but rather equally balanced at the node
  level (because GCE/AWS and other external LB implementations do not
  have the ability for specifying the weight per node, they balance
  equally across all target nodes, disregarding the number of pods on
  each node).
We can, however, state that for NumServicePods « NumNodes or
  NumServicePods » NumNodes, a fairly close-to-equal distribution will
  be seen, even without weights.
Once the external load balancers provide weights, this functionality
  can be added to the LB programming path. Future Work: No support for
  weights is provided for the 1.4 release, but may be added at a future
  date
Internal pod to pod traffic should behave similar to ClusterIP
  services, with equal probability across all pods.


text:
Q: OpenCV2 codec support I am reading in video files with openCV, I use the following simple code to do this.
std::string arg = argv[1];
    VideoCapture capture(arg); //try to open string, this will attempt to open it as a video file
    if (!capture.isOpened()) {
        cerr << "Failed to open video file!\n" << endl;
        help(argv);
        system("Pause");
        return 1;
    }

I can load and manipulate several videos, but I have problems with others. I imagine this is down to codec issues. I can play the videos using old style win media player, so the codecs are on the system, but I imagine not available in opencv?
Does anyone know what codecs and video format will definitely play on opencv and what is a good option to convert video to these formats?
Many Thanks

A: Indeed, the supported codec of OpenCV is dependent on your platform and avaible codecs.
This tutorial Creating a video with OpenCV explains the video codec of OpenCV clearly. Though it is meant for writing videos, I think the underlying principle is the same with reading videos.
The function C++: double VideoCapture::get(int propId) can retrieve your loaded video's codec property by setting propId = CV_CAP_PROP_FOURCC. The interpretation of FOURCC can be found on this site. If you have problems with reading .avi videos, it is very likely that the codes is not installed in your platform.


text:
Q: Looping through multiple php arrays to change value I have an array $users as such:
  [0] => Array (
    [userid] => 1
    [score] => 9.9
  )
  [1] => Array (
    [userid] => 2
    [score] => 9
  )

For each user, I then retrieve items and store them into an array, $results:
foreach ($users as $user) {
  $items = getItems($user['userid']);
  $results[] = $items:
}

The $results array ends up looking like this:
[0] => Array (
  [0] => Array (
    [itemid] => 1
    [rating] => 9.9
  )
  [1] => Array (
    [itemid] => 2
    [rating] => 9
  )
)
[1] => Array (
  [0] => Array (
    [itemid] => 3
    [rating] => 8.5
  )
  [1] => Array (
    [itemid] => 2
    [rating] => 7.5
  )
)

What I would like to do, is weigh the item rating with the user score. So, for each item, the rating would be multiplied by user score * 0.1.
What I've tried is this:
foreach ($users as $user) {
  $items = getItems($user['id']);
  foreach ($items as $item) {
    $item['rating'] = $item['rating'] * $user['score'] * 0.1;
  }
  $results[] = $items:
}

but to no avail. What am I doing wrong and how do I get the desired result?

A: By default in foreach the value is passed by value. So even if you change the data inside of an array inside the loop it will not be reflected. So you have to use & before $item to pass the array data by reference.
You can learn more about it here http://php.net/manual/en/control-structures.foreach.php


text:
Q: jQuery Validate onclick: false not working for checkbox or select I am trying to disable validation until submit after an error occurs. The onfocusout handler works fine, but onclick does not work for a checkbox or a select element.
I wrote the following up as a quick example. If you submit a blank form and then correct the checkbox and select, they should not validate immediately. You'll see the text input is working correctly.
The select seems to work sometimes, irregardless of the onclick handler. It did validate onclick in safari, did not in chrome.
Fiddle: http://jsfiddle.net/ebMdq/6/
<form id="myForm" action="">
Name: <input type="text" name="fname" />

Do you Rawk? <input type="checkbox" name="rock" />

choose color: <select id="color" name="color" class="required">
<option value="">Choose One</option>
<option value="blue">blue</option>
<option value="blue">red</option>
</select>

<input type="submit" />
</form>

$(function () {
var validator = $("#myForm").validate({
             onfocusout: false,
             onkeyup: false,
             onlclick: false,
             rules: {
                 fname: "required",
                 rock: "required",
                 color: "required"
                },
             messages: {
                 fname: "Enter your firstname",
                 rock: "you know you do",
                 color: "pick one!",
             },
         });
});

A: Select, radio, and checkboxes have inconsistent event behavior across different browsers.
change or onchange event is used for radio/checkboxes.


text:
Q: Analytical proofs of saddle node, transcritical and pitchfork bifurcation in 3D I am seeking a general algorithm to prove the existence of saddle-node, transcritical and pitchfork bifurcation for a 3D model.
Please provide some notes on this topic. Thanks in advance!

A: There is no general "algorithm" for bifurcation classification. However, several local bifurcations --i.e. bifurcations which can be detected simply through the stability analysis of equilibrium points-- have a normal form, which makes it possible for them to be identified (see e.g. [1]). A typical example on which this method applies is the Lorenz system [2].


text:
Q: React - Spread MapStateToProps with the same props I have this MapStateToProps:
const mapStateToProps = (state) => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;

  const ESFReport = getESFReport(state);
  const resultStatusReport = getResultStatusReport(state);

  return {
    companInfo: getCompanyInfo(state),
    companyId: getCompanyId(state),
    ...ESFReport,
    ...resultStatusReport,
    year,
    month,
  };
};

And both ...ESFReport, and ...resultStatusReport, have the same property: report but I need somehow to change the name because in the same component I use const { report } = this.props two times but for different props.
How can I do this? (it used to work when I have only ...ESFReport, but when I added ...resultStatusReport, it broke).
Thanks in advance.

A: If you don't need anything other than report from the ESFReport and resultStatusReport objects you could do:
const mapStateToProps = (state) => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;

  const { report: ESFReport } = getESFReport(state);
  const { report: resultStatusReport } = getResultStatusReport(state);

  return {
    companInfo: getCompanyInfo(state),
    companyId: getCompanyId(state),
    ESFReport,
    resultStatusReport,
    year,
    month,
  };
};

It just renames the report property on each to ESFReport and resultStatusReport. You would then have this.props.ESFReport which would actually be  ESFReport.report and this.props.resultStatusReport which would be resultStatusReport.report.


text:
Q: Debugging private NuGet packages? I've published some private/internal libraries as NuGet packages, using the symbols option. The packages and symbols are hosted on an internal network share.  How can I step into these packages when debugging?
When I step to code from these packages, Visual Studio displays a "No Source Available" / "No Symbols Found" page.  Clicking the "Load Symbols" only allows pdb files, not symbol packages.
These packages are not suitable for publishing on NuGet Gallery/SymbolSource.

A: What is the command that you used to generate the packages with the symbols? I tried to do the same exact thing nuget.exe pack -Prop Configuration=Release Framework.csproj -Symbols This creates two files: Framework.nupkg and Framework.symbols.nupkg. I put these files on a network share, used them from another project and debugging worked fine.
Have you tried putting the *.nupkg and *.symbols.nupkg files on a local disk instead of a network share?

A: There are a couple options; one is to set-up & configure your own symbol server.
You could also download Inedo's ProGet, enable symbol serving on the target feed, and then publish your packages to ProGet. All of this can be done with the free edition of ProGet.

disclaimer -- my day job is at Inedo

A: There is also now a tool called GitLink (https://github.com/GitTools/GitLink) which can insert into the symbol file links to versioned GIT files of your source.

A: You can set up your own symbolsource server internally using those network shares.
You can find a step-by-step tutorial on my blog.
It basically comes down to create an empty MVC application and run

Install-Package SymbolSource.Server.Basic

From there on you need to set up the hosting infrastructure and configure Visual Studio and build agents.

A: The way we do it (and works):

*

*Generate "*.symbols.nupkg"

*Deploy symbol package to SymbolSource server (private)

*Configure IDE

*Add required Library to project using NuGet (from our SymbolSource server)

*Debug!

Links that can be useful:

*

*
*

*SymbolSource server installation

*Important: "Debugging Tools for Windows" won't install if it detects newer Visual C++ Redist version in the system than it needs/expects

*
*

*Vs configuration to debug using SymbolSource

*The URL to add is like http://your.symbolsource-server.com:[port]/[appContext]/WinDbg/pdb

A: I found that it doesn't work at all. NuGet package references are closed and cannot be used in the debugger. What I did instead was deleting the assembly reference from the project and instead added a reference to a Debug build of the DLL directly by path.
Then to make the debugger halt somewhere in that code, I inserted the call System.Diagnostics.Debugger.Break(); in that code. When running, the debugger will halt at that line, which is basically a code-defined breakpoint. This will open the correct source file and jump to that line automatically.
Open the library project in a second VS instance and move around the Break calls as necessary and rebuild the library. When done, remove those calls from the library code and restore the original reference (may need to reinstall the NuGet package).


text:
Q: how to crop multiple images and how to run loop in jquery filepreview is working dynamically but the issue is that when I run loop in jQuery it's not working. I want #filepreview1 is coming dynamically in a loop. Can anyone help me? Thanks in advance.

<img id="filePreview<?php echo $i; ?>" style="display:none;"/>

$(document).ready(function(){
    //prepare instant image preview
    for(i=0;i<=5;i++){
    var p = $("#filePreview"+i);
    $("#fileInput"+i).change(function(){
        //fadeOut or hide preview
        p.fadeOut();

        //prepare HTML5 FileReader
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("fileInput"+i).files[0]);

        oFReader.onload = function (oFREvent) {
            p.attr('src', oFREvent.target.result).fadeIn();
        };
    });

    //implement imgAreaSelect plugin
    $('img#filePreview'+i).imgAreaSelect({
        // set crop ratio (optional)
        //aspectRatio: '2:1',
        onSelectEnd: updateCoords
    });
}
});


text:
Q: Why does't my pandas indexer work when I tried to filter just two values? I tried to use a indexer to filter just two values (1 and 2) from a DataFrame, but if I check the .csv file I found some 77 values.

#My len is 15333, this is because of "77" values, the correct it will be 15286, i.e taking account just 1 and 2 values.
PD:All in 'HAD_CPOX' are int64 and I tried to use != 77.

A: If I look at your code and you only want to take values HAD_CPOX==1 or HAD_CPOX==2, then your still have to assign your filtered df back to variable df again like this:
df = df[(df['HAD_CPOX'] == 1) & (df['HAD_CPOX'] == 2)]

You could also write:
df = df[df['HAD_CPOX'].isin([1, 2])

In your code you only have:
df[(df['HAD_CPOX'] == 1) & (df['HAD_CPOX'] == 2)]

But then your df is not assigned, so nothing is changed or filtered then from your dataframe.


text:
Q: Difference between Java working set and Resource working set in Eclipse What is the difference between Java working set and Resource working set in Eclipse?
The Resource working set is more general and it can include not only the Java applications / projects, but let me put it this way:
Let's assume a daily life of a Java developer. Do you suggest him/her to use Resource working set over Java working set? Is there any specific situation in which you prefer one over the other?

A: One difference between the working sets is that they provide different editing wizards (as stated here: http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Fconcepts%2Fcworkset.htm). If you edit a resource working set and a java working set respectively you will see they use different screens for selecting which resources/projects are included.
Apart from this I haven't found any other difference. It also does not seem to differ which resources you can choose in any way. So to answer your question which one would be recommended  I would answer "it doesn't matter" since they behave the same way.

A: A working set is a subset of your workspace and is a way to organise all your projects. With the different types of working sets you have also different types of editing wizards as described here.
Editing wizards
For java projects the Java working set is a more comfortable way to work. Let's assume you have a bunch of java projects in a java working set and you have just opend the editing wizard of the Java Working set:
First of all you can see everything what is in the working set at the moment in the right table. If you now want to include another project you can simply select the project(s) and press CTRL+a. To remove a project you can press CTRL+r
In the Properties of a Resources Working set you don't know what is in the working set until you have scrolled to the bottom of the tree view. This is impossible for people who have 300+ projects in their workspace.
Structure
A benefit from having two types of working sets is structure. There are situations in a daily workflow where it is useful to have different types of working sets, because they have different icons. If you have resources like config files you can create a Resource working set namend 'config files' and put all the files in there.
Afterwards you can open your File Search and search in your config files. This is possible because you can define a working set as a scope for a search.

There are several parts in Eclipse where you can select your working set with the Select working set dialog.

A: It sounds like this should have answered the question:

*

*http://www.avajava.com/tutorials/lessons/what-is-a-working-set-and-how-do-i-use-it.html

A Working Set is a subset of your Eclipse projects. You can create
different Working Sets and then select which Working Set to display in
the Navigator view.

Specifically:

*

*"Working set" (in this particular context), is an "Eclipse thing"

*The purpose of Eclipse working sets is to help organize your projects

*A project consists of "stuff": source code, bitmap graphics files, WSDL's, CSS style sheets - just about anything imagineable.

*Consequently, Eclipse projects are organized (glancing at my J2EE perspective, for example) into subsections like "src", "WebContent", "Services" and so on.  A project itself can be one of many different types: a "Java project", a "Java Swing Design project", and "Dynamic Web Project" and so on.

*Similarly, an Eclipse Working set can be one of several different types: a "Java working set", a "Breakpoint working set ... and a "Resource working set".

*As with Eclipse "Views" and Perspectives", you can usually access any project resource you need any time you need it.  Selecting one or another perspective simply makes the object (e.g. "Problems pane" or "Build list") easier to get to.

*Which kind of "Working Set" you choose - or whether or not you use working sets at all - is largely just a matter of personal preference and convenience.
Please let us know if you still have any further questions.
PS:
Additional links:

https://www.ibm.com/developerworks/library/os-eclipse-visualstudio/
As mentioned, many developers load all their projects into a single
Eclipse workspace. It's convenient, but it can sometimes create too
much clutter. In addition to closing unnecessary projects, you can
define working sets: groups of elements (projects, folders, classes,
etc.). Eclipse can use working sets in different views (such as
Package Explorer) and operations (like searching).

...and:
help.eclipse.org: Working Sets

A: A working set in the context of eclipse is a logical grouping of related projects to ease search and organize views within the IDE.
A resource working set can capture all types of resources - maybe java source, html, xml, javascript, images - anything that exists within the scope of the projects included into the working set.
The Java working set is a different working set (it is NOT a subset of a resource working set!) which captures only those java files which belong to a source folder and are being compiled into the classpath, or those java files which belong to a module (library) in the build path. Hence, it lets you lookup java "classes" which are in the classpath. Note that all java file in your project may not necessarily be built into the classpath (for example when you exclude a java source file, it does not get built any more). But a java source file which is not included in your classpath can still be detected by a resource working set (you will notice that the icon for an included java source file is a solid J, while for an excluded java source, it is a hollow J).
Example:
Say you have two projects p1 and p2 of which p1 belongs to the working set but p2 does not. So:
MyClass.java (belongs to p1 and included in build path) - Shows up in java type search (Ctrl + T) and also in resource search (Ctrl + R).
MyOtherClass.java (belongs to p2 and included in build path) - Does not show up in java type search nor in resource search.
MyExcludedClass.java (belongs to p1 and excluded from build path) - Does not show up in java type search but shows up in resource search.
MyExcludedClass.class (belongs to a dependency jar in the build path of p1) - Shows up in java type search but does not show up in resource search.
MyWebPage.html (belongs to p1) - Does not show up in java working set but in resource working set.
MyOtherWebPage.html (belongs to p2) - Does not show up in java type search nor in resource search.
MyConfig.xml (belongs to p1) - Does not show up in java type search but shows up in resource search.
So, in the context of a Java developer's use: I use Java working sets to look up types / classes defined in Java, whereas the resources working set to lookup all different types.

A: I'll try answering from the perspective as a plugin developer. From the API:

A working set is intended to group elements for presentation to the user or for operations on a set of elements.

This can be any kind of element and does not have to be a project. Working sets are provided by plugins, which can decide what kind of elements can be added and which provide wizards for adding elements as well as operations that can be performed.
It doesn't really matter for a project in which working set(s) it is in. A Java project is still a Java project if it in a resource working set. It only affects some views, dialogs and operations that filter for certain types of working sets.
Besides Java and Resource working sets, there are also Breakpoint, Task, Plugin and C/C++ working sets (depending on your Eclipse setup of course). Some views only show certain types of working sets while other views don't seem to filter them. For example the "Open Type" and "Open Resource" dialogs seem to display all types of working sets. The "Open task" dialog only shows task working sets.
So what is the actual difference between Java and Resource working sets? I haven't seen any functional differences yet. All standard views and dialogs either seem to handle both or none of these two working set types. Most plugins don't seem to care about the distinction at all - but that doesn't mean some plugin could handle both types differently.
On the other hand resource working sets seem to be a catch-all for any type of project, so it makes sense that most plugins don't make a distinction here.
For example if I were to create a plugin that provides an option to analyze Java projects, I would add that operation to the context menu of Java working sets but certainly not to C/C++ working sets. But some people might use resource working sets because they have both Java and C projects in the same working set. So I have to add the Java-specific operation to the context menu of resource working sets too.


text:
Q: Please explain this convert extension method I'm trying to make sense of the code below, can someone please explain to me (in simple terms) how and what gets converted.        In particular this part is confusing me (this IEnumerable> values)
Code:
public static class ConvertExtensions
{
  public static IEnumerable<TTarget> ConvertAll<TSource, TTarget>(this IEnumerable<IConvertModel<TSource, TTarget>> values) => values.Select(value => value.Convert);
}

A: It's basically, for every value in a collection, call the T.Convert function, (where T is the target type) and return another collection of the converted values.
It doesn't DO any conversion, it hands the conversion off to a different function depending on the output type.
It's a shorthand way of doing something like this:
var convertedValues = new List<TTarget>();
foreach(var value in values)
{
   var convertedValue = value.Convert();
   convertedValues.Add(convertedValue);
}
return convertedValues;


text:
Q: Math Operation Showing as String Having trouble with math operator not working.
var posfx = (dwidth - outwd) / 2 + (outwd - twd) + pdir + 1.5 * 14
                 //  =        58                    -         21

The pdir is an operator ( either + or - ) It's negative in this instance.   & I tried using "+ pdir +"
It's giving me a string of: "58-21", instead of a number (37). How do I get it to calculate a number?

A: Multiply the second half of the equation by -1 if it needs to be subtracting.

A: If pdir is a string, adding it to the numbers will form  a string:
> 2 + '-' + 3
'2-3'

You could multiply by 1 or -1 instead, depending on the value of pdir:
... + (pdir == '+' ? 1 : -1) * 1.5 ...

A: var posfx = (dwidth - outwd) / 2 + (outwd - twd) + (pdir == '-' ? -1 : 1) * 1.5 * 14

A: The cheap way would be to put eval() around it, but you can do better than that.
Try replacing pdir + with (pdir == "-" ? -1 : 1) *
This will multiply the following term by -1 if the operation is a subtraction.


text:
Q: Can JMeter replay a test in a browser? Is it possible to get JMeter to replay its recordings via a browser, so one can see the replay in action. Katalon can do this, but not sure about JMeter.
Thanks in advance.

A: As per JMeter project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

So JMeter doesn't actually kick off a real browser, it only sends HTTP Requests like real browsers, but it doesn't render response, just measures time from sending request to receiving the last byte of the response. Therefore as of current version JMeter 5.0 it is not possible
The only way you can visualize the test results and see the request and response details is using View Results Tree listener. By default in Text mode you can see the source HTML code of the page JMeter hits

However in HTML, HTML (download resources) and Browser modes you should be able to see the rendered response:


text: Q: ''pixelatted'' ''griddy'' result from slope function (QGIS) I use the SRTM downloader to download my DEM's, then it happens very often that when I create a slopemap there are weird artefacts in the slope map. Something I do before making the slopemap is reprojecting (warp) the data to the specific location I need. I already have tried different methods for capturing the slope and they always result in a slopemap with the weird grid structure


text:
Q: Convergence in norm to steady-state solution of heat equation Studying the following problem
$ \left\{\begin{matrix}
u_{t}=au _{xx}-u_x & 0<x<1;\ \ 0<t\\
u(x,0)=f(x) & x\in[0,1] &    \\
u(0,t)= 0 & t\in[0,\infty) &   \\
u(1,t)=1 & t\in[0,\infty)  \\
\end{matrix}\right. $
I am advised to first study the steady-state solution, that is, the solution to the equation $av_{xx} -v_x=0$ (with same conditions).
Having solved it, $v(x,t)=\frac{1}{e^{1/a}-1}(e^{x/a} -1)$; I would like to show $u$ converge in $L^2$ to the steady state solution:
$\|u-v\|(t)\xrightarrow{t\rightarrow \infty} 0$, but i seem to miss something.
My work so far:
$$
\begin{align}
\begin{aligned}
\frac{\mathrm{d}}{\mathrm{d}t}\|u-v\|^2 =&\int_0 ^1 (u-v)(u_t -v_t) =\int_0^1(u-v)(au_{xx}-u_x) \\
=&a\int_0^1u u_{xx} -\int_0^1 uu_x -a\int_0^1 vu_{xx} +\int_0^1vu_x \\
=&\left(\underbrace{auu_x\vert_0^1}_{=0} - a\|u_x\|^2\right)-\left(\underbrace{\frac{u^2}{2}\vert^1_0}_{=1/2}\right) +\left(- \underbrace{avu_x\vert_0^1}_{=0}+a\int_0^1v_xu_x \right)+\int_0^1 vu_x \\
=&-a\|u_x\|^2 - 1/2+\left(\underbrace{avu_x\vert_0^1}_{=0} - a\int_0^1v_{xx}u \right)+\int_0^1vu_x \\
=&-a\|u_x\|^2-1/2 +\int_0^1 v_xu +\int_0^1 vu_x \\
=& -a\|u_x\|^2-1/2 +\int_0^1 \frac{\mathrm{d}}{\mathrm{d}x}(uv) \\
=& -a\|u_x\|^2 -1/2 +1 \\
=& - a\|u_x\|^2 + 1/2
\end{aligned}
\end{align}$$
But I cannot figure out how to proceed from here, the bounds are not good enough, I would like to connect the last result with $v$ or $v_x$ and then show the decay of the solution to the steady-state solution.
You're welcome to help!


text:
Q: Material Design Component & reactjs input fields So i have MDC finially working with React and using the Google docs I have worked out that I some how need reactjs to run the following JS when a user clicks on an input field - basiclly the label should move above the input so the user can type - like my pure HTML / JS demo https://codepen.io/russellharrower/pen/oeReEN
However with reactjs I noticed I can't put the code below in the render area, so i am wondering where would I place it and how?
(function() {
        var tfs = document.querySelectorAll(
          '.mdc-textfield:not([data-demo-no-auto-js])'
        );
        for (var i = 0, tf; tf = tfs[i]; i++) {
          mdc.textfield.MDCTextfield.attachTo(tf);
        }
      })();

full reactjs code updated
import React, { Component } from 'react';
import './App.css';
import * as mdc from 'material-components-web';

class App extends Component {
    hrefjs(l){
            var script   = document.createElement("script");
            script.type  = "text/javascript";
            script.src   = l;    // use this for linked script
            document.body.appendChild(script);
    }

    componentWillMount() {
            this.hrefjs("//unpkg.com/material-components-web@latest/dist/material-components-web.min.js");
            var texst ="(function(){var tfs = document.querySelectorAll('.mdc-textfield:not([data-demo-no-auto-js])'); for (var i = 0, tf; tf = tfs[i]; i++) {mdc.textfield.MDCTextfield.attachTo(tf); mdc.autoInit();}})();"
            const script = document.createElement("script");
            script.text=texst;
            document.body.appendChild(script);
    };
  render() {
    return (

              Title

                <input type="checkbox"
                       id="my-checkbox"
                       className="mdc-checkbox__native-control"/>

                  <svg className="mdc-checkbox__checkmark"
                       viewBox="0 0 24 24">
                    <path className="mdc-checkbox__checkmark__path"
                          fill="none"
                          stroke="white"
                          d="M1.73,12.91 8.1,19.28 22.79,4.59"/>
                  </svg>

              This is my checkbox

                      <input type="text" id="username" className="mdc-textfield__input" aria-controls="username-helptext"/>
                      Username

                      This will be displayed on your public profile

    );
  }
}

export default App;

Latest update
I have added these two functions in however for some reason the (function(){})(); script while it will do an alert etc. it will not allow the text label to move like the codepen.io demo
hrefjs(l){
        var script   = document.createElement("script");
        script.type  = "text/javascript";
        script.src   = l;    // use this for linked script
        document.body.appendChild(script);
}

componentWillMount() {
        this.hrefjs("//unpkg.com/material-components-web@latest/dist/material-components-web.min.js");
        var texst ="(function(){var tfs = document.querySelectorAll('.mdc-textfield:not([data-demo-no-auto-js])'); for (var i = 0, tf; tf = tfs[i]; i++) {mdc.textfield.MDCTextfield.attachTo(tf); mdc.autoInit();}})();"
        const script = document.createElement("script");
        script.text=texst;
        document.body.appendChild(script);
};

A: Even if your approach works in the end somehow. It does really not look like a very pleasant way to continue developing and your code will be a nightmare for others to read later on (or yourself).
It can actually be done much easier. I am usually writing react.js wrappers for the components I need from MDC. Here is an example for the textfield:
import React from 'react';
import { MDCRipple } from '@material/ripple/dist/mdc.ripple';

class MdcButton extends React.Component {
    constructor(props) {
        super(props);
        // Init state
        this.state = {}
    }

    componentDidMount() {
        if (this.props.ripple)
            MDCRipple.attachTo(this.refs.button);
    }

    static defaultProps = {
        ripple: true,
        raised: true,
        disabled: false,
        className: "",
        type: "submit"
    }

    render() {
        let className = "mdc-button " + this.props.className;
        if (this.props.raised)
            className += " mdc-button--raised";

        return (
            <button
                ref="button"
                id={this.props.id}
                className={className}
                type={this.props.type}
                onClick={this.props.onClick}
                disabled={this.props.disabled}
            >
                {this.props.children}
            </button>
        );
    }
}

export default MdcButton

You can check out the official mdc demo for react.js here (https://github.com/material-components/material-components-web/tree/master/framework-examples/react).
For styling, I am including the mdc sccs files into my scss files and change the values I need. e.g.:
$mdc-theme-primary: #404040;
$mdc-theme-accent: #a349a3;
$mdc-theme-background: #fff;

@import "@material/ripple/mdc-ripple";
@import "@material/typography/mdc-typography";
@import "@material/theme/mdc-theme";
@import "@material/button/mdc-button";


text:
Q: Displaying phone numbers in Android What's the easiest way to display an active (initiating a call on click) phone number in an Android app?
It would have been great if there was a View subclass, called something like PhoneNumberView, that has all the functionality and UI integrated.

A: You can just use
<TextVIew
   ...
   android:autoLink="all"
/>

It will highlight phone and make it clickable.
http://developer.android.com/reference/android/widget/TextView.html#attr_android:autoLink

A: Displaying the number can be as easy as putting it in a text view. to add touch behavior, you can define an "on touch listener"
view.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        //define behavior here
    }
});

As far as the code for dialing the phone, look into the google api's for the right method. You need to create the proper intent and then call startActivity(...). you can find information about using intents to start apps here (this should start the phone's normal dial interface and call the number so you wont have to create your own)

A: True, as Lin points out, the question is about a number already dialed. But the right way to handle the situation might very well be to take over the phoning and dialing with Intent.ACTION_DIAL and Intent.CALL_ACTION. The OP should read the documentation on how to service these Intents and decide if that is an adequate solution. Otherwise he will have to read the Android source code for the built-in dialer and see if it publishes the phone number dialed: I don't think it does.


text:
Q: How to create an outline polygon (footprint) from raster data with PostGIS How can I create a polygon, containing the actual outlines (aka footprint) of a raster file with PostGIS?
I just need the outlines of the data containing parts of the raster.
ST_PixelAsPolygon creates a complex polygons - but I just need the footprint.
There is a similar question here Creating shapefile showing footprints of Rasters?, but the answers do not cover PostGIS.

A: Use the ST_Envelope function:
SELECT ST_Envelope(rast)
  FROM raster_table;

This will return a rectangular bounding box for your raster(s). PostGIS describes what this function returns as:

Returns the polygon representation of the extent of the raster.

A: Please take a look at ST_DumpAsPolygons. It will draw the polygons around your raster shapes.


text:
Q: SQL to insert millions of dummy records into MySQL database I have a MySQL database that I'd like to test the performance of. I want to insert approximately 5 million records into a table with an auto-incremented primary key. Is there an easy way to do this quickly with SQL? I know I can pipe in a .sql file, but all I really want to do is insert the same identical data (but with a different PK), 5 million times.

A: You can insert NULL as the value of the PK or just simply don't specify it in the columns list in your insert statement. That way it gets auto incremented.
for ($i=0; $i<5000000; $i++) {
    "INSERT INTO table (id,name) values (NULL,'somename')"; // obviously in form of $dbh->() something
}

A: This may not be a good performance test, as identical rows will not create indicies with regularly distributed values for anything but the PK, so most queries will not demonstrate expected performance.
I would consider using a test data generation tool like Faker (ruby and perl varieties exist):
http://faker.rubyforge.org/


text:
Q: How do I extract numbers from a string in JavaScript without using regular expressions? For example, I have a string "asdf123d6lkj006m90" and I need the following result [123, 6, 0, 0, 6, 90].
I tried:
let str = "asdf123d6lkj006m90"
let func = function(inputString){
    let outputArray = []
    let currentNumber = ""
    for(let element of inputString){
        if(Number(element)||element == 0){
            outputArray.push(Number(element))
        }
    }
    return(outputArray)
}
console.log(func(str))

But it returns [ 1, 2, 3, 6, 0, 0, 6, 9, 0 ]
How do I receive the correct numbers?

A: You're looking at each character at a time, when you should be checking the next few as well.

const str = "asdf123d6lkj006m90";
console.log(numbers(str));

function numbers(str) {
  const nums = []; // create an array with the numbers
  for(let i = 0; i < str.length; i++) {
    // in your example you want preceding 0s to be their own number
    if(str[i] == 0) {
      nums.push(0);
      continue;
    }

    let current = ""; // add to our string
    while(!isNaN(str[i])) {
      // as long as the character can be converted to a number
      current += str[i++];
    }
    // if there were any numbers added
    if(current.length)
      nums.push(+current);
  }
  return nums;
}

And note, while this looks like O(n^2) because of the nested loop, it's actually still linear because the loops are traversing the same array and one picks up where the other left off.


text:
Q: String handling in C language for Espressif ESP-IDF The following function call is derived from espressif ESP-IDF and will send an mqtt message  (event->data) with length event->data_len).
esp_mqtt_client_publish(mqtt_client, CONFIG_EXAMPLE_PUBLISH_TOPIC, event->data , event->data_len, 1, 0);
Instead, if event->data I want to extend this character array by some additional characters like "I got [event->data] !" and send this message by the function shown above.
I know, there are many ways how to achieve this, but every solution I found, results in a couple of lines that are ridiculous complicated in my eyes.
    //Buffer to hold event->data as a string with \0 termination
    char *bufData = calloc(event->data_len + 1, sizeof(char));
    snprintf(bufData, event->data_len + 1, "%s", event->data); // get a zero ended string from event->data

    //Additional Buffer to hold complete String
    int mqttStringBufSize = strlen(bufData) + 30;
    char *mqttStringBuf = calloc(mqttStringBufSize, sizeof(char));
    snprintf(mqttStringBuf, mqttStringBufSize, "I received [%s]", bufData);

    esp_mqtt_client_publish(mqtt_client, CONFIG_EXAMPLE_PUBLISH_TOPIC,
            mqttStringBuf, strlen(mqttStringBuf), 1, 0);

    free(bufData);
    free(mqttStringBuf);

So I am looking for a clean solution to this problem.


text:
Q: Convolution 3D image with 2D filter I have a single image of shape img.shape = (500, 439, 3)
The convolution function is
def convolution(image, kernel, stride=1, pad=0):

    n_h, n_w, _ = image.shape

    f = kernel.shape[0]
    kernel = np.repeat(kernel[None,:], 3, axis=0)

    n_H = int(((n_h + (2*pad) - f) / stride) + 1)
    n_W = int(((n_w + (2*pad) - f) / stride) + 1)
    n_C = 1

    out = np.zeros((n_H, n_W, n_C))

    for h in range(n_H):
        vert_start = h*stride
        vert_end = h*stride + f

        for w in range(n_W):
            horiz_start = w*stride
            horiz_end = w*stride + f

            for c in range(n_C):
                a_slice_prev = image[vert_start:vert_end,
                                     horiz_start:horiz_end, :]

                s = np.multiply(a_slice_prev, kernel)
                out[h, w, c] = np.sum(s, dtype=float)

    return out

I want to see the image after any kernel/filter applied to the image, so I got the following
img = plt.imread('cat.png')
kernel = np.arange(25).reshape((5, 5))
out2 = convolution(img, kernel)
plt.imshow(out2)
plt.show()

I get

s = np.multiply(a_slice_prev, kernel)
ValueError: operands could not be broadcast together with shapes
(5,5,3) (3,5,5)

A: np.multiply is doing an elementwise multiplication. However, your arguments do not have matching dimensions. You could transpose your kernel or image with this to ensure it can work:
kernel = kernel.transpose()

You could do this prior to your np.multiply call.

A:
ValueError: operands could not be broadcast together with shapes (5,5,3) (3,5,5)

Since, Convolution is element-wise multiplication, your shapes should be (5,5,3) for the image region and (5,5,3) for the kernel, thus repeat your kernel like this:
kernel = np.arange(25).reshape((5, 5, 1))
kernel = np.repeat(kernel, 3, axis=2)


text:
Q: How to merge audio and video file of any format I am developing an application for android in which I have a video and then I get a list of music from user phones I am able to get both of these, my problem is that now I want to combine the audio selected by user with video like a background music in the video, the video has no sound in it. Please Help me achieve this. I am sorry for the code posting the code not neatly because it's my first time writing a problem.
I have tried media muxer but it seems it doesn't support mp3 format, and since I am getting audio from users phone, it can be in any format.
This is my music object class:
class MusicMP3 : Serializable {
var isCheck: Boolean = false
var namemusic: String? = null
var namesong: String? = null
var path: String? = null

constructor(check: Boolean, namemusic: String, namesong: String, path:
String) {
    this.isCheck = check
    this.namemusic = namemusic
    this.namesong = namesong
    this.path = path
}

}

I am getting audio using this code:
    musicArray = ArrayList<MusicMP3>()
    val contentResolver = contentResolver
    val songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    val songCursor = contentResolver.query(songUri!!, null, null, null,
    null)
    if (songUri != null && songCursor!!.moveToFirst()) {
        val songTitle =
     songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE)
        val songArtist =
     songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)
        val songPath =
     songCursor.getColumnIndex(MediaStore.Audio.Media.DATA)
        do {
            val currentTitle = songCursor.getString(songTitle)
            val currentArtist = songCursor.getString(songArtist)
            val currentPath = songCursor.getString(songPath)
            lsmusic!!.add(MusicMP3(false, currentTitle, currentArtist,
     currentPath))
        } while (songCursor.moveToNext())
    }

Tried to merge using this code:
fun addAudioVideo(pathvideo: String, String: audioPath, output: String) {
    try {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
          val videoExtractor = MediaExtractor()
          videoExtractor.setDataSource(pathvideo)
          val audioExtractor = MediaExtractor()
          audioExtractor.setDataSource(audioPath)
          Log.d("test", "Video Extractor Track Count " +
          videoExtractor.trackCount)
          Log.d("test", "Audio Extractor Track Count " +
          audioExtractor.trackCount)

          val muxer = MediaMuxer(output, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)

          videoExtractor.selectTrack(0)
          val videoFormat = videoExtractor.getTrackFormat(0)
          val videoTrack = muxer.addTrack(videoFormat)

          audioExtractor.selectTrack(0)
          val audioFormat = audioExtractor.getTrackFormat(0)
          val audioTrack = muxer.addTrack(audioFormat)

          Log.d("test", "Video Format $videoFormat")
          Log.d("test", "Audio Format $audioFormat")

          var sawEOS = false
          var frameCount = 0
          val offset = 100
          val sampleSize = 256 * 1024
          val videoBuf = ByteBuffer.allocate(sampleSize)
          val audioBuf = ByteBuffer.allocate(sampleSize)
          val videoBufferInfo = MediaCodec.BufferInfo()
          val audioBufferInfo = MediaCodec.BufferInfo()

          videoExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC)
          audioExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC)
          muxer.start()
          while (!sawEOS) {
                 videoBufferInfo.offset = offset
                 videoBufferInfo.size =
                 videoExtractor.readSampleData(videoBuf, offset)

                 if (videoBufferInfo.size < 0 || audioBufferInfo.size <  0) {
                     Log.d("test", "saw input EOS.")
                     sawEOS = true
                     videoBufferInfo.size = 0

                  } else {
                     videoBufferInfo.presentationTimeUs = videoExtractor.sampleTime
                     videoBufferInfo.flags = videoExtractor.sampleFlags
                     //videoBufferInfo.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;
                     muxer.writeSampleData(videoTrack, videoBuf,
             videoBufferInfo)
                     videoExtractor.advance()
                     frameCount++
                     Log.d("test", "Frame (" + frameCount + ") Video
            PresentationTimeUs:" + videoBufferInfo.presentationTimeUs + "
            Flags:" + videoBufferInfo.flags + " Size(KB) " +
            videoBufferInfo.size / 1024)
                     Log.d("test", "Frame (" + frameCount + ") Audio
             PresentationTimeUs:" + audioBufferInfo.presentationTimeUs + " Flags:" + audioBufferInfo.flags + " Size(KB) " + audioBufferInfo.size / 1024)

                    }
                }
                var frameCount2 = 0
                val frame = frameCount * 2
                while (frameCount2 < frame) {
                    frameCount2++
                    audioBufferInfo.offset = offset
                    audioBufferInfo.size =
               audioExtractor.readSampleData(audioBuf, offset)
                    audioBufferInfo.presentationTimeUs = 30
                    audioBufferInfo.flags = audioExtractor.sampleFlags
                    muxer.writeSampleData(audioTrack, audioBuf,
                audioBufferInfo)
                    audioExtractor.advance()

                    Log.d("test", "Frame (" + frameCount + ") Video
                    PresentationTimeUs:" + videoBufferInfo.presentationTimeUs +
                    " Flags:" + videoBufferInfo.flags + " Size(KB) " +
                    videoBufferInfo.size / 1024)
                    Log.d("test", "Frame (" + frameCount + ") Audio
                    PresentationTimeUs:" + audioBufferInfo.presentationTimeUs +
                    " Flags:" + audioBufferInfo.flags + " Size(KB) " +
                    audioBufferInfo.size / 1024)

                }
                muxer.stop()
                muxer.release
     }
  } catch (e: IOException) {
            Log.d("test", "Mixer Error 1 " + e.message)
  } catch (e: Exception) {
            Log.d("test", "Mixer Error 2 " + e.message)
  }
 }

I want to able to successfully merge the video and audio. where the video will play and audio will act as background music.


text:
Q: Lion + Homebrew: how to fix "config" scripts? When I run brew doctor, I get the output:
Warning: "config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.

Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:

    /opt/ImageMagick/bin/Magick++-config
    /opt/ImageMagick/bin/Magick-config
    /opt/ImageMagick/bin/MagickCore-config
    /opt/ImageMagick/bin/MagickWand-config
    /opt/ImageMagick/bin/Wand-config
Warning: Your XQuartz () is outdated
Please install XQuartz 2.7.4.

How can I fix it or, am I missing something important?
EDIT: I believe this is the reason why I cannot install the rmagick library. While its installation I am getting this error message: an't install RMagick 2.13.1. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information.

A: The only way to fix the issue is to remove the "config" scrips out of your $PATH variable. Deleting that install of ImageMagick will do that. You could always reinstall it with brew.
Keep in mind that this might cause issues if you have other software dependent on that specific location of ImageMagick.


text:
Q: Add loading page between HTML pages I have a mp4 animation, that i wanted to be played as a loading animation between two html pages. The video is about 5 seconds long, so i wanted this loading page to be the same lenght. Is there a way to do that?
If so, is it possible to choose for how long that loading page will be displayed, like 10 seconds, for example, so the loading animation would be repeating until the loading page is over?

A: So for this I would add this to each page
<iframe id="loadingBar" src="loading.mp4"/>

<script>
   $(document).ready = () => {
       Window.setTimeout(5000); //wait for 5 seconds
       $("#loadingBar").attr("display","none");
       $(".page").click = () => {
          location.href = index.html?page=2;
       };
   };
</script>


text:
Q: How to add metadata through grpc ruby client? How to add metadata through grpc ruby client? example code snippet will help.

A: Metadata is an optional parameter to any method call. For example:
metadata = { 'key' : 'value' }
response = service.method(argument, metadata: metadata)

A: do it this way
response = stub.rpc_call(req, {metadata: {key1: value1, key2: value2}})

you can find the right usage by reading grpc rspec code

A: You need to pass metadata as a hash with key metadata.
On the server side, assuming you have your_method(your_req, _call), the metadata will be available as _call.metadata.


text:
Q: How to parse the RDF ontology (turtle file) in c# model classes I have the ontology file. I want to write the OData services on top of my graph database. For this I need to provide the EdmModel in order to register my OData route. but it can not be done because schema is in ttl file and also in the server. According to this blog, we can create the model by fetching the schema from the server. But there github code is having lot of issues. Is there anyone know how to convert it to the c# model classes?
My sample schema in turtle format :
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

@prefix : <http://www.example.com/schema/abc#> .

: a owl:Ontology .

# Class
:Organization a owl:Class ;
  rdfs:label "Organization"@en ;
  skos:definition ""@en .

# Properties
:Name a owl:DatatypeProperty ;
  rdfs:domain :Organization ;
  rdfs:range xsd:string .
:CreatedDate a owl:DatatypeProperty ;
  rdfs:domain :Organization ;
  rdfs:range xsd:dateTime .

# Relation
:hasRole a owl:ObjectProperty ;
  rdfs:domain :Organization ;
  rdfs:range :Role .

A: There are some translators from SPARQL to OData. I haven't tried them, but here are some links. If you search for "odata rdf" or "odata sparql", you'll find more links on Stack Exchange.

*

*https://github.com/BrightstarDB/odata-sparql/tree/master/ODataSparql.Server is an example exposing a bit of DBpedia 3.9 as OData

*

*Driven by the data model https://github.com/BrightstarDB/odata-sparql/tree/master/ODataSparql.Server

*which also shows you the strength of OData/EDMX (allows a lot more specific description of entities and navigation between them) and the weakness (a lot more verbose than even OWL)

*https://www.w3.org/2013/04/odw/odw13_submission_4.pdf is a paper that describes the approach: "an OData service is driven by the underlying domain model". "we have not implemented (generation of domain model from RDFS/OWL) but we are fairly confident that some level of useable OData service metadata could be automatically generated"

*was presented at Open Data on the Web, April 2013: https://www.w3.org/2013/04/odw/papers

*http://inova8.com/joomla/index.php/blog/odata-and-sparqlrdf-contradictory-or-complementary

*Olingo2SPARQL: An OData V2 SPARQL provider for the Apache Olingo framework.

*

*https://github.com/peterjohnlawrence/inova8.olingo2sparql.

*Odata4SPARQL: An OData V3 SPARQL server built upon the Odata4j framework.
https://github.com/peterjohnlawrence/inova8.odata4sparql

*Very good explanation of the strengths and weaknesses of each.

*Seems to build upon the above "SPARQL/OData Interop proposed W3C interoperation proxy between OData and SPARQL (Kal Ahmed, 2013)". However, Kal Ahmed's position paper at ODW13 is in now way related to W3C

*describes "Contradictions between OData and RDF/SPARQL" (i.e. impedance mismatches)

*http://data.oceandrilling.org/labs/odata.html

*

*describes conversion of SPARQL results (CSV) to OData. This seems an overkill since the data is rectangular, could just use ODBC/JDBC

*http://data.oceandrilling.org/source/usioOdata.java.html and two more source files

*describes real case of using Tableau for complex data


text:
Q: Create bug on failed release I have a customized Xaml TFS build that is building an SQL Server project and it's deploying the .dacpac file to a target database. In case of failure the build is creating a bug in TFS.
I'd like to move the "deploy" part from TFS build to the Release Management area.
It's possible to accomplish the same result with TFS Release Management?
In case of release failure to automatically create a bug in TFS.
Update 1:
I was referring to vNext templates.

A: Out of the box? No.
You could easily write a PowerShell script or .NET application that uses the TFS API to create a bug, then call it in a "rollback always" block within an RM release template, though.


text:
Q: ChartJS - How do I remove the X-Axis color overlay on the chart? I styled the ChartJS X grid lines a specific color, but the X Axis gridline has a default color that overlays the color I styled the grid lines with, does anyone what the reason could be that this is occurring?
Heres the chart
https://i.stack.imgur.com/zBl9p.png
Heres the code
https://i.stack.imgur.com/igan6.png
Thanks so much!


text:
Q: How can i open in port 3306 in Ubuntu 8.04.1? I want to open port using command sudo ufw allow 3306/tcp but it gives the following error:
sudo: ufw: command not found

please help me

A: If the command ufw returns:
sudo: ufw: command not found

Than I'm almost sure that ufw is not installed yet.
Use apt-get to install ufw on you machine.
Like Matthew Flaschen typed above type:
sudo apt-get install ufw

A: an open port helps you nothing, if you don't have a server listening on this port.
if you install mysql it will automatically open port 3306

A: sudo apt-get install ufw

You'll find searching the web helpful on these types of questions.

A: Type whereis ufw. If you get back something like this:
ufw: /usr/sbin/ufw /usr/share/man/man1/ufw.1.gz ...

(I'm making up the details, I don't have ufw installed.) If you get back something like that, it tells you that the ufw binary is at /usr/sbin/ufw. Perhaps your $PATH doesn't recognize /usr/sbin. In that case you should call ufw with a full path: sudo /usr/sbin/ufw allow 3306/tcp.
ufw may well be somewhere inside /etc (or inside /etc/init.d), rather than in any .../bin directory.
If whereis ufw returns:
ufw:

then you probably don't have it installed, and will need to do:
sudo apt-get install ufw

as Matthew Flaschen says.


text:
Q: How to apply triplet loss function in resnet50 for the purpose of deepranking I try to create image embeddings for the purpose of deep ranking using a triplet loss function. The idea is that we can take a pretrained CNN (e.g. resnet50 or vgg16), remove the FC layers and add an L2 normalization function to retrieve unit vectors which can then be compared via a distance metric (e.g. cosine similarity). As far as I understand the predicted vectors that come out of a pretrained CNN are not optimal, but are a good start. By adding the triplet loss function we can re-train the network to keep similar pictures 'close' to each other and different pictures 'far' apart in the feature space. Inspired by this notebook  , I tried to setup the following code, but I get an error ValueError: The name "conv1_pad" is used 3 times in the model. All layer names should be unique..
# Anchor, Positive and Negative are numpy arrays of size (200, 256, 256, 3), same for the test images

pic_size=256
def shared_dnn(inp):
    base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(3, pic_size, pic_size),
                          input_tensor=inp)
    x = base_model.output
    x = Flatten()(x)
    x = Lambda(lambda x: K.l2_normalize(x,axis=1))(x)
    for layer in base_model.layers[15:]:
        layer.trainable = False
    return x

anchor_input = Input((3, pic_size,pic_size ), name='anchor_input')
positive_input = Input((3, pic_size,pic_size ), name='positive_input')
negative_input = Input((3, pic_size,pic_size ), name='negative_input')

encoded_anchor = shared_dnn(anchor_input)
encoded_positive = shared_dnn(positive_input)
encoded_negative = shared_dnn(negative_input)

merged_vector = concatenate([encoded_anchor, encoded_positive, encoded_negative], axis=-1, name='merged_layer')

model = Model(inputs=[anchor_input,positive_input, negative_input], outputs=merged_vector)

#ValueError: The name "conv1_pad" is used 3 times in the model. All layer names should be unique.
model.compile(loss=triplet_loss, optimizer=adam_optim)

model.fit([Anchor,Positive,Negative],
          y=Y_dummy,
          validation_data=([Anchor_test,Positive_test,Negative_test],Y_dummy2), batch_size=512, epochs=500)

I am new to keras and I am not quite sure how to solve this. The author in the link above creates his own CNN from scratch, but I would like to build it upon resnet (or vgg16). How can I configure ResNet50 to use a triplet loss function (in the link above you find also the source code for the triplet loss function).

A: In your ResNet50 definition, you've written
base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(3, pic_size, pic_size), input_tensor=inp)

Remove the input_tensor argument. Change input_shape=inp.
If you're using TF backend as you mentioned the input should be (256, 256, 3), then your input should be (pic_size, pic_size, 3).
def shared_dnn(inp):
    base_model = ResNet50(weights='imagenet', include_top=False, input_shape=inp)
    x = base_model.output
    x = Flatten()(x)
    x = Lambda(lambda x: K.l2_normalize(x,axis=1))(x)
    for layer in base_model.layers[15:]:
        layer.trainable = False
    return x

img_shape=(256, 256, 3)
anchor_input = Input(img_shape, name='anchor_input')
positive_input = Input(img_shape, name='positive_input')
negative_input = Input(img_shape, name='negative_input')

encoded_anchor = shared_dnn(anchor_input)
encoded_positive = shared_dnn(positive_input)
encoded_negative = shared_dnn(negative_input)

merged_vector = concatenate([encoded_anchor, encoded_positive, encoded_negative], axis=-1, name='merged_layer')

model = Model(inputs=[anchor_input,positive_input, negative_input], outputs=merged_vector)
model.compile(loss=triplet_loss, optimizer=adam_optim)

model.fit([Anchor,Positive,Negative],
          y=Y_dummy,
          validation_data=([Anchor_test,Positive_test,Negative_test],Y_dummy2), batch_size=512, epochs=500)

The model plot is as follows:
model_plot


text:
Q: Returning each value from for loop in c# EDIT: I realized that I had been going about it completely the wrong way and after an overhaul, got it working. Thanks for the tips guys, I'll keep them in mind for the future.
I've hit an unusual problem in my program. What I need to do is find the difference between two times, divide it by 1.5 hours, then return the starting time followed by each 1.5 hour increment of the starting time. So if the time was 11:45 am - 2:45 pm, the time difference is three hours, 3/1.5 = 2, then return 11:45 am and 1:15 pm. At the moment, I can do everything except return more than one time. Depending on what I've tried, it returns either the initial time (11:45 am), the first increment (1:15 pm) or the end time (2:45 pm). So far I've tried a few different types of for and do/while loops. The closest I've come was simply concatenating the start time and the incremented time, but the start and end times can range anywhere from 3 - 6 hours so that's not a practical way to do it.
The latest thing I tried:
int i = 0;
do{
   i++;
   //Start is the starting time, say 11:45 am
   start = start.AddMinutes(90);
   return start.ToShortTimeString();
} while (i < totalSessions); //totalSessions is the result of hours / 1.5

and I'm calling the function on a dynamic label (which is also in a for loop):
z[i] = new Label();
z[i].Location = new Point(PointX, PointZ);
z[i].Name = "sessionTime_" + i;
z[i].Text = getPlayTimes(dt.Rows[i][1].ToString());
tabPage1.Controls.Add(z[i]);
z[i].BringToFront();
PointZ += z[i].Height;

I'm pretty new to c# so I guess I've just misunderstood something somewhere.

A: I think you're trying to solve the problem the wrong way.  Instead of returning each value as you come to it, create a collection ie List, and push each of your results onto the list until your finishing condition is met.
Then, return the whole array as your return value.  This way you will have a nice self-contained function that doesn't have cross-concerns with other logic - it does only it's one little task but does it well.
Good luck!

A: It's a bit difficult to determine your exact use case, as you haven't offered the complete code you are using. However, you can do what you are asking by using the yield return functionality:
public IEnumerable<string> GetPlayTimes()
{
    int i = 0;
    do
    {
        i++;
        //Start is the starting time, say 11:45 am
        start = start.AddMinutes(90);
        yield return start.ToShortTimeString();
    } while (i < totalSessions); //totalSessions is the result of hours / 1.5
}

And then use it like so:
foreach (var time in GetPlayTimes())
{
    // Do something with time
}


text:
Q: How to list the source URLs from saved html files from a folder? I have a lot of html files in a folder. I used them
in a project. I want to build a References.txt
file in which the URL from which each html file was saved
will be listed with the time stamp on which it was saved.
There will be a space between each URL and its corresponding
timestamp.
How can I do that from Ubuntu 12.04 using a terminal command
or shell script?
One information which can help you is that the URL from which a html
file was saved is present in the second line of the html file
and that is also visible by opening the file in a browser and then
going to source view. But I don't know how to extract it from there
using a command.
First two lines from one of those files:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- saved from url=(0084)http://www.forexrealm.com/technical-analysis/technical-indicators/typical-price.html -->

A: Run the following command in a directory holding html files.
for f in *.html; do echo $(cat "$f" | sed -n '2p' | grep -o 'http://.*\.html') $(stat -c %y "$f");  done > References.tx

Script:
#!/usr/bin/bash

ref_file='References.txt';
> "$ref_file";

for html in *.html
do
    mtime=$(stat -c %y "$html")
    address=$(cat "$html" | sed -n '2p' | grep -o 'http://.*\.html')
    echo "$address $mtime" >> $ref_file;
done


text:
Q: How to hide an image only for Outlook I've built an HTML Email template which looks really good on most of the email clients but Outlook. It just doesn't want to read any inline CSS for images. Is there are way to hide images just for Outlook? Thanks for the help.

A: Put this around the image:
<!--[if !mso]><!--> <img> <!--<![endif]-->
I encourage you to post your html email so we could take a look and maybe suggest a solution.


text:
Q: wrapper method in extended NSManagedObject class objective-c I am using CoreData in an iOS application. Everything works fine except for fields marked as Boolean in xcdatamodel that get modeled and NSNumber.
For this kind of fields I want to write some utility method in extended class, but I was wondering where's the best location for writing them or what's the best practice.
In MyManagedObject.h I have:
@interface MyManagedObject : NSManagedObject {
@private
}
@property (nonatomic, retain) NSNumber * mandatory;
@end

Where mandatory is a boolean in data model. This is the generated class from xcode:
@implementation MyManagedObject
@dynamic mandatory;

At this point, for properly using the entity I need to write somewhere some utility wrapper methods, probably in the entity itself, such as:
[myManagedObject mandatoryWrapper:YES];

-(void)mandatoryWrapper:(BOOL)mandatory {
    // convert boolean to number
    self.mandatory=convertedMandatory;
}

But I am aiming to use the original getter/setter for not generating "confusion":
// setter
myManagedObject.mandatory=YES;
//getter
if(myManagedObject.isMandatory)

but I suppose that rewriting the original methods, will cause some problem later on in the application lifecycle, for example when saving or retrieving in context.
thanks.

A: If you want a true boolean property, then your are forced to change the name. I would recommend just making the it a property of the class and not the entity because the entity doesn't have to know about them.
In your case, you would need something like:
@property BOOL isMandatory;

-(BOOL) isMandatory{
   return [self.mandatory boolValue];
}

-(void) setIsMandatory:(BOOL) boolVal{
  self.mandatory=[NSNumber numberWithBool:boolVal];
}

This lets you use convience constructions like:
If (self.isMandtaory)...
self.isMandatory=YES;

Core Data is happy because the entity modeled NSNumber property is still there and works as expected but the human can use the easier to comprehend boolean version.


text:
Q: Are transient suppression diodes necessary for a battery powered system? I've seen on designs where there is a TVS transient suppression diode on the voltage supply. For example, when the voltage supply is say a wall plug.
However, are such diodes really necessary in a battery powered system? I can't think of any way where the battery supply could "overshoot" the rated voltage.

A: It could still happen.  Static discharge is one method, inductive switching is another, or perhaps some odd grounding issues bumping up voltages.  I would still use TVS diodes on sensitive components.

A: If you have ESD-sensitive device inside, it may die when user replaces the battery and touches contacts. Other than that, I can't think of anything.


text:
Q: how to display my users from firebase using angularjs i'm trying to display the names of my users in a list using angularjs.
already tried to look for an answer in the docs.
"users" : {
    "simplelogin:24" : {
      "age" : "24",
      "email" : "a@a.com",
      "gender" : "male",
      "location" : "USA",
      "name" : "IY"
    },
    "simplelogin:25" : {
      "age" : "21",
      "email" : "girl@girls.com",
      "gender" : "female",
      "location" : "USA",
      "name" : "iris"
    }
  }

here what i'm trying to do:
var app = angular.module('myApp.home', ['firebase.auth', 'firebase', 'firebase.utils', 'ngRoute']);

  app.controller('HomeCtrl', ['usersList','$scope', 'fbutil', 'user', '$firebaseObject', 'FBURL',
    function (usersList, $scope, fbutil, user, $firebaseObject, FBURL) {
    $scope.syncedValue = $firebaseObject(fbutil.ref('syncedValue'));
    $scope.user = user;
    $scope.FBURL = FBURL;
    $scope.users = usersList;
  }]);

  app.factory('usersList', ['fbutil', '$firebaseArray',
   function(fbutil, $firebaseArray) {
    var ref = fbutil.ref('users').limitToLast(50);
    return $firebaseArray(ref);
  }]);

and:

{{user.name}}

A: Most basic way to get the users and show them:
    var app = angular.module('myApp.home', [])

      app.factory('usersList', function(fbutil, $firebaseArray) {
        //Get the firebase reference
        var ref = fbutil.ref('users');
        //return the array of users
        return $firebaseArray(ref);
      });

      app.controller('HomeCtrl', function (usersList, $scope) {
        //Put the users array in the scope.users
        $scope.users = usersList;
      });

And the ng-repeat just stays the same.

A: Since you didn't put an angularJS code, I don't know how to fix your code.
However, I can inform about 'how to display the name property of firebase object.'
    var ref = new Firebase(your firebase url);
    var userOne = $firebaseObject(ref.child('users').child('simplelogin:24'));
    userOne.$loaded(function(){
                console.log(userOne.name);
              });
    var userTwo = $firebaseObject(ref.child('users').child('simplelogin:25'));
    userTwo.$loaded(function(){
    console.log(userTwo.name);
});

I hope this code is what you wanted.
And, you have read the doc of angularFire?
https://www.firebase.com/docs/web/libraries/angular/api.html
Give it a try!


text:
Q: Haskell refer to list of list element --This line count how many 0 are in the list
hasZero :: [Int] -> Bool
hasZero x = 0 < sum [1 | y <- x, y == 0]

--In this line I want to count how many empty list are in the list, but I got compiling erorr.
hasEmpty :: [[a]] -> Bool
hasEmpty x = 0 < [1 | y <- [x], y == []]

A: There are 2 issues in your second method - you are missing sum which does the count in the first one, and you are wrapping passed list into another one, it should be y <- x as in the first one:
hasEmpty :: [[a]] -> Bool
hasEmpty x = 0 < sum [1 | y <- x, null y]

Which can be rewritten as:
hasEmpty :: [[a]] -> Bool
hasEmpty = any null

A: In the first example, you summed the elements of the list your list comprehension generated. In the second, you haven't done this. You also don't need to put x in brackets.
hasEmpty :: Eq a => [[a]] -> Bool
hasEmpty x = 0 < sum [1 | y <- x, y == []]

This is a peculiar way to accomplish this goal. The more idiomatic way (aside from using the existing Prelude function any) would be to use pattern matching and recursion.
hasZero :: [Int] -> Bool
hasZero [] = True
hasZero (0:_) = True
hasZero (_:xs) = hasZero xs

Using any:
hasZero :: [Int] -> Bool
hasZero = any (== 0)


text:
Q: Python - Sorting values in a dict of lists A set of 13 sensors transmit numerical data that is read every 5 minutes. To capture these values I used a dictionary of lists:
Sensors = {
         'Sensor1':[10.52,12.45,15.70],
         'Sensor5':[12.32,22.80,30.42],
         'Sensor3':[4.7,3.4,2.1],
         'Sensor8':[2.34,4.28,7.10],
         'Sensor4':[10.64,14.76,4.25],
         'Sensor2':[3.21,7.88,9.22],
         'Sensor6':[4.11,9.32,2.70],
         'Sensor9':[11.45,14.72,8.30],
         'Sensor7':[6.10,3.98,10.66],
         'Sensor10':[7.22,8.67,10.99],
         'Sensor13':[1.19,4.65,0.87],
         'Sensor12':[2.10,5.46,3.21],
         'Sensor11':[5.80,8.22,14.39]
         }

I need to sort this list so that the sensors that have had a positive increase appear at the top.
To achieve this goal, I created another dictionary DeltaValues with the name of the sensor and the difference between the last and the first value captured:
 DeltaValues={}
  for x, y in Sensors.items():
      if len(y) > 1:
         DeltaValues[x] = format(y[-1] - y[0],'.2f')
      else:
         DeltaValues[x] = format(y[0],'.2f')

I used this syntax to sort:
sorted_d = {k: v for k, v in sorted(DeltaValues.items(), key=lambda x: x[1])}

But the result was not what I expected:
print(sorted_d)

{'Sensor13': '-0.32',
 'Sensor6': '-1.41',
 'Sensor3': '-2.60',
 'Sensor9': '-3.15',
 'Sensor4': '-6.39',
 'Sensor12': '1.11',
 'Sensor5': '18.10',
 'Sensor10': '3.77',
 'Sensor7': '4.56',
 'Sensor8': '4.76',
 'Sensor1': '5.18',
 'Sensor2': '6.01',
 'Sensor11': '8.59'}

A: Dicts do not guarantee to return the values in order in which they were put in.
Consider ordered dict. https://docs.python.org/3/library/collections.html#collections.OrderedDict

A: You could sort the (key, value) pairs and leave them in a list:
>>> sorted(Sensors.items(), key= lambda sensor:sensor[1][-1] - sensor[1][0])
[('Sensor4', [10.64, 14.76, 4.25]), ('Sensor9', [11.45, 14.72, 8.3]), ('Sensor3', [4.7, 3.4, 2.1]), ('Sensor6', [4.11, 9.32, 2.7]), ('Sensor13', [1.19, 4.65, 0.87]), ('Sensor12', [2.1, 5.46, 3.21]), ('Sensor10', [7.22, 8.67, 10.99]), ('Sensor7', [6.1, 3.98, 10.66]), ('Sensor8', [2.34, 4.28, 7.1]), ('Sensor1', [10.52, 12.45, 15.7]), ('Sensor2', [3.21, 7.88, 9.22]), ('Sensor11', [5.8, 8.22, 14.39]), ('Sensor5', [12.32, 22.8, 30.42])]

A: Here is the solution
import operator
def getSortedSensorData():
    sensors = {
         'Sensor1':[10.52,12.45,15.70],
         'Sensor5':[12.32,22.80,30.42],
         'Sensor3':[4.7,3.4,2.1],
         'Sensor8':[2.34,4.28,7.10],
         'Sensor4':[10.64,14.76,4.25],
         'Sensor2':[3.21,7.88,9.22],
         'Sensor6':[4.11,9.32,2.70],
         'Sensor9':[11.45,14.72,8.30],
         'Sensor7':[6.10,3.98,10.66],
         'Sensor10':[7.22,8.67,10.99],
         'Sensor13':[1.19,4.65,0.87],
         'Sensor12':[2.10,5.46,3.21],
         'Sensor11':[5.80,8.22,14.39]
         }

    sensorData = {};

    for sensor in sensors:
        data = sensors[sensor]
        data = sorted(data, reverse = True)
        sensorData[sensor] = data[0];

    sensorData = sorted( sensorData.items(), key=operator.itemgetter(1),reverse=True )
    print( sensorData )

Output

[('Sensor5', 30.42), ('Sensor1', 15.7), ('Sensor4', 14.76),
  ('Sensor9', 14.72), ('Sensor11', 14.39), ('Sensor10', 10.99),
  ('Sensor7', 10.66), ('Sensor6', 9.32), ('Sensor2', 9.22), ('Sensor8',
  7.1), ('Sensor12', 5.46), ('Sensor3', 4.7), ('Sensor13', 4.65)]

A: If you are on python 3.5+, use regular dict as follows:
dict(sorted(Sensors.items(), key=lambda x: x[1][-1] - x[1][0], reverse=True))

Out[11]:
{'Sensor5': [12.32, 22.8, 30.42],
 'Sensor11': [5.8, 8.22, 14.39],
 'Sensor2': [3.21, 7.88, 9.22],
 'Sensor1': [10.52, 12.45, 15.7],
 'Sensor8': [2.34, 4.28, 7.1],
 'Sensor7': [6.1, 3.98, 10.66],
 'Sensor10': [7.22, 8.67, 10.99],
 'Sensor12': [2.1, 5.46, 3.21],
 'Sensor13': [1.19, 4.65, 0.87],
 'Sensor6': [4.11, 9.32, 2.7],
 'Sensor3': [4.7, 3.4, 2.1],
 'Sensor9': [11.45, 14.72, 8.3],
 'Sensor4': [10.64, 14.76, 4.25]}

If you are on python < 3.5+, use collecions.OrderedDict as follows:
collections.OrderedDict(sorted(Sensors.items(), key=lambda x: x[1][-1] - x[1][0], reverse=True))

Out[2067]:
OrderedDict([('Sensor5', [12.32, 22.8, 30.42]),
             ('Sensor11', [5.8, 8.22, 14.39]),
             ('Sensor2', [3.21, 7.88, 9.22]),
             ('Sensor1', [10.52, 12.45, 15.7]),
             ('Sensor8', [2.34, 4.28, 7.1]),
             ('Sensor7', [6.1, 3.98, 10.66]),
             ('Sensor10', [7.22, 8.67, 10.99]),
             ('Sensor12', [2.1, 5.46, 3.21]),
             ('Sensor13', [1.19, 4.65, 0.87]),
             ('Sensor6', [4.11, 9.32, 2.7]),
             ('Sensor3', [4.7, 3.4, 2.1]),
             ('Sensor9', [11.45, 14.72, 8.3]),
             ('Sensor4', [10.64, 14.76, 4.25])])


text:
Q: Why mysql.connector works without problem with python2.7 and not with python3? I checked different post like:
Is there a way to use 'pool_reset_connection' from mysql-connector-python with MariaDB 10.4.7?
But I can't solve my isue, I have a program write in python 2.7; now I'm moving everything to python 3 but I got problems with mysql.connector.
In this moment I'm using python 3.8.2 and mysql-connector-python==8.0.19 but I try with different version of python 3, but I was getting always the same error on mysql.connector when I try to close the connection.
Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\mysql\connector\connection.py", line 819, in reset_session
    self.cmd_reset_connection()
  File "C:\Python38\lib\site-packages\mysql\connector\connection.py", line 1166, in cmd_reset_connection
    raise errors.NotSupportedError("MySQL version 5.7.2 and "
mysql.connector.errors.NotSupportedError: MySQL version 5.7.2 and earlier does not support COM_RESET_CONNECTION.

...
...

mysql.connector.errors.OperationalError: 1047 (08S01): Unknown command

I'm not sure how to solve it, I try in different way increasing the pool and having different pool or just shutdown the connection but in a big project after I got pool exhaust so I really need close the connection but I can't solve this issue; can someone help me pls?
I try even to change the mysql-connector library as explained in the other stackoverflow ticket but every time I change it I got other problems.

A: It's a problem how MySQL Connector/Python detects the server version:
Since replication doesn't work with a 2-digit major version number, MariaDB uses a so called RPL hack which was introduced with version 10.0 and sends the following version number to the client 5.5.5-10.4.13-MariaDB. See also What does the first part of the MariaDB version string mean.
Since MariaDB Connector/Python is not aware of it, it assumes that the server version number is 5.5.5 and will raise a NotSupportedError exception when checking >= 5.7.3.
You can either patch MySQL Connector/Python (fixing server_version in do_handshake()) or you can try MariaDB Connector/Python. It's currently beta, but GA is expected still this month (pip3 install mariadb)


text:
Q: How to design custom keypad in android? I have designed a custom keypad as shown below  but its keys are blurred how to make it look nice
below is the java code in which keyboard view in inflated
@Override
    public View onCreateInputView() {
        kv = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard, null);
        keyboard = new Keyboard(this, R.xml.qwerty);
       // keyboard_sym = new Keyboard(this, R.xml.symbol);
        kv.setKeyboard(keyboard);

        kv.setOnKeyboardActionListener(this);
        Log.e(TAG,"Started");
        return kv;
    }

Below is xml file code
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%p"
    android:horizontalGap="8dp"
    android:verticalGap="5dp"

    android:keyHeight="40dp"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    >
    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"  />
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5"/>
        <Key android:codes="54" android:keyLabel="6"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>
    <Row>
        <Key android:codes="113" android:keyLabel="q" android:keyEdgeFlags="left"/>
        <Key android:codes="119" android:keyLabel="w"/>
        <Key android:codes="101" android:keyLabel="e"/>
        <Key android:codes="114" android:keyLabel="r"/>
        <Key android:codes="116" android:keyLabel="t"/>
        <Key android:codes="121" android:keyLabel="y"/>
        <Key android:codes="117" android:keyLabel="u"/>
        <Key android:codes="105" android:keyLabel="i"/>
        <Key android:codes="111" android:keyLabel="o"/>
        <Key android:codes="112" android:keyLabel="p" android:keyEdgeFlags="right"/>
    </Row>
    <Row>
        <Key android:codes="97" android:keyLabel="a" android:keyEdgeFlags="left"/>
        <Key android:codes="115" android:keyLabel="s"/>
        <Key android:codes="100" android:keyLabel="d"/>
        <Key android:codes="102" android:keyLabel="f"/>
        <Key android:codes="103" android:keyLabel="g"/>
        <Key android:codes="104" android:keyLabel="h"/>
        <Key android:codes="106" android:keyLabel="j"/>
        <Key android:codes="107" android:keyLabel="k"/>
        <Key android:codes="108" android:keyLabel="l" android:keyEdgeFlags="right"/>

    </Row>
    <Row>
        <Key android:codes="-1" android:keyEdgeFlags="left"  android:keyWidth="15%p" android:keyIcon="@drawable/arrow"/>
        <Key android:codes="122" android:keyLabel="z"/>
        <Key android:codes="120" android:keyLabel="x"/>
        <Key android:codes="99" android:keyLabel="c"/>
        <Key android:codes="118" android:keyLabel="v"/>
        <Key android:codes="98" android:keyLabel="b"/>
        <Key android:codes="110" android:keyLabel="n"/>
        <Key android:codes="109" android:keyLabel="m"/>
        <Key android:codes="-5"  android:keyIcon="@drawable/backspace" android:keyWidth="15%p" android:isRepeatable="true" android:keyEdgeFlags="right"/>

    </Row>
    <Row android:rowEdgeFlags="bottom">
        <Key  android:codes="1000" android:keyLabel="Sys" android:keyWidth="20%p"  android:keyEdgeFlags="left"/>
        <Key android:codes="47" android:keyLabel="/" android:keyWidth="10%p" />
        <Key android:codes="32" android:keyLabel="SPACE" android:keyWidth="40%p" android:isRepeatable="true"/>
        <Key android:codes="46" android:keyLabel="." android:keyWidth="10%p" android:isRepeatable="true"/>
        <Key android:codes="-4"  android:keyIcon="@drawable/downleft" android:keyWidth="15%p" android:keyEdgeFlags="right"/>
    </Row>
</Keyboard>

How to change the color of key so it  not look blurred ?

A: The keys of a keyboard are grouped as rows. It's good practice to limit the number of keys on a row to a maximum of ten, with each key having a width equal to 10% of the keyboard. The height of the keys  can be adjusted, but values less than 48dp are not recommended. Change KeyHeight and check once.


text:
Q: MMWormhole.framework crashes on iPhone 4/4s because of "wrong architecture". Works fine on 5/5s and 6 I am bringing in the Wormhole library via Cocoapods. Everything works as expected on iPhone 5 and 6, but on 4s simulator it crashes at launch with the error below. Looks like all the architecture settings are correct and in-sync between app and used frameworks.

Library not loaded: @rpath/MMWormhole.framework/MMWormhole
  Referenced from:
  /Users/myuser/Library/Developer/CoreSimulator/Devices/F04DCEBB-2E34-49C7-9554-E6048D3349E2/data/Containers/Bundle/Application/BC69F59F-7896-44BE-A7E6-26B46A47E7FD/AppName.app/AppName
  Reason: no suitable image found.  Did find:
    /Users/myuser/Library/Developer/CoreSimulator/Devices/F04DCEBB-2E34-49C7-9554-E6048D3349E2/data/Containers/Bundle/Application/BC69F59F-7896-44BE-A7E6-26B46A47E7FD/AppName.app/Frameworks/MMWormhole.framework/MMWormhole:
  mach-o, but wrong architecture


text:
Q: Getting code versions from svn svn provides the up-to-date version of the code.
Is it possible to get the different versions ( not revisions ) of a project stored in svn ?
UPDATE:
It is not my project, it is a general question for any open source project. I do not know if there is any specific used tags or not.

A: I you have tagged them, svn co url://path/to/repo/tags/v2_0_1. If you have not, you will need to find from logs or something which precise revision corresponds to your version. (The /tags directory is not a feature of Subversion itself, but this is a common way to arrange things. To svn, tags and branches are just copies of individual revisions.)
Of course, in order for this to work, you need to obey some common conventions. A common workflow is to always have exactly three directories in the root of your repo; these are trunk, branches, and tags. You would always create new branches for development work from the head in trunk, merge to trunk when you are done, tag in tags when releasing. The command in each case is simply svn cp. See http://svnbook.red-bean.com/en/1.6/svn.ref.svn.c.copy.html