text:
Q: Is there a way to manually clear ram in python 3.7? I am trying to make a program that removes the background in a video so that only the foreground is shown. It works for short videos, but on longer ones it slows down exponentially and begins using more and more memory so that the program crashes.
I have tried deleting the variables used in for loops as shown in the code below.
def video_generator(name_of_video, video, cap, number_of_frames):
    check, frame = cap.read()
    A = np.array([])
    a = np.array([])

    if cap.isOpened():
        width = int(cap.get(3))
        height = int(cap.get(4))

    dims = (height, width)

    while cap.isOpened():
        check, frame = cap.read()

        if check:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).flatten()
            A = np.append(A, gray)
            a = np.append(a, 'row')
            image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        else:
            break

    B = np.resize(A, (number_of_frames, width * height))

    U, S, V = decomposition.randomized_svd(B, 2)
    background = U @ np.diag(S) @ V

    foreground = ([])

    def generate_frames(B, background):
        for i in range(number_of_frames):
            foreground = np.reshape(B[i] - background[i], dims)
            frame = plt.imshow(foreground, cmap = 'gray')
            plt.savefig('D:/Python_Programs/BR_SVD/Frames/' + name_of_video + '/file_' + str(i + x * number_of_frames).zfill(2) + '.png')

            del frame
            del foreground
            gc.collect()

    generate_frames(B, background)

if number_of_frames_initial <= 200:
    cap = cv2.VideoCapture(video)
    video_generator(name_of_video, video_initial, cap_initial, number_of_frames_initial)

else:
    number_of_videos = int(number_of_frames_initial/200 + 1)
    time_of_videos = duration/number_of_videos

    for x in range (number_of_videos):

        subprocess.call ([
            'ffmpeg', '-i', video_initial, '-ss', str(time_of_videos * x), '-t', str(time_of_videos), 'D:/Python_Programs/BR_SVD/Temp_Videos/video_%02d.mp4' % x])

        video = 'D:/Python_Programs/BR_SVD/Temp_Videos/video_%02d.mp4' % x
        cap = cv2.VideoCapture(video)
        number_of_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        video_generator(name_of_video, video, cap, number_of_frames)

        del B
        del background
        gc.collect()

A: *

*http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection

*http://docs.python.org/library/gc.html

*http://arctrix.com/nas/python/gc/
There's no definitive resource on how Python does its garbage collection (other than the source code itself), but those 3 links should give you a pretty good idea.
Update
The source is actually pretty helpful. How much you get out of it depends on how well you read C, but the comments are actually very helpful. Skip down to the collect() function and the comments explain the process well (albeit in very technical terms).

A: As an answer to your top-level question: Explicitly deling the last reference to an object, and calling gc.collect() are the closest thing to manually clearing RAM Python has, and neither one of them is typically needed. Function locals are cleaned automatically when the function exits (as if each local name was deled), and cyclic GC runs every few hundred allocations by default, which is usually fine, unless you have huge objects participating in cycles. Aside from that, the general rule is to explicitly call clean up methods (or better, use with statements when available) to ensure resources are released promptly, and don't keep references around longer than you need them (if you keep a global list that you keep appending to, no GC can save you, as you asked to hold onto that stuff forever).
For specific recommendations:
I believe you should be calling cap.release() on your VideoCapture object when you're done with it; leaving one open for every loop over range(number_of_videos)  is probably tying up resources for quite a while. In theory the docs claim the destructor calls release for you, but it's best to call it explicitly to be sure, especially since reference cycles are surprisingly easy to trigger, and that can end up delaying (or for poorly written or Python 2 extension modules, block completely) the clean up you're expecting.
Your repeated calls to np.append are going to slow you down a lot as well; np.append creates a copy of the input and appends to it, which is going to act as a form of Schlemiel the Painter's algorithm; each new frame ends up copying all the data from before, plus the new data, and that prior data keeps growing and growing. I'd suggest keeping A/a as plain Python lists that you call .append on, and only recombine once at the end, to avoid quadratic growth in memory copying.
I'll also note that your del B and del background make no sense; they exist solely within the scope of video_generator, and you're trying to del them while at global scope (after they've been cleaned up anyway, and from a scope where they never existed). Explicit dels of names is usually not needed; locals are cleaned up when a function exits (assuming no other references exist), so you're trying to do the runtime's job for it when you don't need to.


text:
Q: Update a third table by comparing values of two tables using triggers Hii
I have three tables (Table1, Table2, Table3).All the three tables have same column names(Company, License_count). when an update will happen in table2, trigger will compare the values of table2 & table1 and insert the difference into table three. I have to do this only for single row.
Can anyone help?

A: Alright, I got it.
drop trigger if exists table1and2difference;
CREATE TRIGGER table1and2difference
AFTER UPDATE ON Table2
FOR EACH ROW
  INSERT INTO Table3(Company, License_count)values
    (new.Company, (SELECT (SUM(License_count1) - License_count2) as License_count FROM
                   (SELECT Company as company1, License_count as License_count1 FROM
                           Table1 WHERE Company=new.Company) AS t1
                   INNER JOIN
                   (SELECT Company as company2, License_count as License_count2 FROM
                           Table2 WHERE Company=new.Company) As t2
                   On company1=company2));

For reference, these are the values I used to test the trigger.
create table Table1(
Company VARCHAR(100) NOT NULL,
License_count INT NOT NULL);

insert into Table1(Company,License_count)values('Test_company',10);

create table Table2(
Company VARCHAR(100) NOT NULL,
License_count INT NOT NULL);

insert into Table2(Company,License_count)values('Test_company',8);

create table Table3(
Company VARCHAR(100) NOT NULL,
License_count INT NOT NULL);

drop trigger if exists table1and2difference;
CREATE TRIGGER table1and2difference
AFTER UPDATE ON Table2
FOR EACH ROW
     INSERT INTO Table3(Company, License_count)values
         (new.Company, (SELECT (SUM(License_count1) - License_count2) as License_count FROM
                            (SELECT Company as company1, License_count as License_count1 FROM Table1 WHERE Company=new.Company) AS t1
                            INNER JOIN
                            (SELECT Company as company2, License_count as License_count2 FROM Table2 WHERE Company=new.Company) As t2
                            On company1=company2));

update Table2 set License_count=7;

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTTPPost not sending proper values This is 3rd question today pertaining to Android, this is starting to get embarrassing. I'm trying to send a HTTP POST request to this PHP page, I'm trying to retrieve information for albums from my MySQL database:
<?php

if (isset($_POST['req']) && $_POST['req'] != '') {
    $request = $_POST['req'];

    // Including the handler for the database
    require_once 'include/db_functions.php';
    $db = new db_functions();

    // Array for response
    $response = array("req" => $request, "success" => 0, "error" => 0);

    // Check the request type

    // Obtains a list of medias for the listview.
    if ($request == 'listemedias'){
        $mediaList = $db->getMediasList();
        // Parse the media list
        for($i = 0; $i < count($mediaList); $i++){
            $response["mediaList"][$i]["id"] = $mediaList[$i]['idmedia'];
            $response["mediaList"][$i]["titre"] = $mediaList[$i]['titre'];
            $response["mediaList"][$i]["annee"] = $mediaList[$i]['annee'];
            $response["mediaList"][$i]["duree"] = $mediaList[$i]['duree'];
            $response["mediaList"][$i]["jaquette"] = $mediaList[$i]['jaquette'];
        }
        $response["success"] = 1;
        echo json_encode($response);
        exit;
    }

    // Obtains specific informations for a specific media.
    if ($request == 'media') {
        if (isset($_POST['no']) && $_POST['no'] != '') {
            $no = $_POST['no'];
            $media = $db->getMedia($no);
            if ($media != false){
                $response["success"] = 1;
                $response["media"]["id"] = $media["idmedia"];
                $response["media"]["titre"] = $media["titre"];
                $response["media"]["annee"] = $media["annee"];
                $response["media"]["duree"] = $media["duree"];
                $response["media"]["jaquette"] = $media["jaquette"];
                $response["media"]["genre"] = $media["nomgenre"];
                $response["media"]["editeur"] = $media["nomediteur"];
                $response["media"]["collection"] = $media["nomcollection"];
            } else {
                echo 'Media does not exist';
                exit;
            }
            echo json_encode($response);
            exit;
        } else {
            echo 'Access Denied';
            exit;
        }
    }

} else {
    echo 'Access Denied';
    exit;
}
?>

The issue is, I'm only getting "Access Deniedn" (Yes, with the n) as a reply from my HTTP requests. Here is my android java code:
Here is the function that sets the parameters for the request:
public JSONObject getMediaList(){
        List<NameValuePair> params = new ArrayList<NameValuePair>(1);

        // We add the request name to get all medias from the API service
        params.add(new BasicNameValuePair("req","listemedias"));

        // We get the JSON Object from the API service
        JSONObject json = jsonParser.getJSONFromUrl(url, params);

        return json;
    }

And here is the getJSONFromURL function from the JSONParser class which does the actual request:
public JSONObject getJSONFromUrl (String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

I apologize for posting about this, I'm new to Android, and I've been trying to wrap my head around it for a couple of days.
EDIT: After debugging a bunch of times, params do contain "req" as a name and "listemedias" associated to it. Why isn't it working at all? Is it an encoding problem? Is there any way I can verify the header sent for the request?
EDIT2: After some extra tinkering, I just can't figure it out, I'm throwing the towel. Is there any other method I can use that actually works?


text:
Q: Problem with python and __import__ Sorry for the generic title, will change it once I understand the source of my problem
I have the following structure:
foo/
foo/__init__.py
foo/bar/
foo/bar/__init__.py
foo/bar/some_module.py

When I try to import some_module by doing so:
from foo.bar import some_module

it works like a charm.
But this is no good for me, since I only know the name of the module to import in runtime. so if I try:
from foo.bar import *
mod=__import__('some_module')

I get an error. Am I doing something wrong? Is there a better way to do this? and why is this happening?
Why is that? I am not quite sure I completely understand the concept behind python packages. I thought they were equivalent to java's packages and thus

A: I believe the proper way to do this is:
mod = __import__('foo.bar', fromlist = ['some_module'])

This way even the 'foo.bar' part can be changed at runtime.
As a result some_modulewill be available as mod.some_module; use getattr if you want it in a separate variable:
the_module = getattr(mod, 'some_module')

A: from foo.bar import *

is a bad practice since it imports some_module into the global scope.
You should be able to access your module through:
import foo.bar
mod = getattr(foo.bar, 'some_module')

It can be easily demonstrated that this approach works:
>>> import os.path
>>> getattr(os.path, 'basename')
<function basename at 0x00BBA468>
>>> getattr(os.path, 'basename\n')
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    getattr(os.path, 'basename\n')
AttributeError: 'module' object has no attribute 'basename
'

P.S. If you're still interested in using your kind of import statement. You need an eval:
from foo.bar import *
eval('some_module')

To clarify: not only it's bad practice to use *-import it's even worse in combination with eval. So just use getattr, it's designed exactly for situations like yours.

A: From the docs:

Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.

However, the dotted notation should work:
mod = __import__('foo.bar.some_module')


text:
Q: Equals validation vs indexOf validation? I need to validate if one String contains the char $  before replace this one.
I did two implementations for this propose.
The first implementation always execute replace(char oldChar, char newChar)  and equals(Object anObject) as validation.
String getImportLine(Class<?> clazz) {
    String importLine = toSanitizedClassName(clazz.getName());
    String importStaticLine = importLine.replace('$', '.');
    if (importLine.equals(importStaticLine)) {
        return String.format("import %s;", importLine);
     }
    return String.format("import static %s;", importStaticLine);
}

This implementation parses the string two times with:

*

*importLine.replace('$', '.')

*importLine.equals(importStaticLine)

The second implementation uses indexOf(int ch) as validation and replace(char oldChar, char newChar) in the worst case.
String getImportLine(Class<?> clazz) {
    String importLine = toSanitizedClassName(clazz.getName());
    if (importLine.indexOf('$') == -1) {
        return String.format("import %s;", importLine);
    }
    importLine = importLine.replace('$', '.');
    return String.format("import static %s;", importLine);
}

The second implementation, in the worst case, parse the string two times  with:

*

*importLine.indexOf('$') == -1

*importLine.replace('$', '.')
Is there some difference in terms of performance between the use of equals vs indexOf as validation?

A: What you are asking are the difference in execution time between String.indexOf and String.equals. With Big-O notation these are the same, since both (worst case) will iterate through the entire String before returning.
In practice, it really depends on the input.
For instance:

*

*equals will return pretty much immediatly if the two strings compared are a different length

*equals will return sooner if the difference in the strings occur early ("abcdef".equals("aXcdef") is faster than "abcdef".equals("abcdeX"))

*indexOf('$') will be faster if $ occurs early in the string ("a$cdef".indexOf('$') is faster than "abcde$".indexOf('$'))

*indexOf will be slower if the input char is a special character

On modern computers this should not matter, since they are so fast that any difference will be unnoticable, unless the method is called hundreds of thousands of times (or with really large input strings). When optimizing code one should focus on saving seconds, not nanoseconds. With your current problem you should be a lot more worried about making your code readable and understandable to others than you should be worried about which uses the most CPU cycles..


text:
Q: paging without postback using javascript I am using Gridview. There are several pages. I want to go to the next page without post-back.
I have already tried by setting EnableSortingAndPagingCallbacks = "true" but then i found i will not work if there is any TemplateColumn. So how could i have a solution? Here are my sample code...can anyone help?
<AlternatingItemStyle CssClass="GridAlternateRowStyle"></AlternatingItemStyle>
              <ItemStyle CssClass="GridRowStyle"></ItemStyle>
              <HeaderStyle Font-Bold="True" CssClass="GridColumnHeaderStyle"></HeaderStyle>
              <FooterStyle HorizontalAlign="Right" VerticalAlign="Middle"></FooterStyle>
              <Columns>
                <asp:TemplateColumn>
                  <HeaderStyle Width="25px"></HeaderStyle>
                  <HeaderTemplate>
                    <asp:CheckBox ID="CheckAll" language="javascript" onclick="return CheckAll_onclick(this.checked)"
                      Runat="server" />
                  </HeaderTemplate>
                  <ItemTemplate>
                    <asp:CheckBox ID="DeleteThis" language="javascript" onclick="return DeleteThis_onclick(this.checked)"
                      runat="server" />
                  </ItemTemplate>
                </asp:TemplateColumn>
                <asp:TemplateColumn>
                  <HeaderStyle Width="100px"></HeaderStyle>
                  <HeaderTemplate>
                    Code
                  </HeaderTemplate>
                  <ItemTemplate>
                    <asp:LinkButton id=Code onclick=EditItem runat="server" Text='<%# DataBinder.Eval (Container.DataItem, "EmployeeCode") %>'>
                    </asp:LinkButton>
                  </ItemTemplate>
                </asp:TemplateColumn>
                <asp:BoundColumn DataField="EmployeeName" HeaderText="Name"></asp:BoundColumn>
              </Columns>
              <PagerStyle NextPageText="" PrevPageText="" Mode="NumericPages" CssClass="ControlLinkButtonStyle" Position="TopAndBottom"></PagerStyle>
            </asp:datagrid>

A: Did you try to use client side GridView funcitionality? Look at the code below
<dx:ASPxGridView ID="_gridView" runat="server" AutoGenerateColumns="False" Width="100%" KeyFieldName="id" DataSourceID="ProjectsCenterDataSource" ClientInstanceName="_gridView">
....
</dx:ASPxGridView>
<script type="text/javascript">
    $(function () {
        $("#button").click(function(){
          _gridView.NextPage(); // or _gridView.GotoPage(10)
        });
    });
</script>


text:
Q: Activity functions in Durable Function I'm trying to learn converting an Azure Function to Durable Function. In the Azure Function, I have the code to get users for all the required AAD groups. Here is my code:
        IGraphServiceClient graphServiceClient;
        GetUsersForEachGroup(IEnumerable<AzureADGroup> groups)
        {
            foreach (var group in groups)
            {
                    var users = await GetUsersInGroupc(group);
            }
        }

        GetUsersInGroup(Guid objectId)
        {
            var nonUserGraphObjects = new Dictionary<string, int>();
            IGroupTransitiveMembersCollectionWithReferencesPage members;
            members = await graphServiceClient.Groups[objectId.ToString()].TransitiveMembers.Request()
                            .WithMaxRetry(MaxRetries)
                            .Select("id")
                            .GetAsync();
                var toReturn = new List<User>(ToUsers(members.CurrentPage, nonUserGraphObjects));
                while (members.NextPageRequest != null)
                {
                    members = await members.NextPageRequest.WithMaxRetry(MaxRetries).GetAsync();
                    toReturn.AddRange(ToUsers(members.CurrentPage, nonUserGraphObjects));
                }
                return toReturn;
          }

          ToUsers(IEnumerable<DirectoryObject> fromGraph, Dictionary<string, int> nonUserGraphObjects)
          {
            foreach (var directoryObj in fromGraph)
            {
                switch (directoryObj)
                {
                    case User user:
                        yield return new AzureADUser { ObjectId = Guid.Parse(user.Id) };
                        break;
                    default:
                        if (nonUserGraphObjects.TryGetValue(directoryObj.ODataType, out int count))
                            nonUserGraphObjects[directoryObj.ODataType] = count + 1;
                        else
                            nonUserGraphObjects[directoryObj.ODataType] = 1;
                        break;
                }
            }
        }

I'm thinking of adding an 1) Activity function to find out all the groups, 2) SubOrchestrator function 3) Activity function to get all users for each group. Is there a way I could add more Activity functions for the code GetUsersInGroup() for a better performance? Please let me know. Thank you!
[FunctionName("GetUsersInGroups")]
public static async Task GetUSersInGroups(
    [OrchestrationTrigger] IDurableOrchestrationContext context)
{
    var groups = await context.CallActivityAsync<IEnumerable<AzureADGroup>>("GetGroups");
    var tasks = new List<Task>();
    foreach (string group in groups)
    {
        Task task = context.CallSubOrchestratorAsync("GetUsers", group);
        tasks.Add(task);
    }

    await Task.WhenAll(tasks);
}


text:
Q: git - cannot push to repository - bug with hashmap When I try to push to repository, I got this message
BUG: remote.c:236: hashmap_put overwrote entry after hashmap_get returned NULL

Any idea what is wrong? Google shows nothing...
When I try push to another repository on the same server, it is working correctly. The problem is only with one repo.
Local Git version: 2.36.0.windows.1
Server Git version: 2.19.2

A: Git has self-detected an internal error.  Report this to the Git mailing list (git@vger.kernel.org).  The output from git config --list --show-origin may also be useful to the Git maintainers, along with the output of git ls-remote on the remote in question (origin, probably).  (The bug itself is in your Windows Git; the server version of Git should be irrelevant, but it won't hurt to mention that too.)

A: Based on reporting problem to git team, the problem was caused by branch with an empty name "". After removing this form .git/config, pushing works again.
However, the problem is passed to git team and will probably be solved in future version.


text:
Q: Getting Image Dimensions From URL I am using the NextJS Image component to render images using a provided URL. I want it to display the images at their full native size. When using it to render local images, it works perfectly as such:
<Image src={news.image} alt={news.title} />

However, when I try to render an image from a URL, it asks for width and height props to be passed. One way to bypass this is to use the layout="fill" property, but this results in a badly scaled image. I also tried passing "100%" as properties but it renders the image as 100x100px.
Is there a way that I can essentially fetch the native size of the image from its URL and pass it to the next/Image component to render at its full size?


text:
Q: Count of selected rows is not updated correctly in a DT datatable I have a simple shiny app
#ui.r
navbarPage(
  "Application",
  tabPanel("General",
           sidebarLayout(

             sidebarPanel(
               uiOutput("tex2")

             ),
             mainPanel(
               DT::dataTableOutput("hot3")

             )
           )))
#server.r
library(shiny)
library(DT)
library(tidyverse)
server <- function(input, output,session) {
  output$tex2<-renderUI({
    numericInput("text2","Rows selected",
                 value = input$hot3_rows_selected,
                 min=0
    )
  })

  output$hot3 <-DT::renderDataTable(
      iris %>% rowid_to_column("Row") %>% mutate(Row = ""),
      rownames = FALSE,
      extensions = "Select",
      options = list(
        columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
        select = list(style = "multi", selector = "td:first-child")
      ))
}

I have a numericInput() which should normally display the count of rows selected in the datatable but as you will see it displays only the first row selected and not the count of them.

A: To show the count of rows selected you need the length of input$hot3_rows_selected (use length(input$hot3_rows_selected) instead).
library(shiny)
ui <- navbarPage(
    "Application",
    tabPanel("General",
        sidebarLayout(
            sidebarPanel(uiOutput("tex2")),
            mainPanel(DT::dataTableOutput("hot3"))
        )
    )
)
server <- function(input, output,session) {

    library(tidyverse)
    output$tex2 <- renderUI({
        numericInput("text2", "Rows selected",
                     value = length(input$hot3_rows_selected),
                     min = 0)
    })

    output$hot3 <- DT::renderDataTable(
        iris %>%
            rowid_to_column("Row") %>%
            mutate(Row = ""),
        rownames = FALSE,
        extensions = "Select",
        options = list(
            columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
            select = list(style = "multi", selector = "td:first-child")
        )
    )
}

shinyApp(ui, server)


text:
Q: Azure Document DB – JS file with server-side API I'm using Cosmos DB with SQL API. I keep definitions of stored procedures in my project in JS files and initialize them during startup if it's needed. I'm using WebStorm as JS code editor and it have really helpful feature: autocomplete. But to use is I need JS library file. Is it possible to download JS file used to generate this documentation:
https://azure.github.io/azure-cosmosdb-js-server/

A: The Cosmos DB JS server code is part of the page you linked.
You can find the page containing the DocDbWrapperScript.js here
If you just want the raw JS file then you can get that here


text:
Q: PromQl: alert on first value of a counter I have a prometheus counter (spring_batch_job_seconds_count{status=~'FAILED'}) that counts job failures.  I want to graph job failures over time and alert on job failures.  The increase function gives me what I want except for the first occurrence.  The counter is not published until a failure occurs, so there is no increase (or delta or rate) on the first failure event since there is no previous counter value of 0 to compare the first non-zero counter value to.  How can I create a graph that will show the first failure occurrence (as well as subsequent failure occurrences) and a corresponding alert that will trigger on the first failure occurrence (as well as future failure occurrences)?  I might be willing to settle for two alerts: one that triggers when the counter increments, and one that triggers on the first occurrence, but I would not want to have to manually shut off the alert that triggers on the first occurrence after it triggers for the first time.

A: I managed to do this with falco metrics.
I want to alert on any change, even the first time a metric appears.
(sum(falco_events{k8s_pod_name="runner"} or falco_events{} * 0) by (k8s_pod_name, rule) - sum(falco_events{k8s_pod_name="runner"} offset 5m or falco_events{} * 0) by (k8s_pod_name, rule))

Workaround from here: https://github.com/prometheus/prometheus/issues/1673


text:
Q: How to make ion-select popover render correctly after input focus changes from keyboard to non-keyboard input? (Ionic 3)
In my component HTML i have a select box (ion-select) that displays some options.
<ion-content padding>
  <form [formGroup]="p" (ngSubmit)="submit()">
    <ion-item>
      <ion-label floating>{{"somePage.bId"|translate}}</ion-label>
      <ion-input type="tel" formControlName="pId"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label floating>{{"somePage.defect"|translate}}</ion-label>
      <ion-select formControlName="error" interface="popover">
        <ion-option *ngFor="let option of options" [value]="option.error">{{option.description}}</ion-option>
      </ion-select>
    </ion-item>
    <ion-item>
      <ion-label floating>{{"message"|translate}}</ion-label>
      <ion-textarea
        rows="13"
        formControlName="message"
        autocorrect="on"
        autocomplete="on">
      </ion-textarea>
    </ion-item>
    <button *ngIf="!..." ion-button type="submit" [disabled]="...">{{"submit"|translate}}</button>
  </form>
</ion-content>

When the first thing a user selects is the select box, then it opens and is scrollable as one would expect.

But if one would select number input first, the keyboard opens. After entering the number and tapping the select box, it opens but can't be scrolled and is overflowing the screen.

Obviously, the popover is calculated bigger on the smaller screen, through to the keyboard overlay leading to a taller window height, which the following log shows (*Height* being the select box height, and window height is self-explanatory).

(The second line displays the buggy case)
I am using the current ionic-angular version 3.9.9.
Are there any workarounds/solutions for this, so the popover renders correctly?


text:
Q: Matplotlib make subplot axes same size - imshow and plot I'm trying to make a figure of some xyz data. I need to show different regions of the data using a colormap, as well as an integrated area in a plot alongside. Here's my example code:
import matplotlib.pyplot as plt
import numpy as np

#Generate some arbitrary xyz data
def gauss(x, y, mx, my, sx, sy):
    return np.exp(-(x-mx)**2/(2*sx**2))*np.exp(-(y-my)**2/(2*sy**2))

xmin, xmax, ymin, ymax = 0.97, 1.04, 2.60, 3.05
x, y = np.meshgrid(np.linspace(xmin, xmax, 1000), np.linspace(ymin, ymax, 1000))
data = gauss(x, y, 1, 3, 0.01, 0.01) + gauss(x, y, 1, 2.7, 0.01, 0.01)

#Plot the data
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.imshow(data, extent=[xmin, xmax, ymin, ymax], origin="lower")
ax2 = fig.add_subplot(122)
ax2.plot(np.sum(data, axis=1),y[:,0])
ax2.set_ylim(ax1.get_ylim())
ax2.set_yticklabels([])

plt.show()

This code produces a nice figure:
Fig. 1
Now I'd like to focus in on just the two regions with significant z-value. To do this, I split the two subplots into four subplots, with the top row focusing in on the top peak, and the bottom row focusing in on the bottom peak. Using the same data, here's the code:
#Plot the data
fig = plt.figure(figsize=(4,10))
ax1 = fig.add_subplot(221)
ax1.imshow(data, extent=[xmin, xmax, ymin, ymax], origin="lower")
ax1.set_ylim([2.60, 2.75])

ax2 = fig.add_subplot(222)
ax2.plot(np.sum(data, axis=1),y[:,0])
ax2.set_ylim(ax1.get_ylim())
ax2.set_yticklabels([])

ax3 = fig.add_subplot(223)
ax3.imshow(data, extent=[xmin, xmax, ymin, ymax], origin="lower")
ax3.set_ylim([2.95, 3.05])

ax2 = fig.add_subplot(224)
ax2.plot(np.sum(data, axis=1),y[:,0])
ax2.set_ylim(ax3.get_ylim())
ax2.set_yticklabels([])

The figure produced has axes which don't line up with one another:
Fig. 2
What I'd like to have is the two subplots on the left have x-axes which match, the two subplots on the right to have the same size x-axis, and in both rows I'd like to have the curves on the right to have the same y-axis size as its corresponding image to the left. I'd also like to keep the aspect ratio of the plots on the left equal, which rules out the possible solution discussed here.
I can resize the window to satisfy some of these conditions, but I can never get the y-axes of the plots on the right to stay the same size as the images at left. I've tried using GridSpec, subplot2grid, and generating the axes on the right manually using appropriate Bbox bounds taken from the image subplots on the left, but these methods all give me the same issue. I've also tried using the sharedx and sharedy options when creating axes, and while it seems to make the y-axes of the images on the left match the y-axes of the plots on the right, it does so by zooming in on the image, which is not what I want.
I made an example of what I want using Inkscape: Fig. 3.
EDIT:
It was suggested that I try to use set_aspect to adjust the aspect of the plots on the right so that the y-axis size is the same as what is on the left, but this doesn't work:
asp = np.diff(ax2.get_xlim())[0]/np.diff(ax2.get_ylim())[0]
ax2.set_aspect(asp)

While this does seem to prevent the subplot from being larger than the subplot on the left, it doesn't make the axes the same size. Again upon resizing the window I can now make the subplot on the top right the same size as the one in top left, but then the x-axes of the top left and bottom left don't match.


text:
Q: Best HDD Setup for HTPC I am configuring an HTPC that can support up to 4 internal hard drives, as well as RAID levels 0, 1, 5 and 10. My plan is to install Windows 7 Home Premium 64-bit.
I have been taught that its best to have a small, fast primary drive for the OS and then a larger secondary drive for data. Though I realize this may be different on an HTPC. I would like to have some redundancy in my data, and I was wondering what would be the best configuration of disks for me.

A: I agree with this advice, and it is entirely doable on an HTPC:

I have been taught that its best to have a small, fast primary drive for the OS and then a larger secondary drive for data.

The reason for this is that if the OS becomes corrupted and you need to reinstall, this setup allows reformatting/reinstalling the system drive with no need to touch the data partitions.
But I can't recommend RAID solutions.

*

*If you absolutely need the performance, go with hardware RAID-0, keep good backups, and be prepared to restore from backup at the first hardware failure.

*If you absolutely need the redundancy, a RAID-1 mirroring solution -- preferably software RAID -- is best.
Why?  Two words: hardware failure.  Hardware RAID is chipset dependent.  You cannot take a RAID set from one chipset and plug it into another and access your data.  Software RAID is slower, but doesn't depend on a RAID chipset.  In the event of a controller failure, you won't have to locate an identical controller chip to get a software RAID set up and running again.
Personally, I use standard partitions on bare drives -- no RAID, no LVM, no Dynamic Disk.  I have a spare drive in the server to backup the important stuff, and another offline that gets plugged in and updated once in a while.  That protects me from a drive failure.  If the motherboard or drive controller fails, these drives will work immediately on any other  hardware.  I don't need to find matching chipsets, I don't need to configure a new system to use another system's software RAID set or LVM, and a single drive failure has no effect on my ability to access other drives.
Remember, RAID is not a backup.  RAID is not a substitute for a backup.  RAID-0 is for performance, RAID-1 is for redundancy, RAID-5 is for a little of both.  There's another piece of advice that's worth keeping in mind:

There are only 2 kinds of people in the world: those who have experienced catastrophic data loss, and those who will experience catastrophic data loss.

A: Home premium does not allow RDP connections to it, so you might want to jump for a higher version of windows (like professional).
You could get an SSD for the C: partition of windows.  But you will be forking out 200-300 dollars for a decent one (~80-130GB).  IMO it is easier to have a large raid array for C: then to have to worry about where to put stuff (and the eventual hell of when C: becomes cramped with software and junk).
If your going to use raid then use a raid 1, 5 or 10 setup.  Raid 0 is begging for your data to go bye bye and raid 5 tends to suffer from slow writes (due to parity calculations).  With raid 1 and 10 you will loose half your disk space for redundancy, with raid 5 it is N-1 where N is the number of disks times the capacity per disk.

*

*Raid 1 stores an exact copy of the data on both disks

*Raid 0 stores a portion of the data on the disks (no redundancy)

*Raid 5 stores a portion of the data on the disks and uses one for parity (ie 1 bit goes to each drive then it stores if their sum is even or odd).

*Raid 10 is a mixture of 1 and 0.  With redundancy on the node (raid 1) and raid 0 spanning the nodes, you need to have multiples of 2 though.

A decent controller with hardware raid will run you upwards of 100-200 dollars.  You can use software raid, but it is a PITA in most cases.

A: I would only really consider a raid solution if I really wanted a large effective drive size perhaps for a large online media library. Although due to heat and noise considerations I would probably rather keep the library on a server far from my lounge room. For me a large single drive is the way to go.
With respect to a small boot partition and a large data drive scheme then there probably is little real advantage for a pure HTPC (recording TV and playing media files only) as the OS is going to remain relatively stable over a long period without software being installed and uninstalled all the time.
On the other hand if you are going to be using this for more general computing or playing games then a boot drive (or partition) wouldn't be a bad idea. Performance is usually not an issue on a HTPC so I would favor a boot partition rather than an extra drive but if you are a heavy gamer then a fast boot drive my be of benefit.


text:
Q: could not load assembly '{library project}'. Ensure it is referenced by the startup project '{winforms project}' using Scaffold-DbContext I have a class library project that is referenced by a Winforms project in .NET Core 6.
In package manager, I run this when selected the class library project.
Scaffold-DbContext "Data Source=localhost;Initial Catalog=ControlParking;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB -Force
After that, this error is shown:
PM> Scaffold-DbContext "Data Source=localhost;Initial Catalog=ControlParking;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB -Force
Build started...
Build succeeded.
Could not load assembly 'Manager'. Ensure it is referenced by the startup project 'ParkControlWin'.

Where Manager is the class library project and ParkControlWin is the winforms project. ParkControlWin is actually referencing Manager project.
When I build the whole solution, no errors are shown, just some warnings, for example, variables are never used, and so on.
What may be happening here?


text:
Q: Is there a better way to do a PopToRoot async without leaking GRefs? According to this bug: bugzilla.xamarin.com/show_bug.cgi?id=52597 the PopToRoot of the Navigation object still leak GRefs (in fact JNI Global References)
In one application we use Listview really intensively and to avoid crash I had to implement a workaround using two methods :
/// <summary>
/// Workaround to minimize the quantity of GREFs leaked by Xamarin.Forms JMA 17.02.2017
/// </summary>
/// <param name="animate">if set to <c>true</c> [animate].</param>
public async Task PopToRoot(bool animate)
{
    var nav = Application.Current.MainPage.Navigation;

    if(animate == false) //simulate animate = false
        for (int i = 1; i < nav.NavigationStack.Count; i++)
            if(nav.NavigationStack[i] is BaseView)
            {
                //hide the animation
                (nav.NavigationStack[i] as BaseView).IsVisible = false;
                //hide the toolbar title change
                (nav.NavigationStack[i] as BaseView).Title = (nav.NavigationStack[nav.NavigationStack.Count - 1] as BaseView).Title;
            }

    await _PopToRootInner(true);
}

/// <summary>
/// Workaround to minimize the quantity of GREFs leaked by Xamarin.Forms JMA 17.02.2017
/// </summary>
/// <param name="animate">if set to <c>true</c> [animate].</param>
private async Task _PopToRootInner(bool animate)
{
    var nav = Application.Current.MainPage.Navigation;

    await PopAsync(animate);

    if (nav.NavigationStack.Count > 1 && nav.NavigationStack[nav.NavigationStack.Count - 1] is BaseView)
        await (nav.NavigationStack[nav.NavigationStack.Count - 1] as BaseView)._PopToRootInner(animate);

}

My question is : Do you know any better method to do a PopToRoot without animation and without leaking GRefs ?
And Also, if you know how to correct the bug, I am of course interested !


text:
Q: Watts - I think I'm getting free energy from a circuit? Imagine I have a 10V battery with a capacity of 1Ahrs connected to a 100 Ohm resistor.
I'll get 0.1A (V/R) at a power of 1W (current x voltage) for a total of 10hrs. As a watt is defined as J/s my battery produces 3,600J (1x60x60) in total.
Now, imagine I get a second, identical battery and connect it in series to the first one. I will effectively have a battery of 20V with a capacity of 2Ahrs, all connected to the same 100 Ohm resistor.
I'll get 0.2A at a power of 4W (current x voltage) for a total of 10hrs. This will generate 14,400J (4x60x60).
So, from doubling my energy source I have quadrupled the energy output!
I've obviously made an error somewhere either in my calculations or conceptual understanding, and I would be most grateful to anyone who could set me right.
Thanks!

A:
I'll get 0.2A at a power of 4W (current x voltage) for a total of 10hrs.

Since neither battery can supply 0.2A for 10 hours, and both would need to for this to be true, this is false.
The same current flows through both batteries and that's the same as the current through the load because this is a pure series circuit. So in order to supply 0.2A to the load, each battery needs to be able to supply 0.2A.

Now, imagine I get a second, identical battery and connect it in series to the first one. I will effectively have a battery of 20V with a capacity of 2Ahrs, all connected to the same 100 Ohm resistor.

You don't show how you got 2Ahrs, but that's not correct. Again, both batteries have to supply the full current. Since each battery can supply 1Ah, the two together in series can supply 1Ah because the currents don't add up in a series connection.

A: Congratulations for having the wit to know something was wrong!

simulate this circuit – Schematic created using CircuitLab
Figure 1. Parallel and series arrangements of batteries will have the same VAh rating.

I will effectively have a battery of 20 V with a capacity of 2 Ah.

That's the error.

*

*In parallel they can supply 1 A each for one hour. This is very easy to visualise if you run one for an hour and then replace with the other.

*In series they both run simultaneously and the same current runs through both of them. They will both discharge at the same rate.

This is one good reason to use Wh (watt-hours) for battery comparison. It makes it much easier to compare battery energy storage when the batteries have different voltages.

In your example you have \$ Capacity = V \cdot Ah = 10 \cdot 1 = 10~Wh \$. With two batteries we have \$ 20~Wh \$ capacity whether in series or parallel.
Our load power is given by \$ P = \frac {V^2}{R} \$.

*

*In parallel \$ P = \frac {10^2}{100} = 1~W \$ as you calculated. \$ Runtime = \frac {Wh}{W} =  \frac {20}{1} = 20~h \$.

*In series  \$ P = \frac {20^2}{100} = 4~W \$ as you calculated. \$ Runtime = \frac {Wh}{W} =  \frac {20}{4} = 5~h \$.

simulate this circuit
Figure 2. An alternative view may help. (a) Is your original series circuit. (b) is a direct equivalent. Because the mid-point of the 50 Ω resistors is at the same potential as the mid-point of the battery stack it makes no difference if we connect them together as shown in (c). Now we have two 1 Ah circuits each feeding into a 50 Ω load.

A: When you double the batteries, you double the current, and consequently quadruple the power in the resistor. You got all that correct.
However you seem to have missed that by doubling the current, you also halve the runtime of your batteries. So it won't run for 10 hours, but 5. So the total energy is only doubled, not quadrupled.
When you connect batteries in series like this, the charge capacity of the resulting composite battery (typically in mAh) does not change. It doesn't change because each unit of charged moved through the battery must also move through each cell. So adding more cells (or batteries of cells) in series does not increase the total charge that can be moved by the battery in its lifetime, but it does increase the voltage over which that charge can move, which accounts for the extra chemical energy you've added.


text:
Q: ORA-1033: ORACLE initialization or shutdown in progress I am stuck with a little Oracle problem. My PC was shut down improperly after my graphics card freaked out, which caused Oracle 11g Express to not properly close down. This means that I get the above error when I try to connect. My PC has been on for 3 hours, and I still get the error, so it is safe to assume that there's something wrong.
The usual way of remedying the problem is to use the following sequence of commands from the command line:
sqlplus /nolog
SQL> connect / as sysdba
SQL> shutdown abort
SQL> startup nomount
SQL> alter database mount;
SQL> alter database open;

However, when I give the shutdown command, I get the error

ORA-12560: TNS:protocol adapter error

So now, I can't mount my db. ANy help would be appreciated.

A: This worked for me:

*

*Open the Start menu --> All Programs

*Open folder "Oracle Database 11g Express Edition"

*Choose "Start Database"

*Wait until you get "C:\Windows\system32"

*Open "Run SQL Command Line" and connect to your database

A: This is probably not necessary or even possible in all cases, but I ended up uninstalling and reinstalling Oracle because I get paid per hour and I'd rather spend that time producing code than wrestling with Oracle.

A: My guess would be that your listener service is not running.
You can check this by openening the services screen by (in Win7) searching for "services". In the list you should find an Oracle Listener service with status Started.


text:
Q: How could I use "tr" to translate every byte? My goal is to have every byte from an input file xor with 42 using tr.
But I was stuck at this point:
tr '\0-\377' '?'

Anyone can help? Thanks a lot..
Some restrictions:
translation has to be done by tr.
we are allowed to use bash script, but it shouldn't use any temporary files. (only pipeline in other words)

A: This isn't possible with tr alone since it - as the name says - simply translates from one codeset to another. Math calculations or logical operations are not supported.
Btw, if you want to address the whole ascii range using numeric values, you are bound to octal numbers. The range would be \0-\377 in that case. But anyway, calculating the xor value is not possible.
What you can do is the prepare a table with xor^42'ed ascii values and use as SET2. I'm using python to create that list:
xor.py
v = []
for i in range(0,255):
    v.append("\\" + oct(i^42))
print("".join(v))

Or simply:
print("".join(["\\" + oct(i^42) for i in range(0,255)]))

Then use that to create SET2 for tr:
tr '\0-\0377' "$(python xor.py)" < input.file

Note: When python is already required, why not using python for the whole solution?
Edited by Mark Setchell
As Peter pointed out this list can of course getting generated in advance and then getting passed as a string for SET2. This would not require a runtime python call. Like this:
tr '\0-\0377' '\052\053\050\051\056\057\054\055\042\043\040\041\046\047\044\045\072\073\070\071\076\077\074\075\062\063\060\061\066\067\064\065\012\013\010\011\016\017\014\015\02\03\0\01\06\07\04\05\032\033\030\031\036\037\034\035\022\023\020\021\026\027\024\025\0152\0153\0150\0151\0156\0157\0154\0155\0142\0143\0140\0141\0146\0147\0144\0145\0172\0173\0170\0171\0176\0177\0174\0175\0162\0163\0160\0161\0166\0167\0164\0165\0112\0113\0110\0111\0116\0117\0114\0115\0102\0103\0100\0101\0106\0107\0104\0105\0132\0133\0130\0131\0136\0137\0134\0135\0122\0123\0120\0121\0126\0127\0124\0125\0252\0253\0250\0251\0256\0257\0254\0255\0242\0243\0240\0241\0246\0247\0244\0245\0272\0273\0270\0271\0276\0277\0274\0275\0262\0263\0260\0261\0266\0267\0264\0265\0212\0213\0210\0211\0216\0217\0214\0215\0202\0203\0200\0201\0206\0207\0204\0205\0232\0233\0230\0231\0236\0237\0234\0235\0222\0223\0220\0221\0226\0227\0224\0225\0352\0353\0350\0351\0356\0357\0354\0355\0342\0343\0340\0341\0346\0347\0344\0345\0372\0373\0370\0371\0376\0377\0374\0375\0362\0363\0360\0361\0366\0367\0364\0365\0312\0313\0310\0311\0316\0317\0314\0315\0302\0303\0300\0301\0306\0307\0304\0305\0332\0333\0330\0331\0336\0337\0334\0335\0322\0323\0320\0321\0326\0327\0324' < inputFile > outputFile


text:
Q: URLTask does not send any UrlRequest I am new to swift and doing a project in swift 4.0 to acquire data form Fitbit API and got a Strange problem, my url task does not send any urlrequest any more but skip all the code until task.resume, and do not give anything back. Can anyone helps me plz. The code is shown below
import UIKit
class FitbitAPI{
static let sharedInstance : FitbitAPI = FitbitAPI()

var parsedJson : [Any]? = nil

func authorize(with token: String){
    let accessToken = token
    let baseURL = URL(string: "https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json")
    let request = NSMutableURLRequest(url:baseURL!)
    let bodydata = "access_token=\(String(describing: accessToken))"
    request.httpMethod = "GET"
    request.setValue("Bearer \(String(describing: accessToken))", forHTTPHeaderField: "Authorization")
    request.httpBody = bodydata.data(using: String.Encoding.utf8)
    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {[weak self] (data, response, error) in
        if let error = error {
            print(error)
        }
        if let data = data, error == nil{
            do {

                self?.parsedJson = (try JSONSerialization.jsonObject(with: data, options: []) as? [Any] )
                print(String(describing: self?.parsedJson))

            }catch _{
                print("Received not-well-formatted JSON")
            }

        }
        if let response = response {
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")

        }

    })
    task.resume()
 }
}

A: As @Larme implied in his comment, all of that code between the let task = line and the task.resume() line is a callback. Meaning it won't get called until the task completes. Put breakpoints inside of that callback (like on your if let error = error line), and see if they get hit.
ALso, your URL task is a local variable in this method. That means it's entirely possible that its getting released from memory right at the end of this method, before the callback can even be executed. You'll need a reference to the task outside of the method if you want to guarantee that it stays alive in memory long enough to hit the completion callback.


text:
Q: Executing a cmd.exe command from a python script I have a python script callee.py which is in a certain directory and that directory is part of the Windows PATH environment variable. In the Windows command prompt cmd.exe I can simply execute it as
> callee.py arg1 arg2

Now, I have another python script caller.py in another directory. To execute the first script I would like to use the subprocess module like
subprocess.Popen("callee.py arg1 arg2")

but this does not work, because it does not get that it should actually call python.exe callee.py .... Furthermore,
subprocess.Popen("python.exe callee.py arg1 arg2")

does not work, because it does not find callee.py.
Is there something like subprocess.Popen which accepts the very same kind of commands that the Windows command prompt cmd.exe does?

A: Is callee.py executable? Or, why don't you give the full path?
subprocess.Popen("python.exe c:\full_path\to\callee.py arg1 arg2")

Too late, don't consider this answer.

A: It works like this
subprocess.Popen("cmd.exe /c callee.py arg1 arg2")


text:
Q: View has _Layout but dropdown menu isn't working I have a view that is using the Shared _Layout which has all of the stylesheets and javascript files referenced.
On my navbar I have a dropdown-menu:
Navigate

But when I click on the dropdown, nothing happens.. the menu isn't displayed or anything.  When I click on the dropdown and move the cursor away the focus stays on the dropdown menu but again, nothing shows..
It looks like this:

This dropdown works on every other View except this one.
I have checked the View Source and all of the stylesheets & Javascript files from the _Layout are there.
This view gets created from an ajax call on another view:

Any help is appreciated.

A: After your Ajax call the JS is not listening your new content, that why it's not working. You should "reload" your function after $("body").html(data); you can put $('.dropdown-toggle').dropdown(); to make your dropdown menu working.


text:
Q: Best hyperparameter is not consistent among different seeds I do hyper-parameter tuning on my network and it outperforms the simple classifier. The difference in classification is considerable after hyper-parameter tuning. But, the problem is that an optimal hyper-parameter performs poorly in a different seed. In other words, I can not find an optimal hyper-parameter for all seeds. Is there any way I can do hyper-parameter tuning in a better way to find good hyper-parameters for all seeds?  Currently, I am using scikit-learn optimization package (skopt).

A:
I can not find an optimal hyper-parameter for all seeds

That's the stochastic nature of machine learning. We don't have all the data, so any inference/training is vulnerable to noise. The model complexity, dataset size, your search, properties of the data all can affect this. Each seed is a separate snapshot that the real world represents. It's not expected to come up with the same set of optimal hyper-parameters for each seed. The most sensible way is the do multiple random experiments and use commonly selected hyper-parameters as your best and report accordingly; though not every research paper does that.


text:
Q: How to avoid serializing the float array properties I have used a float array property for CustomDashPattern and used it like below code,
float[] customDashPattern = { 5, 3, 5, 3 };

public float[] CustomDashPattern
{
   get
   {
       return customDashPattern;
   }
   set
   {
       customDashPattern = value;
   }
}

public bool ShouldSerializeCustomDashPattern()
{
    return customDashPattern != new float[] { 5, 3, 5, 3 };
}

but still the property value is serialized in designer even when its default value is not changed.
The logic for should serialize returns true even when pattern is default value.
Could any one please let me know, what i have done wrong ?

A: For arrays the != operator compares object references. To compare arrays contents use Enumerable.SequenceEqual():
public bool ShouldSerializeCustomDashPattern()
{
    return !Enumerable.SequenceEqual(customDashPattern, new float[] { 5, 3, 5, 3 })
}


text:
Q: jstring base64 to string conversion I am working on cocos2dx project, in a JNI call, method returns a java string which contains base64 encoded string, but as soon I try to get that from jstring to const char in C++ side it gives error, can you help me out here ?
  string getBase64EncodingJNI(std::string pData) {
  JniMethodInfo methodInfo;
            if (JniHelper::getStaticMethodInfo(methodInfo, "com/abc/something/modules/myHelper", "getBase64Encoding", "(Ljava/lang/String;)Ljava/lang/String;")) {

            jstring jData;
            if (!pData.c_str())
                jData = methodInfo.env->NewStringUTF("");
            else
                jData = methodInfo.env->NewStringUTF(pData.c_str());

            jstring output =  (jstring) methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID,jData);
            const char *strReturn = methodInfo.env->GetStringUTFChars(output, 0);
            string outputData = strReturn;

            methodInfo.env->DeleteLocalRef(methodInfo.classID);
            methodInfo.env->DeleteLocalRef(jData);
            methodInfo.env->ReleaseStringUTFChars(output, strReturn);
            return outputData;
    }
return "";

}
this is the methods being called
public static String getBase64Encoding(String pdata) {
    String encodedStr = Base64.encodeToString (pdata.getBytes(), Base64.DEFAULT);
    return encodedStr;
}

I get error on line GetStringUTFChars I want to ready that encoded jstring and pass it to other function. Error is
JNI DETECTED ERROR IN APPLICATION: JNI GetStringUTFChars called with pending exception java.lang.IllegalArgumentException: bad base-64


text:
Q: Determining T38 packet using either C or C++ I am working on analyzing a packet using C/C++.
At present I am stuck at one place. I researched a lot but was not able to find an appropriate solution. I am still searching but thought if anyone could help me out over here. How can I uniquely determine a T38 packet?
Is there a specific protocol value or specific hex value that represents a T38 packet?
Awaiting a positive response.
Thanking you in advance.


text:
Q: Doctrine saves entities twice Iam using Symfony(4.3) and Doctrine. When I want to get a user like this in the constructor of the script:
$userRepo = $this->em->getRepository(User::class);
    $this->systemUser = $userRepo->findOneBy([
        "firstName" => "system",
        "lastName" => "system",
    ]);

And save the reference to this user for example at a createdBy-field like this:
$newUser->setName("test");
$newUser->setCreatedBy($this->systemUser);
$this->entityManager->persist($newUser);
$this->entityManager->flush();

The systemUser is persisted to the database after every flush().
I already tried to get only the reference with
$this->systemUser = $this->entityManager->getReference(User::class, $this->systemUser->getId());

But this doesn't work either.
Edit:
The setCreatedBy-Method:
public function setCreatedBy(User $user): void {
    $this->createdBy = $user;
}

The 'createdBy'-Field:
/**
* @var User
* @ORM\ManyToOne(targetEntity="App\Entity\User", cascade={"persist"})
* @ORM\JoinColumn(nullable=true)
*/
protected $createdBy;

A: You have configured the cascade={"persist"} option for the relation which means Doctrine will save "new" entities found through the relation.
As your question suggests the createdBy field can only contain a relationship to already existing users. This means cascade is definitely not necessary here. It's also the reason why existing entities are persisted again in your case.
Remove the cascade option from the mapping-configuration for the property to resolve your issue.
Clear your cache afterwards.

A: To answer my own question:
I forgot to mention that I insert ~ 70.000 items in a loop and use clear() every 100 rows. The problem is the use of the entity manager's clear()-method. it detaches all doctrine-managed entites so doctrine thinks that these entities are new and saves them to the db. So I have to do it like this:
$newUser->setCreatedBy($this->em->getReference(User::class, $this->systemUser->getId()));


text:
Q: XLForm Cell numberOfLines Any pros out there using XLForm and have any idea on how to configure the cell such that the textLabel.numberOfLines can be changed to 2? I have a very long string that cannot fit in 1 line.
Any suggestions or thoughts is really appreciated! Thank you very much in advance!!! =D

A: Seems like this did the trick:
[self.row.cellConfigAtConfigure setObject:@(3) forKey:@"textLabel.numberOfLines"];

A: This did the trick for me:
form +++= TextRow() {
            $0.cell.textLabel?.numberOfLines = 0
            $0.title = "Some long string that doesn't fit iPhone 5 screen width"
            $0.placeholder = "Provide your answer"
        }


text:
Q: if-up.d launches two instances of a single script Case:
On our Ubuntu Xenial(16.04) station I host a bot written in Python that connects to our IRC server that's set to launch in /etc/network/if-up.d/
Our bot was connecting twice though the script is set to only run one instance and if its username is taken it must close the current connection and reconnect under the next username.
Troubleshooting:
I used ps aux | grep bot_name.py$ to determine the issue was not at the script level, but for some reason two instances of the script were being run when Ubuntu connected to the internet.
I've created a workaround on the script level that checks how many instances of the script are running locally and if it's any number besides one, it will close the script.
Question:
What would be some reasons if-up.d/might launch two instances of a single script stored in its directory?
if-up.d/Script:
The script in if-up.d/ is a sh script that wraps the call to python so it waits past the timeout period for irc then connects:
sleep 269
sh -c "python /dir/to/bot.py >> /dir/to/log" & disown

Additional Sources:
So far, I've seen the issue mirrored here in a different context where someone used a python script to send emails and the recipients received multiple emails due to multiple instances of their script launching.
I was also able to find this question for 16.04 on Server Fault where someone experienced a similar issue and the answer listed suggested it might be running twice because there's one instance launched for IPv4 and IPv6, though I'm not sure if this is actually the root cause or how to specify you'd only want to use IPv4 and forego the IPv6 call if that was the case.
Between our 3 cases, Ubuntu 16.04 seems to be the common thread which makes me wonder if this is a bug.

A: Looking more into 16.04 if-up.d/, I found a similar question for someone running Debian 7.3 and found the answer. It is not a bug, and the issue I experienced is explained here in @Søren Løvborg's answer:

In general, ifup / ifdown does not guarantee that your script only runs once. Thus your script has to be idempotent; that is, contain its own logic not to establish a tunnel that already exists. The best way, of course, is to start the script by actually checking if the tunnel is already there:

# Exit if network device "tun0" exists.
ip link show dev tun0 >/dev/null 2>&1 && exit 0

Additionally, the scripts in if-up.d etc. run for every interface that is brought up. As Jeff correctly observes, the if-*.d scripts receive no arguments specifying e.g. which interface is coming up.

  Instead, per the interfaces(5) man page:

   There  exists  for  each  of  the  above  mentioned options a directory
   /etc/network/if-<option>.d/ [...]

   All of these commands have access to the  following  environment  vari‐
   ables.

   IFACE  physical name of the interface being processed

   LOGICAL
          logical name of the interface being processed

  [... and more ...]

The solution is to start the script with a check for the correct IFACE value, e.g.:

# Exit if we're not starting "eth0".
[ "$IFACE" = 'eth0' ] || exit 0

Otherwise, the script will run for every network device, including lo, at which point it may be too early to establish a tunnel.

That said, my issue was it was executing the script for the lo interface in addition to my eth0 connection. I took one of the steps which was to program your script with the logic to not run more than once, but to only run it once without adjusting the code just specify the interface to be used
before execution.
If I wanted to go back and solve this on the sh level, I'd simply need to update my script with this line since the interface I want to use is my Ethernet connection
[ "$IFACE" = 'eth0' ] || exit 0
sleep 269
sh -c "python /dir/to/bot.py >> /dir/to/log" & disown

A: On top checking for the interface in $IFACE, you may also want to check for the address family in $ADDRFAM. It is "inet" for IPv4, and "inet6" for IPv6.
Scripts in /etc/network/if-*.d are not only run for each interface, but also for each address family if configured (IPv4 and IPv6).
For example, if you only need your script to run for a specific interface and only for it's IPv4 address, you could start with something like this:
[ "$IFACE"   = "eth0" ] || exit 0  # we only want interface "eth0"
[ "$ADDRFAM" = "inet" ] || exit 0  # we only want IPv4 (not "inet6" for IPv6)


text:
Q: Bucket Sort with a custom data structure My program is tasked with sorting points on an x-y plane, given by the user, according to their distance from the origin using bucket sort. In the instance of having two points with the same distance, the point with the smallest x-coordinate would be selected as the first point. If both the distance and the x-coordinate are the same, the element with the smallest y-coordinate will come first. The output is the points themselves, not their distances. The most logical way I've found to do it so far is to create a custom data structure that houses both the x coordinate, y-coordinate, and its distance in one element. The problem I have at the moment is my current algorithm for standard vectors of doubles, and I have no idea how to convert the sort to fit my needs. Any ideas or suggestions would be helpful.
Here is the layout of the structure:
struct point {
double  xc;
double  yc;
double  dist;  };

The current bucket sort, which works fine with vectors of doubles.
void bucketSort(vector<double> &arr) {
    int n = B.size();
    vector<point> b[n];

    for (int i=0; i<n; i++)
    {
       int bi = n*arr[i];
       b[bi].push_back(arr[i]);
    }

    for (int i=0; i<n; i++)
       sort(b[i].begin(), b[i].end());

    int index = 0;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < b[i].size(); j++){
            arr[index++] = b[i][j]; }
        }
    }

The entirety of the code, as of now.
using namespace std;

struct point {
    double  xc;
    double  yc;
    double  dist;
};

vector<double> A;
vector<double> B;

double findDistance(double x = 0, double y = 0) {
    double x2 = pow(x, 2);
    double y2 = pow(y, 2);
    double z = x2 + y2;
    double final = sqrt(z);
    return final;
}

void bucketSort(vector<double> &arr)
{
    int n = B.size();
    vector<point> b[n];

    for (int i=0; i<n; i++)
    {
       int bi = n*arr[i];
       b[bi].push_back(arr[i]);
    }

    for (int i=0; i<n; i++)
        sort(b[i].begin(), b[i].end());

    int index = 0;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < b[i].size(); j++){
            arr[index++] = b[i][j]; }
        }
    }

int main(){
    double number; int t = 0;
    while (cin >> number){
        A.push_back(number);    }
    struct point    C[A.size()];
    while (t < A.size()){
        C[t / 2].xc = A[t]; C[t / 2].yc = A[t + 1];
        C[t / 2].dist = (findDistance(A[t], A[t + 1])); t += 2; }
    cout << setprecision(6); cout << fixed; ;
    bucketSort(C);
    cout << showpos; cout << fixed;
    int x = 0;
    while (x < (A.size() / 2)){
        cout << C[x].xc << " " << C[x].yc << endl;
        x++;
    }
}

A vector of doubles B is here because initially, I was trying to get it done with multiple vectors of doubles.
Here is a sample of the input:
0.2 0.38
0.6516 -0.1
-0.3 0.41
-0.38 0.2

Sample output:
-0.380000 +0.200000
+0.200000 +0.380000
-0.300000 +0.410000
+0.651600 -0.100000

I realize that point could have a lot more functions added to it to make it more usable in general, but I'm aiming for just enough to get the current job. Any suggestions or help would be greatly appreciated. Please and thank you.

A: I would suggest one of there 2 options -

*

*make point a class, not an struct, and overload the < operator, thus making the sort work well.

2.use the sort by function instead of the normal sort:
Firstly, add a compare function:
bool comparePoint(point* a, point* b) {
  return true if a < b;
}

the function above would compare the 2 points, according to any rules you like, depends on your code.
and instead of the sort use:
std::sort(b[i].begin(), b[i].end(),comparePoint);

that should work for you.


text:
Q: Optimizing a program C++ I have to create a program, which counts bursted baloons, like from ZUMA. If I have a line with 3 or more  baloons with the same color this sequence will burst. So in input, I have number of ballons  (3 <= N <= 10^5) , and line with numbers (line with baloons color  (1 <= сi <= 100) ), with 1 sequence for sure. I have to output number of bursted baloons. I have a programm, but it is working longer than 4000msv sometimes. How can I make it working faster?
  #include <iostream>
#include <string>
#include <vector>
using namespace std;

int Fmax(int n, const string& f){
int  max;
vector<int> k(n);

int i, j, p = 0;
for (i = 0; i <= n; i++)
{
    k[i] = 0;
}

for (i = 0; i <= n; i++)
{
    for (j = i; j <= n; j++)
    {

        if (f[i] == f[j])
        {
            k[p]++;

        }
        else break;
    }
    p++;
}

max = k[0];
for (i = 0; i <= p; i++){ if (max <= k[i]){ max = k[i]; } }
return max;
}
string pog(int n){
int d;
string doa;
for (int i = 1; i <= n; i++){
    cin >> d;
    doa += (char)d;
}

return doa;
}
void main(){
int i, sc = 1, bf = 1;
string f;
int len;
cin >> i;
f = pog(i);
len = i;

while (Fmax(f.length(), f) >= 3){

    for (int c = 1; c <= f.length(); c++){

        if (f[c] == f[c - 1]){
            if (sc == 1){ bf = c - 1; }
            sc++;
        }
        else{
            if (sc >= 3){ f.erase(bf, sc);  sc = 1; break; }
            sc = 1;
        }

    }
}
cout << len - f.length() << endl;

}

Any help is warmly welcome.

A: You are leaking memory. Use vectors to avoid that.
Why do you need to create array? Why not use the string directly?
Pass strings which aren't modified by const reference to avoid copies.

A: Use constant variables for the lengths:
const unsigned int f_length = f.length();
while (Fmax(f_length, f) >= 3){

  for (int c = 1; c <= f_length ; c++){

This helps the compiler reduce the number of calls to the length method.


text:
Q: pdf file size is largely increased when copied using itext java library I am trying to copy existing pdf file into some new file using itextpdf library in Java. I am using version 5.5.10 of itextpdf. I am facing different issues with both ways : PDFStamper and PdfCopy. When I use PDFStamper class, I observe that new file size is increased by large margin, although nothing new items were added. Here is code piece :
    String currFile="C:\misc\pdffiles\AcroJS.pdf" ;
    String dest = "C:\misc\pdffiles\AcroJS_copy.pdf" ;
    PdfReader reader = new PdfReader(currFile) ;
    PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(dest)) ;
    stamper.close() ;
    reader.close() ;

Some observations are :  7 MB(original) to 13 MB (Approx, new file)  , 116 KB > 119 KB (Approx)
I was expecting approximate same file size when just copying existing pdf file. I am not able to figure out why size is increasing that much.
I have tried PdfCopy class as well. I Followed 2 approaches with PdfCopy:

*

*Copy page by page.

*Call setMergeFields() on pdfcopy object then call pdfcopy.addDocument(reader) ;

But problem in both approaches is that it is throwing away some non-content metadata from pdf file and hence new pdf is breaking when opened by Adobe reader. For example my pdf contains dictionary object PdfName.S . In this case newly created pdf file is just 2KB (original was 1.6 MB) , it clearly means nothing is copied into document and it is broken.
My original requirement is very simple : copy existing pdf to new pdf file, without increase in size, without throwing away necessary items. Obiviously It is not like, copy, paste and then rename. Because in next step, I have some processings to do with pdf content. Any help will be much appreciated.
OS : Windows 10 Pro
Java : 1.8.101
itext : 5.5.10
thanks

A: Use of PdfStamper
Your code
Your code
PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(dest)) ;
stamper.close() ;

essentially tells iText to copy the original PDF throwing away unused object and using iText's default compression settings.
iText's default compression settings include not using compressed cross reference and object streams (introduced in PDF 1.5) but the older technique of cross reference tables and individually compressed objects.
The sample file, on the other hand does use these techniques. Thus, it is much better compressed.
Code with full compression
You can tell iText to use these improved compression techniques, too, like this:
PdfReader reader = new PdfReader(resourceStream);
PdfStamper stamper = new PdfStamper(reader, outputStream);
stamper.setFullCompression();

stamper.close();

(Stamping.java test method testStampAcroJSCompressed)
This results in a file less than 4 MB in size.
Code with append mode
If you want to remain faithful to the original way objects were stored, you can instead use the append mode which identically copies the original file and adds changes in the form of a so called incremental update, like this:
PdfReader reader = new PdfReader(resourceStream);
PdfStamper stamper = new PdfStamper(reader, outputStream, '\0', true);

stamper.close();

(Stamping.java test method testStampAcroJSAppended)
This results in a file slightly larger than the original file.
Use of PdfCopy
You observed that PdfCopy

is throwing away some non-content metadata

Of course it does. PdfCopy is designed to copy pages from one PDF to another, keeping content and annotations as they were but ignoring other page-level and all document-level information.


text:
Q: Using fastai image augmentation reduced my accuracy I am working on a classifier using the Food-101 dataset. I am trying to react a SOTA score of >=90% using ResNet50. Initially, I was sitting at 75% accuracy. When I included label smoothing, I jumped to a sweet 81% but now when I use fastai's get_transforms, I dropped to 79%. I also noticed that even though I'm using image augmentation, there wasn't an increase in my data's dimensions when I was running the epoch.
Currently, the tfms variable is my augmentation:
np.random.seed(42)

path = '/content/food-101/images/train'
file_parse = r'/([^/]+)_\d+\.(png|jpg|jpeg)$'
tfms = get_transforms(do_flip=True,flip_vert=True, max_rotate=10.0, max_zoom=1.1, max_lighting=0.2, max_warp=0.2, p_affine=0.75, p_lighting=0.75)

data = ImageList.from_folder(path).split_by_rand_pct(valid_pct=0.2).label_from_re(pat=file_parse).transform(tfms, size=224).databunch()

top_1 = partial(top_k_accuracy, k=1)
learn = cnn_learner(data, models.resnet50, metrics=[accuracy, top_1], loss_func = LabelSmoothingCrossEntropy(), callback_fns=ShowGraph)

learn.lr_find()
learn.recorder.plot(suggestion=True)

My learning rate also slightly increased from 1.02e-06 to 1.023e-06 when I applied get_transforms() to my model.
I'm running another 5 epochs. The accuracy is low due to label smoothing. This isn't an issue:
learn.fit_one_cycle(5, max_lr=slice(1.023e-06/5, 1.023e-06/15))
learn.save('stage-2')

epoch   train_loss  valid_loss  accuracy    top_k_accuracy  time
0       6.549849    5.393574    0.009835    0.009835        18:39
1       6.520850    5.373156    0.009835    0.009835        17:57
2       6.468420    5.362789    0.009901    0.009901        17:49
3       6.461528    5.363743    0.009769    0.009769        17:51
4       6.473554    5.364657    0.009901    0.009901        18:05

Now I'm pulling out another learning rate. It jumped to 1.03e-06.
learn.unfreeze()
learn.lr_find()
learn.recorder.plot(suggestion=True)

Running another 5 epochs using the new LR and saving it. In this round, the label smoothing does not seem to have the same effect as it did on the earlier run. The model is now showing better accuracy than the earlier 5 epochs:
learn.fit_one_cycle(5, max_lr=slice(1e-03/5, 1e-03/15))
learn.save('stage-3')

epoch   train_loss  valid_loss  accuracy    top_k_accuracy  time
0       3.476312    2.645357    0.491683    0.491683        18:11
1       2.781384    2.276255    0.599670    0.599670        18:22
2       2.356208    1.974409    0.677426    0.677426        18:31
3       2.068619    1.836324    0.732409    0.732409        18:26
4       1.943876    1.789893    0.742310    0.742310        18:20

When I was checking the confusions using this block of code:
interp.plot_confusion_matrix()
interp.most_confused(min_val=5)
interp.plot_multi_top_losses()
interp.plot_confusion_matrix(figsize=(20, 20), dpi=200)

I got this output about my validation set:
15081 misclassified samples over 15150 samples in the validation set.

Finally, when I validate the model with the test set, this is what I get:
path = '/content/food-101/images'
data_test = ImageList.from_folder(path).split_by_folder(train='train', valid='test').label_from_re(file_parse).transform(size=224).databunch()

learn.load('stage-3')
learn.validate(data_test.valid_dl)

[1.602944, tensor(0.7987), tensor(0.7987)]


text: Q: How to integrate Bacnet into arduino I am trying to integrate bacnet protocol into arduino uno.I tried to add the libraries here https://github.com/bacnet-stack/bacnet-stack/tree/master/ports/arduino_uno. I tried compiling with programs like minGW WinAVR eclipse, but I kept getting errors.How can I write a code for bacnet ip with udp/ip. and finally how can i integrate bacnet protocol into arduino uno. I would be very grateful if you could help. Thank you very much in advance.


text:
Q: Directly calculating integral of l-form over an sphere If you have $\omega=x_3 dx_1\wedge dx_2$, $\sigma(\theta,\phi) = (\sin\phi\cos\theta,\sin\phi\sin\theta,\cos\phi)$ defined on $[0,2\pi]\times[-\pi/2,\pi/2]$, calculate $\int_\sigma \omega$ directly.
What I did/thought:
So, I know that for a continuously differentiable mapping $\sigma':Q_2\to \mathbb{R^3}$, we should be able to write something like: $\int_{\sigma'} \omega = \int_{Q_2}\omega(D_1\sigma'(x),D_2\sigma'(x)) \quad dx$, where $Q_2$ is the 2-simplex. But, I'm not sure how to proceed, it's not immediate to me that our $\sigma$ is such a mapping from the $Q_2$ simplex and also, even if it's, I don't know how what to do beyond this:
$\int_{\sigma} \omega = \int_{Q_2}\omega(D_1\sigma(x),D_2\sigma(x)) dx = \int_{Q_2}\omega((-\sin\phi\cos\theta,\sin\phi\cos\theta,0),(-\sin\phi\cos\theta, -\sin\phi\sin\theta, cos\phi)) dx
$

A: $x_1=\sin\phi\cos\theta, x_2=\sin\phi\sin\theta,x_3=cos\phi$
$dx_1=-\sin\phi\sin\theta d\phi+\cos\phi\cos\theta d\theta$
$dx_2=\sin\phi\cos\theta d\phi+\cos\phi\sin\theta d\theta$
$$\omega=x_3dx_1\wedge dx_2=\cos\phi((-\sin\phi\sin\theta d\phi+\cos\phi\cos\theta d\theta)\wedge(\sin\phi\cos\theta d\phi+\cos\phi\sin\theta d\theta)=\cos\phi(-\cos^2\phi\sin^2\theta d\phi d\theta+\sin\phi\cos\phi\cos^2\theta d\theta d\phi)=\cos\phi(\sin\phi\cos\phi+\cos^2\phi) d\phi d\theta$$
$$\int_{\sigma([0,2\pi]\times[-\pi/2,\pi/2])}\omega=\int_{[0,2\pi]\times[-\pi/2,\pi/2]}\cos\phi(\sin\phi\cos\phi+\cos^2\phi) d\phi d\theta$$


text:
Q: How do I share a javascript object between different pages in Adobe AIR? I'd like to have a custom object attached to the application so I can preserve state in it between different html pages in adobe air. Is this possible?

I was asking for a fullblown solution to store a custom js object in memory and persist it between pages loaded from the application sandbox, but this cannot be done unless I use iframes which is not very pleasant, since I have to add a lot of stuff to the bridge. Anoter way may be to do partial rendering of the page filled with html read from files, but this exposes a lot of unpleasant bugs + you cant write script tags  in the dom dynamically. It's a crippled platform.

A: Perhaps you could try attaching the object on the user's machine. There is a tutorial online that seems like it could help:
http://corlan.org/2008/09/02/storing-data-locally-in-air/
Example from the site:
//write an Object to a file
private function writeObject():void {
    var object:Object = new Object();//create an object to store
    object.value =  asObject.text; //set the text field value to the value property
    //create a file under the application storage folder
    var file:File = File.applicationStorageDirectory.resolvePath("myobject.file");
    if (file.exists)
        file.deleteFile();
    var fileStream:FileStream = new FileStream(); //create a file stream
    fileStream.open(file, FileMode.WRITE);// and open the file for write
    fileStream.writeObject(object);//write the object to the file
    fileStream.close();
}

A: What sort of object ?-)
If it only holds values that are meaningful in a string, you could store it as a cookie or perhaps in a serverside session ...


text:
Q: Execution order of anonymous function (function() {
  f();
  f = function() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();

prints 9, 8.
Why isn't it 8, 9?
Why doesn't the anonymous function execute first?

A: Please see the numbers for order of execution.
Basically you have 4 parts,

*

*The function declaration with a hoisted function,

*an IIFE calling the function

*a new assignment of f and

*the last call of the new function.

(function() {
  f();                 // calling hoisted function      2
  f = function() {     // assigning new function to f   3
    console.log(8);
  }
})()
function f() {         // hoisted function              1
  console.log(9)
}
f();                   // calling new function          4

A: Because you defined f() after the invocation of it.
So it doesn't invoke the  f() function defined in the IIFE but the outter f() :
by reversing the order :
(function () {
    f = function () {
        console.log(8);
    }
    f();
})()

you could have 8 and 8 as output as in both cases it invokes the overridden f() function.

A: If you need the output you can modify it like this
(function() {
  f();
  function f() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();

But let me explains why it executes that way.
(function() {
  f(); // Line Number -a
  f = function() { //b
    console.log(8);
  }
})()

function f() { //c
  console.log(9)
}

f() //d

There is the difference.The line 'b' is a function expression.It is only defined when it is reached.So when it reaches 'a' i doesn't actually know about the 'b' function.On the contrary, c is a function declaration and when it encouters 'f()' it immediately knows.
Right after 'a' is executed (which executes 'c',it will be modified by 'b' to its new defanition.
To make it more clear consider this function
function printMe(){
  var a;
  console.log(a);
  a = 10;//It an expression
}

The output you would get is it is defined.Because untill that line a=10 is not executed, it doesn't have a value.
There is this little code written by Philip Roberts which actually shows how your code is being executed .Please have a look here


text:
Q: Get module instance given its vars dict Suppose I have the dict of a module (via vars(mod), or mod.__dict__, or globals()), e.g.:
import mod

d = vars(mod)

Given the dict d, how can I get back the module mod? I.e. I want to write a function get_mod_from_dict(d), which returns the module if the dict belongs to a module, or None:
>>> get_mod_from_dict(d)
<module 'mod'>

If get_mod_from_dict returns a module, I must have that this holds:
mod = get_mod_from_dict(d)
assert mod is None or mod.__dict__ is d

I actually can implement it like this:
def get_mod_from_dict(d):
    mods = {id(mod.__dict__): mod for (modname, mod) in sys.modules.items()
                                  if mod and modname != "__main__"}
    return mods.get(id(d), None)

However, this seems inefficient to me, to iterate through sys.modules.
Is there a better way?

Why do I need this?

*

*In some cases, you get access to the dict only. E.g. in the stack frames. And then, depending on what you want to do, maybe just for inspection/debugging purpose, it is helpful to get back the module.

*I wrote some extension to Pickler which can pickle methods, functions, etc. Some of these have references to the module, or the module dict. Wherever I have a dict which belongs to a module during pickling, I don't want to pickle the dict, but instead a reference to the module.

A: Every module has a __name__ attribute that uniquely identifies the module in the import system:
>>> import os
>>> os.__name__
'os'
>>> vars(os)['__name__']
'os'

Imported modules are also cached in sys.modules, which is a dict mapping module names to module instances. You can simply look up the module's name there:
import sys

def get_mod_from_dict(module_dict):
    module_name = module_dict['__name__']
    return sys.modules.get(module_name)

Some people have expressed concern that this might not work for (sub-)modules in packages, but it does:
>>> import urllib.request
>>> get_mod_from_dict(vars(urllib.request))
<module 'urllib.request' from '/usr/lib/python3.7/urllib/request.py'>

There is a very minor caveat, though: This will only work for modules that have been properly imported and cached by the import machinery. If a module has been imported with tricks like How to import a module given the full path?, it might not be cached in sys.modules and your function might then unexpectedly return None.

A: You can use importlib.import_module to import a module given it's name. Example for numpy

In [77]: import numpy
    ...: import importlib

In [78]: d = vars(numpy)

In [79]: np = importlib.import_module(d['__name__'])

In [80]: np.array([1,2,3])
Out[80]: array([1, 2, 3])

A: For completeness, another solution, via the gc module:
def get_mod_from_dict_3(d):
  """
  :param dict[str] d:
  :rtype: types.ModuleType|None
  """
  objects = gc.get_referrers(d)
  for obj in objects:
    if isinstance(obj, types.ModuleType) and vars(obj) is d:
      return obj
  return None

Using gc might be Python interpreter dependent, though. Not all Python interpreters might have a GC. And even if they have, I'm not sure it is guaranteed that the module has a reference to its dict (although, very likely, it does; it cannot really think of a good reason why it would not have).
So, I think the other solution via sys.modules[d['__name__']] is probably better.
Although I checked CPython and PyPy, and in both cases, this solution works. And also, this solution is more generic. It works (without the check for ModuleType) even for any arbitrary object.
Despite, thinking about different Python interpreters, I could imagine even a Python interpreter where vars(mod) will never return the same dict, where this will create a dict on-the-fly. Then such a function cannot be implemented at all. Not sure.
I collected all the given solutions, and some testing code, here.

A: You could eventually improve a little your solution by using a generator:
def get_mod_from_dict_2(d):
    return next((mod for modname, mod in sys.modules.items() if mod and modname != "__main__" and id(mod.__dict__) == id(d)), None)

But that won't help you to avoid the use of sys.modules...
Update: As said in the answer of @Devesh Kumar Singh, you could use the importlib module to retrieve an already imported module by name (or import it if it haven't been already). The module's dictionary holds the module's name and file as long as it is not the '__main__' module. From there, you can do:
import importlib
import some_module

d = vars(some_module)
print(d['__name__']) # >> 'some_module'

m = importlib.import_module(d['__name__'])
print(m)   # >> <module 'some_module' from '/path/to/some_module.py'>


text:
Q: When I use Objective-C dot notation to set a subclass member, I get a compiler error Enrivonment: Mac OS X 10.6.8    Xcode 3.2.3
@interface A : NSObject
@end

@implementation: A
@end

@interface B : A
{
    int b;
}
@property int b;
@end

@implementation B
@synthesize b;
@end

#import "A.h"
#import "B.h"

int main()
{
    A *pa;
    pa = [[B alloc] init];
    pa.b = 3; /*here I get a error: request for member 'b' in something
                not a structure or union. */

    [pa setB: 3]; // this works.
    return 0;
}

So why is that an error? As I know dot notation and bracket notation do the same thing.

A: pa is pointer to an instance of class A, which doesn't have a property b.
You need to cast it to a pointer to B:
((B*)pa).b = 3;

This line has no compiler error, but it has warning about an unknown selector (because pa is a pointer to A):
[pa setB: 3];

But in the case of a property, the compiler needs to know what kind of property it is, to be able to generate the appropriate message.

A: You have declared pa as being of type A*
Then you alloc B and assigns to pa. Since B is a subclass of A, it works.
Then you reference pa.b. A* (which is the type of the variable) does not have the member b. It should work if you cast it:
((*B)pa).b = 3;
setB works, as the compiler will try to send the selector setB: , which the object might or might not respond to.
You'll probably get a warning though.

A: At runtime they do the same, yes, but you are still at compile time.
At compile time, if you use dot notation the compiler doesn't let you get away with something that it thinks might not work. Since you are accessing the object through the base class type A, but the property sits on type B, the compiler complains with an error.
If on the other hand you use bracket notation, the compiler is less adamant and prints a warning only. It concedes that you might know what you are doing :-) but it lets you know that it hasn't seen a method named setB: in the interface of class A.
To get rid of the warning, declare your variable lke this:
id pa;

Using the type id (which translates as "pointer to an object") lets you send any message to an object without a warning, because now the compiler makes no assumptions whatsoever about the object's type. You have arrived in the wonderful world of the fully dynamic language Objective-C :-)

A: you define the object of a class and alloc the object of class b so when you wamt too use that after type cast that pointer.
((B*)pa).b = 3;
then its not given any error.


text:
Q: What is the EmitMapper equivalent for this AutoMapper configuration? I have the following class and interface definitions, and would like to use EmitMapper instead of AutoMapper to map from class to interface. The current code works, but I'd like to use EmitMapper, yet have not figured out how to use it.
public interface  ITreeViewDTO
{
    int Id { get; set; }
    string Name { get; set; }
    int? Parent_Id { get; set; }
    string ExtraData { get; set; }
    IEnumerable<ITreeViewDTO> SubNode { get; set; }
}

public class Navigation
{
    public int Id { get; set; }
    public string Name{ get; set; }
    public int? Parent_Id { get; set; }
    public virtual IList<Navigation> SubNavigations { get; set; }
}

This is the current AutoMapper configuration for the desired mapping:
Mapper.CreateMap<Navigation, ITreeViewDTO>()
   .ForMember(dest => dest.SubNode,
              opt => opt.MapFrom<IEnumerable<Navigation>>(src => src.SubNavigations));
var iTreeView = Mapper.Map<Navigation, ITreeViewDTO>(root);

What would be the equivalent EmitMapper code for the above sample?


text:
Q: Take out the first line of a field and add it as a new field in Logstash 1.4.0 I have my ELK stack configured and running using log4j and everything is working fine. What I would like to be able to do is group all exceptions by their type, for example - create a terms graph and have a term for each exception type like FileNotFound, NullPointerException and so on. I already have a stack_trace field which includes the exception type at the first line, and then the complete stack trace. I found something online like this:
filter{
  mutate {
    gsub => [
      "stack_trace", "\n.*", ""
    ]
  }
}

but this would just override the stack_trace field with it's first line, which is not what I want. I want to add a new field that takes out the first line, the exception type, of the stack_trace field.

A: Make a copy of the stack trace field and perform your gsub on that
filter{
  mutate {
    add_field => {
      "exception" => "%{stack_trace}"
    }
  }
  mutate {
    gsub => [
      "exception", "\n.*", ""
    ]
  }
}

EDIT: Thanks to @Alpha for pointing out this question, you may need to use two separate mutates.


text:
Q: Google Speech API, the option [phrases] using I try to use the 'phrases' property to add extra words to be recognized by the Google API. When I set them in my request, I receive an error message.
I receive the response 400 with this error : "Invalid JSON payload received. Unknown name \"speech_contexts\": Cannot find field.",
Do someone know why ?
@ May 19 08:30:41.72, conn = 0, URL = https://speech.googleapis.com/v1/speech:recognize?key=xxx
POST /v1/speech:recognize?key=xxx HTTP/1.1
Accept: */*
Host: speech.googleapis.com
User-Agent: OpenVXI/3.0 (compatible; Linux x86_64; Debian GNU/Linux 8 (jessie); Asterisk 11.22.0; BORJA) Voximal/14.0b
Connection: keep-alive
Content-Length: 51427
Content-Type: application/json

{"audio": {"content" : "UklGRiSWAABXQVZFZm10IBAAAAABAAEAQ...B8AAIA+AAACABAAZGF0YQCWAA

AAAAAAA="} , "config": {"encoding" : "LINEAR16" , "languageCode" : "en-US" , "sampleRateHertz" : "8000"} , "speechContexts": {"phrases" : [ "borja" ]}}
@ May 19 08:30:41.83, conn = 0, URL = https://speech.googleapis.com/v1/speech:recognize?key=AIzaSyDsK4BVecut8hce-DtwVkZB54QvBz8vRvA
HTTP/1.1 400 Bad Request
Vary: X-Origin
Vary: Referer
Content-Type: application/json; charset=UTF-8
Date: Fri, 19 May 2017 08:30:41 GMT
Server: ESF
Cache-Control: private
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Alt-Svc: quic=":443"; ma=2592000; v="37,36,35"
Accept-Ranges: none
Vary: Origin,Accept-Encoding
Transfer-Encoding: chunked

1c3
{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"speech_contexts\": Cannot find field.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"speech_contexts\": Cannot find field."
          }
        ]
      }
    ]
  }
}

A: I think you need to include the speechContexts argument as part of the config structure.  The payload should look something like this instead:
{
  "audio": {
    "content": "UklGRiSWAABXQVZFZm10IBAAAAABAAEAQ...B8AAIA+AAACABAAZGF0YQCWAAAAAAAAA="
  },
  "config": {
    "encoding": "LINEAR16",
    "languageCode": "en-US",
    "sampleRateHertz": "8000",
    "speechContexts": {
      "phrases": [
        "borja"
      ]
    }
  }
}


text:
Q: Eclipse Jface Projection Viewer - no reaction to Ctrl-Z In my current project I am working with a specific implementation of the jface ProjectionViewer attached to a TextEditor nested in a MultiPageEditor.
My task is now to implement a custom reaction to Ctrl-Z, and from what I get this is best done by attaching a specific implementation of IUndoHandler to the Viewer, all of that would be no problem.
But, pressing Ctrl-Z while having that TextEditor focused fails to cause any reaction that would be expected. While clicking "Undo Typing" in the context menu, which displays the associated key combination Ctrl-Z causes the TextViewerUndoManager.DocumentUndoListener's notification method is called, no line of code in the TextViewerUndoManager is touched when pressing Ctrl-Z.
As a possible source of this problem I assumed that maybe a handler might be defined for this key combination in an extension point, since I had previously experimented with this mechanism, but the plugin.xml does not define any key combinations nor undo handlers apart from one that is associated with a special context menu for a different widget.
It might be worth to note that Ctrl-C and Ctrl-V work as intended.
I need to find out what happens when Ctrl-Z is pressed and why nothing is relayed to the TextViewerUndoManager.
It would be very helpful if someone could describe the progress how eclipse handles these key combinations normally and decides which command is appropriate.
Thanks in advance

A: Cntrl+Z- undo is processed using OperationHistorySupport. Look at UndoActionHandler class.
Binding support is implemented using keydown event filter using WorkbenchKeyboard ( all keydown events first filtered using this class. this is how BindingService was implemented). This will figure out correspond command for the key binding.
DocumentUndoManager.UndoableTextChange is where undo operation is handled.