text:
Q: Inno Setup always starts PowerShell in 32-bit mode in Pascal Script code I want to use PowerShell (64-bit version) in the ssPostInstall step of my Inno Setup, but it always opens a 32-bit PowerShell.
As you can see in my script my Inno Setup is configured as 64-bit application.
When I start the setup I can see in the Task Manager that it is running as a 32-bit application

Also the PowerShell which will be opened, is in 32 bit-mode.

Here is my Inno Stup script:
[Setup]
ArchitecturesAllowed=x64
ArchitecturesInstallIn64BitMode=x64
PrivilegesRequired=admin

[Code]
Procedure CurStepChanged(CurrentStep:TSetupStep);
var
  i, ResultCode, ErrorCode: Integer;
  findRec: TFindRec;
  isInstallationCmdSuccessful: Boolean;
  folderNameOfUpdateIni: String;
  ReturnCode: Boolean;

begin
  if CurrentStep = ssPostInstall then begin
      Log('Starting post install steps, calling install.ps1');
      ReturnCode := ShellExec('open', ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '', '', SW_SHOWNORMAL, ewWaitUntilTerminated, ErrorCode);
      if (ReturnCode = True) then
        Log('post install returned true')
      else
        Log('post install returned false');

      Log('Starting post install steps, calling install.ps1');
      ReturnCode := ShellExec('open', ExpandConstant('{syswow64}\WindowsPowerShell\v1.0\powershell.exe'), '', '', SW_SHOWNORMAL, ewWaitUntilTerminated, ErrorCode);
      if (ReturnCode = True) then
        Log('post install returned true')
      else
        Log('post install returned false');
  end;
end;

How can I force Inno Setup to open a 64-bit PowerShell?

A: If you want to allow Pascal Script code functions to use 64-bit System32 files, use EnableFsRedirection function to disable WOW64 file system redirection.
And you also cannot use ShellExec, you need to use Exec function instead.
OldState := EnableFsRedirection(False);
try
  ReturnCode :=
    Exec('powershell.exe', '', '', SW_SHOWNORMAL, ewWaitUntilTerminated,
         ErrorCode);
finally
  EnableFsRedirection(OldState);
end;

Btw, ArchitecturesInstallIn64BitMode does not/cannot make Inno Setup run as 64-bit application. Inno Setup is 32-bit application, no matter what.


text:
Q: Bandwidth Speed Test Slower Than Expected Im trying to create a bandwidth test using Dart using a LibreSpeed server, but for some reason it's reporting a much slower speed than expected. When I test using the web client for LibreSpeed I get around 30mb/s download bandwidth, however with my Dart program I'm only getting around 4mb/s.
The code for the speed test is as follows:
Future<void> start() async {
  var rand = Random();
  var req = await client.getUrl(Uri.http(_serverAddress, '/garbage.php',
      {'r': rand.nextDouble().toString(), 'ckSize': '20'}));
  var resp = await req.close();
  var bytesDownloaded = 0;
  var start = DateTime.now();
  await for (var bytes in resp) {
    bytesDownloaded += bytes.length;
  }
  var timeTaken = DateTime.now().difference(start).inSeconds;
  var mbsDownloaded = bytesDownloaded / 1000000;
  print(
      '$mbsDownloaded megabytes downloaded in $timeTaken seconds at a rate of ${mbsDownloaded / timeTaken} mbs per second');
}

I think I'm probably not understanding a crucial reason as to why it appears to be so slow compared to the web client. Can anyone give me any ideas as to what the bottleneck might be?

A: The problem is confusion between the use of units when measure internet speed. In general terms there are two ways we can measure the speed:

*

*Mbps (MegaBit Per Second)

*MB/s (MegaByte per second)

To understand your problem we need to notice that 1 byte = 8 bits. Also, that the unit LibreSpeed (and most internet providers) uses is Mbps.
The unit your current program are measuring in is MB/s since you are using the length of the list (each element of the list is 1 byte = 8 bit:
  await for (var bytes in resp) {
    bytesDownloaded += bytes.length;
  }

And never multiply that number by 8 later in your code. You are then comparing this number against the number from LibreSpeed which uses Mbps (same as most internet providers) which means your number is 8 times smaller that expected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What event exist to datagrid What event exist to datagrid, that works when you change any data on datagrid?
in wpf

A: I think you are looking for the RowEditEnding event:
Reference: RowEditEnding

A: Here is a quick example
<DataGrid .... SelectionChanged="selection_changed" RowEditEnding="row_Editing"  CellEditEnding="cel_Editing"       >

their is a nice example on this link http://www.dotnetcurry.com/ShowArticle.aspx?ID=563


text:
Q: Excel formula "counta" return 1 on a range of empty cells I got a file I am working on that contains various sheets and I am trying to get a "COUNTA" formula to update the values of the not empty cells of a certain range.
The problem is the formula keeps returning "1".
I got "=IFERROR(COUNTA('A-Servers'!B2:B31;);"0")" on Sheet B that reffers to Sheet A.
To be absolutely sure, I went to Sheet A and got the "LEN" for the cell range I wanna check with "=LEN(B2)" up to B31 and go "0" all the way down.
The only thing I assume I am not sure and might be the cause of this, is that the range got the cells merged on every 2 cells, so B2 and B3 are merged as well as B4 with B5 and so on.
BTW I am using excel 2013
Could you guys help me figure out why the CountA formula keeps returning the count of 1 cell not empty?

A: COUNTA also counts cells with the empty string (""), even though they have a length of zero.  Merging does not impact this.  So, select the range and press delete, and you should be brought back to zero.
(FYI - formulas also make a cell non-empty, since they must have an output.  So a formula that appears to have no output will instead output the empty string.)

A: What worked for me was adding a "-1" on the end of the formula like this: =IFERROR(COUNTA('A-Servers'!B692:B721;)-1;"0") and it works fine.


text:
Q: Change network cards names in Network Manager applet I have four network cards of the same type in my PC, and all of them look the same in network manager applet:
EthernetNetwork (Broadcom NetXtreme BCM5704 Gigabit Ethernet)
disconnected
EthernetNetwork (Broadcom NetXtreme BCM5704 Gigabit Ethernet)
disconnected
EthernetNetwork (Broadcom NetXtreme BCM5704 Gigabit Ethernet)
disconnected
EthernetNetwork (Broadcom NetXtreme BCM5704 Gigabit Ethernet)
disconnected

Is there a way to change name for each card in network manager applet to distinguish interfaces?
System is Ubuntu 14.04.


text:
Q: Initializing c3p0 pool... timeout I am trying to connect to mysql database using hibernate and c3p0, but i'm having server timeout error (even if i increase timeout to several minutes)
I am using mysql, eclipse, maven, spring, tomcat 8.5, hibernate and c3p0.
here's my .properties file
# MySQL properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.user=root
mysql.password=root
# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
# C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=180
hibernate.c3p0.max_statements=150

configuration
package com.bookshop.configuration;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import static org.hibernate.cfg.Environment.*;

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = {
        @ComponentScan("com.bookshop.model"),
        @ComponentScan("com.bookshop.dao"),
        @ComponentScan("com.bookshop.service")
})
public class AppConfig {

    @Autowired
    private Environment env;

    @Bean
    public LocalSessionFactoryBean getSessionFactory() {
        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
        Properties prop = new Properties();

        // Setting JDBC properties
        prop.put(DRIVER, env.getProperty("mysql.driver"));
        prop.put(URL, env.getProperty("mysql.url"));
        prop.put(USER, env.getProperty("mysql.user"));
        prop.put(PASS, env.getProperty("mysql.password"));

        // Setting hibernate properties
        prop.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
        prop.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));

        // Setting C3P0 properties
        prop.put(C3P0_MIN_SIZE, env.getProperty("hibernate.c3p0.min_size"));
        prop.put(C3P0_MAX_SIZE, env.getProperty("hibernate.c3p0.max_size"));
        prop.put(C3P0_ACQUIRE_INCREMENT, env.getProperty("hibernate.c3p0.acquire_increment"));
        prop.put(C3P0_TIMEOUT, env.getProperty("hibernate.c3p0.timeout"));
        prop.put(C3P0_MAX_STATEMENTS, env.getProperty("hibernate.c3p0.max_statements"));

        factoryBean.setHibernateProperties(prop);
        factoryBean.setPackagesToScan("com.bookshop.model");
        return factoryBean;
    }

     @Bean
     public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
       transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
     }
}

server TIMEOUT occurs after these log lines
...
INFO: Root WebApplicationContext: initialization started
jan 13, 2019 7:33:51 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Sun Jan 13 19:33:51 MSK 2019]; root of context hierarchy
jan 13, 2019 7:33:51 PM    org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.bookshop.configuration.AppConfig]
jan 13, 2019 7:33:52 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.0.CR2}
jan 13, 2019 7:33:52 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
jan 13, 2019 7:33:52 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
jan 13, 2019 7:33:53 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: com.mysql.cj.jdbc.Driver at URL: jdbc:mysql://localhost:3306/bookshop?autoReconnect=true&useSSL=false
jan 13, 2019 7:33:53 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001001: Connection properties: {user=root, password=****}
jan 13, 2019 7:33:53 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001003: Autocommit mode: false
jan 13, 2019 7:33:53 PM com.mchange.v2.log.MLog
INFO: MLog clients using java 1.4+ standard logging.
jan 13, 2019 7:33:53 PM com.mchange.v2.c3p0.C3P0Registry
INFO: Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
jan 13, 2019 7:33:53 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001007: JDBC isolation level: <unknown>
jan 13, 2019 7:33:53 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource
INFO: Initializing c3p0 pool...
com.mchange.v2.c3p0.PoolBackedDataSource@27499807
connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@69d301cd
[ acquireIncrement -> 1,
acquireRetryAttempts -> 30,
acquireRetryDelay -> 1000,
autoCommitOnClose -> false,
automaticTestTable -> null,
breakAfterAcquireFailure -> false,
checkoutTimeout -> 0,
connectionCustomizerClassName -> null,
connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester,
contextClassLoaderSource -> caller,
debugUnreturnedConnectionStackTraces -> false,
factoryClassLocation -> null,
forceIgnoreUnresolvedTransactions -> false,
forceSynchronousCheckins -> false,
identityToken -> 1hge0wga0jzt7ghyoftwg|30ba8455,
idleConnectionTestPeriod -> 0,
initialPoolSize -> 5,
maxAdministrativeTaskTime -> 0,
maxConnectionAge -> 0,
maxIdleTime -> 1800,
maxIdleTimeExcessConnections -> 0,
maxPoolSize -> 20,
maxStatements -> 150,
maxStatementsPerConnection -> 0,
minPoolSize -> 5,
nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@2a1a6154
[ description -> null,
driverClass -> null,
factoryClassLocation -> null,
forceUseNamedDriverClass -> false,
identityToken -> 1hge0wga0jzt7ghyoftwg|15fd41d6,
jdbcUrl -> jdbc:mysql://localhost:3306/bookshop?autoReconnect=true&useSSL=false,
properties -> {user=******, password=******} ],
preferredTestQuery -> null,
privilegeSpawnedThreads -> false,
propertyCycle -> 0,
statementCacheNumDeferredCloseThreads -> 0,
testConnectionOnCheckin -> false,
testConnectionOnCheckout -> false,
unreturnedConnectionTimeout -> 0,
usesTraditionalReflectiveProxies -> false;
userOverrides: {} ],
dataSourceName -> null,
extensions -> {},
factoryClassLocation -> null,
identityToken -> 1hge0wga0jzt7ghyoftwg|6b84d329,
numHelperThreads -> 3 ]

(i am learning and i was followed these videos: https://www.youtube.com/watch?v=OyLF640v7WE)
Can anybody tell what's wrong?

A: Finally, i solved it
There was written in logs 'hibernate.properties not found', so i renamed .properties file from db.properties to hibernate.properties, also i added to properties file dialect as
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

and added it in AppConfig class:
prop.put(DIALECT, env.getProperty("hibernate.dialect"));

and now everything works fine.


text:
Q: Line Graph D3.js Error :  attribute d: Expected number, "MNaN,289.8LNaN,27…" LineGraph is not plotted only the axis are shown.
Error shown is : d3.v4.min.js:2 Error:  attribute d: Expected number, "MNaN,289.8LNaN,27…".
The time is in Unix code maybe that's causing the error.
The file shows X-axis with time and Y-axis with temperature.
I have tried converting unix to a timestamp, but I need it in minutes/seconds.
The javascript Part :
 const xValue = d => new Date(d.timestamp * 1000);
    const xLabel = 'Time';
    const yValue = d => d.temprature;
    const yLabel = 'Temperature';
    const margin = { left: 120, right: 30, top: 20, bottom: 120 };

    const svg = d3.select('svg');
    const width = svg.attr('width');
    const height = svg.attr('height');
    const innerWidth = width - margin.left - margin.right;
    const innerHeight = height - margin.top - margin.bottom;

    const g = svg.append('g')
        .attr('transform', `translate(${margin.left},${margin.top})`);
    const xAxisG = g.append('g')
        .attr('transform', `translate(0, ${innerHeight})`);
    const yAxisG = g.append('g');

    xAxisG.append('text')
        .attr('class', 'axis-label')
        .attr('x', innerWidth / 2)
        .attr('y', 100)
        .text(xLabel);

    yAxisG.append('text')
        .attr('class', 'axis-label')
        .attr('x', -innerHeight / 2)
        .attr('y', -60)
        .attr('transform', `rotate(-90)`)
        .style('text-anchor', 'middle')
        .text(yLabel);

    const xScale = d3.scaleTime();
    const yScale = d3.scaleLinear();

    const xAxis = d3.axisBottom()
        .scale(xScale)
        .tickPadding(15)
        .ticks(5)
        .tickSize(-innerHeight);

    const yTicks = 5;
    const yAxis = d3.axisLeft()
        .scale(yScale)
        .ticks(yTicks)
        .tickPadding(15)
        .tickSize(-innerWidth);

    const line = d3.line()
        .x(d => xScale(xValue(d)))
        .y(d => yScale(yValue(d)))
        .curve(d3.curveBasis);

    const row = d => {
        d.timestamp = new Date(d.timestamp * 1000);
        d.temprature = +d.temprature;
        return d;
    };

    d3.csv('http://localhost:8000/result.csv', row, data => {
        xScale
            .domain(d3.extent(data, xValue))
            .range([0, innerWidth]);

        yScale
            .domain(d3.extent(data, yValue))
            .range([innerHeight, 0])
            .nice(yTicks);

        g.append('path')
            .attr('fill', 'none')
            .attr('stroke', 'steelblue')
            .attr('stroke-width', 4)
            .attr('d', line(data));

        xAxisG.call(xAxis);
        yAxisG.call(yAxis);
    });

The CSV file :
temprature,time
22.34,1553974814384
24.77,1554453925188
25.09,1554455725250
25.73,1554457525395


text:
Q: jQuery UI dialog - problem with event on close I'm trying to perform a specific action when I close a jQuery UI dialog. Here's a simplified version of my code:
$('a.open-trigger').click(function(){
    var test = 'hello';

    $('#dialog').dialog({
        bgiframe: true,
        dialogClass: 'change',
        resizable: false,
        draggable: false,
        modal: true,
        height: 334,
        width: 450,
        autoOpen: false,
        show: 'fade'
    });

    $('#dialog').dialog('open');

    $('a.close-trigger').click(function(){
        alert(test);
        $('#dialog').dialog('close');
    });
});

The first time I close the dialog, I get the expected alert with the word "hello". If I open the dialog a second time, and close it, I get the "hello" alert twice. If I open and close it a third time, I get three alerts, and so on.
Why are these alerts duplicating themselves? I would want to the alert to only show up once on close, no matter how many times I open/close the dialog.
Thanks!
Simon

A: You are attaching additional event handlers every time you call .click. That is why it is duplicating.
$('a.close-trigger').click(function(){
                    alert(test);
                    $('#dialog').dialog('close');
            });

Pull that code out onto the same level as the other event binding and it should work as expected.

A: You've bound a function to the open button that adds a event handler to the close button each time the open event is fired.  You should add your close event handler somewhere outside of 'a.open-trigger' event function...
$('a.open-trigger').click(function(){
        var test = 'hello';

        $('#dialog').dialog({bgiframe: true, dialogClass: 'change', resizable: false, draggable: false, modal: true, height: 334, width: 450, autoOpen: false, show: 'fade'});
        $('#dialog').dialog('open');
});

$('a.close-trigger').click(function(){
        alert(test);
        $('#dialog').dialog('close');
});

A: You need to take the close click event handler out of the open click event handler
$(function() {
    $('#dialog').dialog({bgiframe: true, dialogClass: 'change', resizable: false, draggable: false, modal: true, height: 334, width: 450, autoOpen: false, show: 'fade'});

    $('a.open-trigger').click(function(){
        $('#dialog').dialog('open');
    });

    $('a.close-trigger').click(function(){
        alert("hello");
        var myDialog = $('#dialog');
        if (myDialog.dialog('isOpen'))
            myDialog.dialog('close');
    });
});


text:
Q: iTunes not showing app update description texts I have a very weird problem with iTunes lately. When I go to Apps → Updates, all apps that show up there, don't have an update description text. The app is displayed, its version is displayed, vendor, size, etc., but no text. I tried to clear the cache from within iTunes, but no luck. This is how it looks like:

I'd appreciate if someone could help me.


text:
Q: Does Firebase always guarantee added events in order? I am developing messenger IOS app  based on Firebase Realtime Database.
I want that all messages to be ordered based on timestamp.
There is a scenario as like below.
There are 3 clients. A, B and C.
1)
All clients register 'figure-1' listener to receive messages from others.
<figure-1>

ref.queryOrdered(byChild: "timestamp").queryStarting(atValue: startTime).observe(.childAdded, with:
{
    ....
    // do work for the messages, print, save to storage, etc.
    ....

    // save startTime to storage for next open.
    startTime = max(timeOfSnapshot, startTime)
    saveToStorage(startTime)
}

2)
Client A write  message 1 to server with ServerValue.timestamp().
Client B write  message 2 to server with ServerValue.timestamp().
Client C write  message 3 to server with ServerValue.timestamp().

They sent messages extremely the same moment.
All clients have good speed wifi.
So, finally. Server data saved like 'figure-2'
<figure-2>

text : "Message 1",  timestamp : 100000001
text : "Message 2",  timestamp : 100000002
text : "Message 3",  timestamp : 100000003

As my listener's code, i keep messages on storage and next listening timestamp for preventing downloading duplicated messages.
In this case.
Does Firebase always guarantee to trigger callback in order as like below?
Message 1
Message 2
Message 3

If it is not guaranteed, my strategy is absolutely wrong.
For example, some client received messages as like below.
Message 3  // the highest timestamp.

// app crash or out of storage

Message 1
Message 2

The client do not have chance to get message 1, 2 anymore.
I think if there are some nodes already, Firebase might trigger in order for those. Because, that is role of 'queryOrdered' functionality.
However, there are no node before register the listener and added new nodes additionally after then. What is will happen?
I suppose Firebase might send 3 packets to clients. (No matter how quickly the message arrives, Firebase has to send it out as soon as it arrives.)
Packet1 for message1
Packet2 for message2
Packet3 for message3

ClientA fail to receive for packet 1,2
ClientA success to receive for packet 3
Firebase re-send packet 1,2 again.
ClientA success to receive for packet 1,2

Eventually, all datas are consistent. But ordering is corrupted.
Does Firebase guarantee to occur events in order?
I have searched stack overflow and google and read official documents many times. However, i could not find the clear answer.
I have almost spent one week for this. Please give me piece of advice.

A: The order in which the data for a query is returns is consistent, and determined by the server. So all clients are guaranteed to get the results in the same order.
For new data that is sent to the database after the listeners are attached, all remote clients will receive it in the same order. The local client will see events for it's write operation right away though, before the data even reaches the database server.
In figure 2, it is actually quite simple: since each node has a unique timestamp, and they will be returned in the order of that timestamp. But even if they'd have the same timestamp, they'd be returned in the same order (timestamp first, then key) for each client.


text:
Q: How to use PFRelation for liking? I want to make a social media app where you can like posts and I heard that you can use PFRelation to do that, but I'm not sure how. I checked Parse.com's docs but it gave me limited information on it, so how would I go about doing this?

A: It all depends on what you want to make it a relation to. Is it users? Is it a post class itself? Is it statistics class (i.e. Number of views, number of likes, active comments)? If you want to create a like feature, for simplicity, I would forego creating an entire relation if that's the only feature you are worried about. Simply create a new column in the backend and increment it every time the user taps on like, and decrease it when they re-tap.
Let's say you have a Class called Posts. And in Posts you have these columns:
| objectId | PostTitle (string) | PostDesc (string) | PostImage (File) | Likes (number) | updatedAt | createdAt | etc etc
All you would need to do is when a user taps on the like button increment the 'Like' column by 1, and vice versa
If your worried about relations for other reasons than I understand. But this is a suitable avenue to take for something so simple

someObject.incrementKey("Likes")
someObject.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
  if (success) {
  // The like key has been incremented
  } else {
  // There was a problem, check error.description
  }
}


text:
Q: rotating coordinate system with time I am not sure if this is the correct place for my question, but I'll give it a shot. I guess it is somewhere between CS and physics, but since I am programming this in C++, I'll post it here.
I am looking at a particle in 3D, which is being bent in the (x, y)-plane due to a force applied to it, as illustrated in the figure. The force is the bolded arrow entering from NE. The angle between the y-axis and the force is "a".
setup
The particle enters from the left with a velocity vector (v_x, v_y, v_z) and is bend around the corner. This is nicely and easily described by Newtons second law, no problems there. This is easy to solve numerically e.g. by an Euler method. This I have implemented succesfully, so far so good.
However as the figure suggests, the particle moves in a cylindrical tube of constant diameter h and I wish to find the normal distance to the wall in both the x- and z-direction (which points out of the screen) at some time t. By "normal distance" I mean that if the coordinate system rotates with the particle, then I want to know the distance from the particle to the edge of the tube along y and z (as illustrated with the 3 small arrows pointing towards the tube edge). The ultimate goal is somehow to figure out if the particle has hit the wall or not.
For the z-direction it is trivial as its axis does not change during the trajectory. However the y-direction is causing me huge problems. This is my question: Is there a way for me to find the distance to the tube edge along y during the trajectory? Note that I am doing this numerically, so I don't necessarily need an analytical expression.
Best,
Niles.

A: You don't say what the shape of the tube is, but in general:

*

*If the bend in the tube is circular, then compute the distance from the particle to the center of curvature (the center of the circle) for both the inner and outer rim of the tube. Call this Dpi and Dpo (distance from particle to center of curvature, inner and outer). The distance from the center of the circle to the tube itself is constant: the radius of the circle, Ri and Ro. You can then calculate the distance of the particle from the inner and outer parts of the tube by Dpi - Ri and Dpo - Ro.

*If the bend in the tube is not circular, then you have to evolve a function which calculates the two radii, Ri and Ro, as function of the ANGLE of the radius, since these values will no longer be constant. Once you have this function you compute Dpi(theta) and Ri(theta) and Dpo(theta) and Ro(theta) and your distances are the differences as above.


text:
Q: Call moveRowAtIndexPath from TableViewController I implemented the body of the method moveRowAtIndexPath:toIndexPath: as follows:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    XYZToDoItem *itemToMove = [self.toDoItems objectAtIndex:fromIndexPath.row];
    NSLog(@"Moving");
    NSLog( itemToMove.itemName);

    [self.toDoItems removeObjectAtIndex:fromIndexPath.row];
    [self.toDoItems insertObject:itemToMove atIndex:toIndexPath.row];
}

I'd like to call this method from TableViewController's didSelectRowAtIndexPath method.
When I do the rows of the table do move, but the above method doesn't seem to execute. Nothing logs to the console and the items in the array toDoItems DO NOT swap.
Here's the body of that method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *indexPathOfLastItem =
    [NSIndexPath indexPathForRow:([self.toDoItems count] - 1) inSection:0];

    [tableView moveRowAtIndexPath:indexPath toIndexPath:indexPathOfLastItem];
}

How do I get the table view to move rows properly from within the delegate (the TableViewController)?

A: Moving (or adding, removing) table view rows by code (and not by user interaction) does not cause the
data source methods to be called.
If you need the data source method to be executed, you need to call it explicitly:
// Move table view row:
[tableView moveRowAtIndexPath:indexPath toIndexPath:indexPathOfLastItem];
// Call data source method:
[self tableView:tableView moveRowAtIndexPath:indexPath toIndexPath:indexPathOfLastItem];

Swift 3:
// Move table view row:
tableView.moveRow(at: indexPath, to: indexPathOfLastItem)
// Call data source method:
self.tableView.moveRow(at: indexPath, to: indexPathOfLastItem)

A: I don't think you're calling the method correctly, since it's not a real delegate method you have to call it on self.
Try:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *indexPathOfLastItem =
    [NSIndexPath indexPathForRow:([self.toDoItems count] - 1) inSection:0];

   [self tableView:tableView moveRowAtIndexPath:indexPath toIndexPath:indexPathOfLastItem];
}


text:
Q: Blogdown Site not showing my Images after deploying on Netlify After updating Blogdown package (1.3.2) and with Hugo version 0.79.0, there's a modification on my .html files generated by .Rmd files. The images now have this string: {{< blogdown/postref >}} that wasn't present before. See below example.

<img src="{{< blogdown/postref >}}index.en_files/figure-html/unnamed-chunk-5-1.png" width="432" style="display: block; margin: auto;" />

Then, the site after being deployed on Netlify, doesn't show the images of the .Rmd file.
Here's the link of my Github repo: https://github.com/FranciscoPiccolo/franciscopiccolo.github.io
Link of the webpage: https://franciscopiccolo.netlify.app/post/2019-09-05-residual-analysis-in-econometric-models/
Check site ouput:
> blogdown::check_site()
― Running a series of automated checks for your blogdown website project...
-------------------------------------------------------------------------------------------
○ A successful check looks like this.
● [TODO] A check that needs your attention looks like this.
| Let's check out your blogdown site!
-------------------------------------------------------------------------------------------
― Checking config.toml
| Checking "baseURL" setting for Hugo...
○ Found baseURL = "https://francisco.piccolo.com/"; nothing to do here!
| Checking "ignoreFiles" setting for Hugo...
○ "ignoreFiles" looks good - nothing to do here!
| Checking setting for Hugo's Markdown renderer...
○ All set! Found the "unsafe" setting for goldmark.
― Check complete: config.toml

― Checking .gitignore
| Checking for items to remove...
○ Nothing to see here - found no items to remove.
| Checking for items to change...
● [TODO] Change items in .gitignore: resources -> /resources
| Checking for items you can safely ignore...
○ Found! You have safely ignored: .DS_Store, Thumbs.db
| Checking for items to ignore if you build the site on Netlify...
● [TODO] When Netlify builds your site, you can safely add to .gitignore: /public/, /resources/
| Checking for files required by blogdown but not committed...
○ Great! Did not find such files.
― Check complete: .gitignore

― Checking Hugo
| Checking Hugo version...
○ Found Hugo. You are using Hugo 0.79.0.
| Checking .Rprofile for Hugo version used by blogdown...
| Hugo version not set in .Rprofile.
● [TODO] Set options(blogdown.hugo.version = "0.79.0") in .Rprofile and restart R.
― Check complete: Hugo

― Checking netlify.toml...
○ Found HUGO_VERSION = 0.79.0 in [build] context of netlify.toml.
| Checking that Netlify & local Hugo versions match...
○ It's a match! Blogdown and Netlify are using the same Hugo version (0.79.0).
| Checking that Netlify & local Hugo publish directories match...
○ Good to go - blogdown and Netlify are using the same publish directory: public
― Check complete: netlify.toml

― Checking content files
| Checking for validity of YAML metadata in posts...
○ All YAML metadata appears to be syntactically valid.
| Checking for previewed content that will not be published...
○ Found 0 files with future publish dates.
● [TODO] Found 2 files marked as drafts. To un-draft, run the command:

  blogdown::edit_draft(c(
  "content/privacy.md",
  "content/terms.md"
  ))

  and change a file's YAML from 'draft: true' to 'draft: false' or delete it
| Checking your R Markdown content...
○ All R Markdown files have been knitted.
○ All R Markdown output files are up to date with their source files.
| Checking for .html/.md files to clean up...
○ Found 0 duplicate .html output files.
○ Found 0 incompatible .html files to clean up.
| Checking for the unnecessary 'content/' directory in theme...
○ Great! Your theme does not contain the content/ directory.
― Check complete: Content

A: That is because you modified the file postref.html in this commit and added an EOL to it. This file must not have an EOL. To fix the problem, run this in your R console:
blogdown:::create_shortcode('postref.html', 'blogdown/postref', force = TRUE)


text:
Q: Pausing my App without stopping Display Im trying to let my App wait for 5 seconds. But it doesnt matter if I use sleep() or wait() in my created thread, My screen always gets white and after the 5 seconds it does what it should. How can I let the App wait without pausing the screendisplaying.

A: You should think about implementing some sort of timer, instead of sleep or wait. This will allow rendering and other things to continue while your timer completes.
Tutorial here:
CountDown Timer ios tutorial?


text:
Q: Grails - How to render partial unescaped JSON inside a Meta tag in an HTML page I'm passing a JSON String ({"myData":"data"}) to my rendered page like so:
render(view: 'myPage', model: [jsonData: JSONStr]);

then on the page template:
<meta content='http://www.myDomain.com/video?config=${ (jsonData) }' property="og:video" />

the result is:
<meta content='http://www.myDomain.com/video?config={"myData":"data"}' property="og:video" />

Is There a way to prevent escaping of the JSON data?

A: I fixed it with a TagLib
class SimpleTagLib {

 def unescaped = { attrs ->
      out << attrs.value
  }

}

<meta content='http://www.myDomain.com/video?config=${g.noEncode(value:jsonData)}' property="og:video" />


text:
Q: saving multiple check-boxes as different records in php Am trying to save the result of multiple check-boxes as separate records. my code is not functioning. please help!
<?php

session_start();
$id = $_SESSION['user_id'];
$db = new PDO('mysql:host=localhost;dbname=idp;charset=utf8','root', '');

foreach($_POST['comp'] as $val){
    $tmp['user_id'] = $id;
    $tmp['comp_id'] = $val;
    $vars[] = $tmp;
}

$qry = "INSERT INTO compentency_result (user_id, result) VALUES (:user_id, :comp_id)";

try
{
    $sql = $db->prepare($qry);
    $numRows = 0;
    foreach($vars as $insert){
        $numRows += $sql->execute($insert);
    }
    print("
There were {$numRows} inserted into the database!
");
}
catch(PDOException $e)
{
    print("
Oops! There was an issue - this is the message: {$e->getMessage()}
");
}

?>

The result is showing me that nothing is added to the database.

A: To bind the parameters individually you would do this:
try
{
    $sql = $db->prepare($qry);
    $numRows = 0;
    foreach($vars as $insert){
        $sql->bindParam(':user_id', $insert['user_id'], PDO::PARAM_STR);
        $sql->bindParam(':comp_id', $insert['comp_id'], PDO::PARAM_STR);
        $sql->execute();
        $numRows += $sql->rowCount(); // get the rows affected this way
    }
    echo "
There were {$numRows} inserted into the database!
";
}

In addition, I added a more proper and reliable method of getting the affected rows, using rowCount().
If you don't want to bind the elements individually you can use execute() with an array as shown in Demystifying PDO


text:
Q: Ask user for SIM Card PIN I searched for a question similar to this one, but no luck.
I'm writing an app which, in order to correctly authenticate the user, it should ask him to input the correct SIM Card. Is it possible, or will I have to user another PIN just for the app authentication?

A: I am not sure if it is possible, but as there are devices out there that have no SIM (think tablets with WLAN only), it may be a better idea to have a different PIN that is not SIM-related.


text:
Q: "Download pipeline artifact" task output "Download build artifacts" task has the output variable BuildNumber that makes it possible to get the id of the build the artifact was downloaded from. The new "Download pipeline artifact" task (which is preferred over the "Download build artifacts") does not have any the output variables. Is there a way to get the id of the build the artifact was downloaded from?
Also posted an issue on GitHub.

A: Microsoft is about to release a fix.

A: There is workaround to get the build id of the downloaded artifact using restful api.
To get the BuildId of the Specific version. You can refer to below below example.
First add a powershell task in your pipeline to run below scripts.
To get the definition id provided definition name(definition id will be used in the following scripts), check here for rest API.
$urldefinition ="https://dev.azure.com/<org>/<proj>/_apis/build/definitions?name=AboutSite-ASP.NET-CI&api-version=5.1"

$result = Invoke-RestMethod -Uri $urldefinition -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Method Get
$definition= $result.value
$definitionId = $definition[0].id

Then you can get the build id with below scripts:
$url="https://dev.azure.com/<org>/<proj>/_apis/build/builds?definitions=$definitionId&buildNumber=20191109AboutSite-ASP.NET-CI&statusFilter=completed&resultFilter=succeeded&api-version=5.1"
$result = Invoke-RestMethod -Uri $urldefinition -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Method Get
$build = $result.value
$id = $build[0].id

And then you can output the buildid for the following task to use with below script:
echo "##vso[task.setvariable variable=ArtifactBuildId;isOutput=true]$id"

To get  the latest build id you can simply use below api
GET https://dev.azure.com/{organization}/{project}/_apis/build/latest/{definition}?branchName={branchName}&api-version=5.1-preview.1


text:
Q: Bash if and or conditionals I have a perl script runs in cron and if the script fails to run it leaves behind a lock file to prevent the script to run again.
I'm trying to run a bash script that checks if the process is running and checks to see if a lock file is left behind
if processes is running and lock file exists
exit 0;
if process is not running and lock file exists
rm lockfile.
exit 0;
if process does not exist and lock file is 'not present'
exit 0;
I've been checking if the process exists running
ps ax |grep -v grep |grep process.pl
I'm looking for the conditionals in bash that I should be running here.
Thanks

A: -e for "file exists":
$ if [ -e /etc/passwd ]; then echo "passwords" ; else echo "no passwords" ; fi
passwords

-n for "length of string is zero" (useful for your pidof(1) command).
$ F=$(pidof firefox-bin) ; if [ -n "$F" ]; then echo "browser" ; else echo "boring" ; fi
browser
$ F=$(pidof chrome) ; if [ -n "$F" ]; then echo "browser" ; else echo "boring" ; fi
boring

(I have firefox running, but not chrome.)

A: The process.pl should write its process id into the lockfile, wihch is a common pattern. Then you can write the following code:
if [ -f "$lockfile" ]; then
  pid=$(cat "$lockfile")
  if kill -0 "$pid"; then
    : "running normally"
  else
    : "terminated somehow"
    rm -f "$lockfile"
  fi
fi

A: Check this question for some techniques to make sure only 1 copy of script runs, in bash.

A: pgrep -f process.pl || { [ -f lock.file ] && rm lock.file; }


text:
Q: Not able to Query alphanumeric fields from ELASTIC SEARCH using TERMS QUERY I am trying to query Alphanumeric values from the index using TERMS QUERY, But it is not giving me the output.
Query:
{
  "size" : 10000,
  "query" : {
    "bool" : {
      "must" : {
        "terms" : {
          "caid" : [ "A100945","A100896" ]
        }
      }
    }
  },
  "fields" : [ "acco", "bOS", "aid", "TTl", "caid" ]
}

I want to get all the entries that has caid  A100945 or A100896
The same query works fine for NUmeric fields.
I am not planning to use QueryString/MatchQuery as i am trying to build general query builder that can build query for all the request. Hence am looking to get the entries usinng TERMS Query only.
Note: I am using Java API org.elasticsearch.index.query.QueryBuilders for building the Query.
eg: QueryBuilders.termQuery("caid", "["A10xxx", "A101xxx"]")
Please help.
Regards,
Mik

A: If you have not customized the mappings/analysis for the caid-field, then your values are indexed as e.g. a100945, a100896 (note the lowercasing.)
The terms-query does not do query-time text-analysis, so you'll be searching for A100945 which does not match a100945.
This is quite a common problem, and is explained a bit more in this article on Troubleshooting Elasticsearch searches, for Beginners.

A: You better use match query.match query are analyzed[applied default analyzer and query] like
QueryBuilders.matchQuery("caid", "["A10xxx", "A101xxx"]");


text:
Q: Ensuring Unique Json I apologise if this has been asked before but I can't seem to find a solution from other posts on here.
I'm trying to build a json array in local storage (which is fine) but want to check if an entry already exists before adding new values.
The Json itself
[{"title":"title1","url":"somefile1.pdf","background":"bg1.png"},
{"title":"title2","url":"somefile2.pdf","background":"bg2.png"},
{"title":"title3","url":"somefile3.pdf","background":"bg3.png"}]

Now how would I query the array to ensure only unique entries are being added?
Heres the code to add to array with
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

        var newItem = {
            'title': title,
            'url': url,
            'background': background
        };

        // Need to check the newItem is unique here //

        oldItems.push(newItem);
        localStorage.setItem('itemsArray', JSON.stringify(oldItems));

I thought I could use the jquery unique function instead before setting the localstorage object
var cleanedItems = $.unique(oldItems);
localStorage.setItem('itemsArray', JSON.stringify(cleanedItems));

but that didnt work...

A: You will have to loop over each of the items in the array that is parsed from local storage and perform an object equality test with the new item.
Object equality testing is not as simple as obj1 == obj2.
Here are some references to get you started

*

*http://procbits.com/2012/01/19/comparing-two-javascript-objects

*https://github.com/joyent/node/blob/e4cef1a0833e6d677298600e205a142d15639bf2/lib/assert.js#L205-L247

*http://stamat.wordpress.com/2013/06/22/javascript-object-comparison/

*http://underscorejs.org/docs/underscore.html#section-84
The following may end up working for you, by using JSON.stringify to compare the new object as a JSON string with the objects in the old array as JSON strings.
function objInArr(newObj, oldItems) {
    var newObjJSON = JSON.stringify(newObj);
    for (var i = 0, l = oldItems.length; i < l; i++) {
        if (JSON.stringify(oldItems[i]) === newObjJSON) {
            return true;
        }
    }
    return false;
}

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

var newItem = {
    'title': title,
    'url': url,
    'background': background
};

// Need to check the newItem is unique here
if (!objInArr(newItem, oldItems)) {
    oldItems.push(newItem);
}
localStorage.setItem('itemsArray', JSON.stringify(oldItems));


text:
Q: How to split a sheet of exercises in different files, one file containing just one exercise? I have a big file having the following structure :
\begin{exo}
...
\end{exo}

\begin{exo}
...
\end{exo}

My aim is to create different files containing just one exercice. How can I do this ? Does there exist a software ?

A: You could use standard latex functionality such as the import libraries and manually split up exercises into individual files. And then use either import with relatives paths via subimport, use just use the full path.
How to use the import package?
I think the main issue would be getting all the commands into separate files.
However if you wish to automatic this process, you may need to use a scripting language like python and do something similar to web scrapping using a tool like TexSoup

A: That is not really an answer but this can help you.
I have used the following pieces of code to manage a lot of questions written in different files.
\documentclass[10pt]{beamer}

\usepackage{pgffor}
\newcommand\nbquest{16}

\newcommand\dirofquest{01-no-parabola}

\begin{document}

\foreach \n in {1,...,\nbquest}{
    \begin{frame}
        \frametitle{Question FLASH no. \n}

        \Large\centering

        \input{\dirofquest/question-\n.tex}
    \end{frame}
}

\end{document}

A: Emacs users can perform this function.
(defun save-environments (env)
  "Collects all the ENV environments (default to EXO) to save them each in a separate file. Replaces each with an \input"
  (interactive
   (list (read-string "Environment: " "exo")))
  (with-current-buffer (buffer-name)
    (let ((env-number 0)
          (file-se (file-name-sans-extension (buffer-name))))
      (goto-char (point-min))

      (while
          (search-forward  (format"\\begin{%s}" env) nil t)
        (setq env-number (1+ env-number))
        (LaTeX-mark-environment)
        (kill-region (point) (mark))
        (with-temp-file (format "%s-%s-%d.tex" file-se env  env-number)
          (goto-char (point-min))
          (insert (format "%% %s-%s-%d.tex\n" file-se env env-number)
                  (format "%% From %s.tex \n\n" file-se))

          (yank))
        (insert (format "\\input{%s-%s-%d}\n" file-se env env-number))))))

It can be used for any environment, default is exo.


text:
Q: How can I select the tag-name and attributes AND values of those attributes with ONE regular expression? I have the following Regular Expression from this post (Regular expression for extracting tag attributes).
(\S+)=["\']?((?:.(?!["\']?\s+(?:\S+)=|[>"\']))+.)["\']?

I've created the following PHP code and it works nicely. I get [id='gridview1' and 'id' and 'gridview1'] from the preg_match_all() function.
$regexp = '/(\S+)=["\']?((?:.(?!["\']?\s+(?:\S+)=|[>"\']))+.)["\']?/';
$text = '<asp:gridview id=\'gridview1\' />';

$matches = null;
preg_match_all($regexp, $text, $matches);

print_r($matches);

How should the regular expression be changed to also return 'asp' and 'gridview'? (or 'Foo' and 'bAR' when i use:

<Foo:bAR />

A: ([a-zA-Z]+)\:([a-zA-Z]+)  would work for something like Foo:bar
<.*?([a-zA-Z])+.*?\:.*?([a-zA-Z])+.*?\/> would work for < Foo   :  BArrr   />
Things can be optimized depending on your requirements and whether you know that a certain type of formatting is enforced.

A: You should not be using regular expressions to parse HTML


text:
Q: Show that the following infinite series converges pointwisely Suppose $f: \Bbb R \rightarrow \Bbb R$ is a continuous function satisfies $$|f(x)| \le {1\over 1+x^2} \forall x\in \Bbb R$$
For each $n \in \Bbb N$, let $s_n: \Bbb R \rightarrow \Bbb R$ be a function such that $$s_n(x)=\sum_{k=-n}^{n}f(x+k) \forall x\in \Bbb R$$
Show that the sequence of functions $(s_n)$ converges pointwisely to a limit function $s: \Bbb R \rightarrow \Bbb R$ such that $$s(x+1)=s(x) \forall x \in \Bbb R$$
Also show that s is continuous on $\Bbb R$
I try to prove  $(s_n)$ converges pointwisely: for fixed $x$,  $$\begin{align}|s_n| & \le \sum_{k=-n}^{n}|f(x+k)| \\
& \le \sum_{k=-n}^{0}{1\over 1+(x+k)^2}+ \sum_{k=1}^{n}{1\over 1+(x+k)^2}
\end{align}$$
So I think what I really need to prove is $\sum_{k=0}^{\infty}{1\over 1+k^2}$ converges? If yes, then I just use the fact $\sum_{k=0}^{\infty}{1\over k^2}$ converges.
So I guess the expression of $s$ is $\sum_{k=-\infty}^{\infty}f(x+k)$. Hence, switching the summation index will not affect the sum, i.e. $s(x+1)=s(x)$
But how to prove $s$ is continuous? $s$ may not be uniform continuous, I cannot apply those theorems about uniform continuous.

A: You are on the right track, though your formulation ($|s_n(x)| \le \ldots$) would rather amount  to showing that $s_n$ is bounded.
For fixed $x$, we have $s_n(x)=f(x)+\sum_{k=1}^n(f(x+k)+f(x-k))$, and therefore we wonder whether the series with general term $a_k=f(x+k)+f(x-k)$ converges.
With $m:=\left\lceil \,|x|\,\right\rceil$ we see that for $k>m$ we have $a_k\le \frac2{(k-m)^2}$ and hence obtain convergence by comparison with $\sum\frac1 {k^2}$.
To show that $s$ is continuous, let us instead show that $s|_{[a,b]}$ is continuous for any closed interval $[a,b]$ (which immediately implies that $s$ is continuous as well):
Then, similar as above, as soon as $n$ is big enough, we find that $s_n-s_{n-1}$ can be bounded by something $\sim\frac1{n^2}$ on all of thge interval.


text:
Q: Switch observable on condition I have two observables and I want to use the first one unless it doesn't give me what I want (in this case an empty list). If that's the case I wwant to switch to the second one.
fun test() {

    listSource1().switchMap {
        if (it.isEmpty()) listSource2() else listSource1()
    }

}

fun listSource1() = Observable.just(emptyList<String>())

fun listSource2() = Observable.just(listOf("hello"))

Is there a better way than this? it seems strange to map listSource1 to listSource1, is this the correct way to do it?

A: FlatMap the first to see if the item is an empty list:
Observable<List<T>> source = ...

Observable<List<T>> fallbackSource = ...

source.flatMap(list -> {
    if (list.isEmpty()) {
        return fallbackSource;
    }
    return Observable.just(list);
});


text:
Q: Retrieving project version from csproj in Azure Pipeline .NET Core CLI task I have the following tasks in my yaml file in Azure DevOps
It publishes my console application and zip it in a file
- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: false
    projects: '**/MyApp.csproj'
    arguments: '-r win-x64 -p:PublishSingleFile=True --self-contained true -o $(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'
    publishLocation: 'Container'

I set the project version directly on the project file in Visual Studio when I make any changes.
Now I'm trying to get that version when I am publishing the project in AzureDevOps and customise the file name, lets say for a project version 1.2.1 the archived file output of the publish in azure should be MyApp-v1.2.1.zip
Currently it only output file as MyApp.zip
Not sure if even my approach towards versioning is correct, so appreciate any input!
Updated:
Unfortunately the provided answer didn't work for me, I can get the version but I cannot rename the file, even copying the exact script below results in the same zip file, not renamed! The folder will be renamed but the zip file stays as MyApp.zip.
I have the following script now, trying to rename using PowerShell at the end but that successfully finish executing and again results in exact the same MyApp.zip file in the drop folder

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
         $xml = [Xml] (Get-Content .\MyApp\MyApp.csproj)
         $version = $xml.Project.PropertyGroup.Version
         echo $version
         echo "##vso[task.setvariable variable=version]$version"

- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: false
    projects: '**/MyApp.csproj'
    arguments: '-r win-x64 -p:PublishSingleFile=True --self-contained true -o $(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Rename-Item -Path "$(Build.ArtifactStagingDirectory)\MyApp.zip" -NewName "$(Build.ArtifactStagingDirectory)\MyApp-Win-x64-v$(version).zip"'

However the above script doesn't work either, as if we don't have permission to change that zip file, no matter what I cannot rename it.
Fixed - Solution
I had to move the rename power shell script to before Publish Artifact

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
         $xml = [Xml] (Get-Content .\MyApp\MyApp.csproj)
         $version = $xml.Project.PropertyGroup.Version
         echo $version
         echo "##vso[task.setvariable variable=version]$version"

- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: false
    projects: '**/MyApp.csproj'
    arguments: '-r win-x64 -p:PublishSingleFile=True --self-contained true -o $(Build.ArtifactStagingDirectory)'

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Rename-Item -Path "$(Build.ArtifactStagingDirectory)\MyApp.zip" -NewName "$(Build.ArtifactStagingDirectory)\MyApp-Win-x64-v$(version).zip"'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

A: To set the name of the output file(zip file), you need to set the corresponding format in dotnet build argument.
--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)/MyApp-$(version)

In order to get the Version value in csproj file, you can add a powershell task before the Dotnet Publish task. Then you could retrieve project version from csproj
Here is my example:
- powershell: |
   $xml = [Xml] (Get-Content .\MyApp.csproj)
   $version = $xml.Project.PropertyGroup.Version

   echo $version

   echo "##vso[task.setvariable variable=version]$version"
  displayName: 'PowerShell Script'

- task: DotNetCoreCLI@2
  displayName: Publish
  inputs:
    command: publish
    publishWebProjects: false
    projects: '**/*.csproj'
    arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)/MyApp-$(version)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

Result:

You can also try to set the name as $(build.artifactstagingdirectory)/MyApp-v$(version)
The output name will be MyApp-v1.0.0.zip
Update:
I have tested your sample in Yaml Pipeline and I could reproduce this issue.
To solve this issue, you could add the parameter: modifyOutputPath: false in Dotnet Publish task.
Here is the yaml sample:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
         $xml = [Xml] (Get-Content .\MyApp\MyApp.csproj)
         $version = $xml.Project.PropertyGroup.Version
         echo $version
         echo "##vso[task.setvariable variable=version]$version"

- task: DotNetCoreCLI@2
  displayName: Publish
  inputs:
    command: publish
    publishWebProjects: false
    projects: '**/*.csproj'
    arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)/MyApp-v$(version)'
    modifyOutputPath: false

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()


text:
Q: Key Combination to Make All Instances of App the Same Window Size Is there a default Mac OSX key combination that'll make all of my open windows/instances for a given application the same dimension (height/width)? Is there a way to do this with Automator (not experienced with it enough to know if it's doable)? Or, an AppleScript script that I could initiate using a "hot-key" combination?
Scenario: I have multiple instances of the notes app open and would like to resize them to some arbitrary size, preferably stacked staggered on top of each-other.
From:

To:


text:
Q: Why the next set is not open? I hope you can help me with my next question.
Let U be a subset of a continuum X (that is, it is a connected, compact, metric space).
And let's consider the set $2^{X} = \{ U \subset X:$ U is closed and not empty$\}$.
I'm using hausdorff metric $H(A,B)= \inf \{ \epsilon>0: A \subset N(\epsilon,B)$ and  $B \subset N(\epsilon,A) \}$ for $2^{X}$, where $N(\epsilon,A)=\{x \in X:$ exists $a \in A$ such that $d(a,x)< \epsilon \}$. Note that $ N (\epsilon, A) = \cup_{a \in A} B_{d}(\epsilon, a)$ so it is an open at $ X $.
I prove that if $ U $ be an open and nonempty subset of $ X $ then the set defined by
$ C(U) = \{B \in 2^{X}: B \subset U \} $
is open of $2^{X}$.
Proof:
Let $ B \in C(U) $. By definition $ B \subset U $. And  there exists $ \delta > 0 $ such that $ N (\delta, B) \subset U $. It will now be shown that $ B_{H} (\delta, B) \subset C(U) $.
Let $ C \in B_{H}(\delta, B) $. Since $ H (C, B) < \delta $ then $ C \subset N(\delta, B) \subset U $ so $ C \in C(U) $. With this we have that given an element $ B \in C(U) $, there exists the open $ B_{H} (\delta, B) $ of $ 2^{X} $ such that $ B_{H}(\delta, B) \subset C(U) $, so  C(U) is an open at $ 2^{X} $.
My doubt is why the set $E(U)=\{B \in 2^{X}: U \subset B\}$ (where U is open)  is not open in $2^{X}$.
I really appreciate any help.


text:
Q: addEventListener('click') is executing on its own In my javascript (ES6), I have a simple  tag with an event handler, basically when the  tag is clicked I want the page to redirect.
My problem is that when I pass the URL parameter to the function that handles the redirect, the test function executes regardless of whether the addEventListener has been clicked or not, so it's basically just redirecting back and forth on its own on page load which is not what I want.
Is there any reason this.elem.addEventListener('click', this.test(this.elem.id), false); is executing on its own?
index.html:
About

about.html:
Index

Master.js:
import { Nav } from 'module/Nav';

(function() {

  Nav.init();

})();

Nav.js:
export const Nav = {

  elem: document.querySelector('.a-tag'),

  init() {
    this.render();
  },

  test(page) {
      window.location.href = "/" + page + ".html";
  },

  render() {
    if (this.elem) {
      this.elem.addEventListener('click', this.test(this.elem.id), false);
    }
  }

};

A: Because you don't pass the reference of the function, but the result of the function. You call function which redirects directly. Replace with this
this.elem.addEventListener('click', () => this.test(this.elem.id), false);


text:
Q: Pyarrow drop a column in a nested structure I would like to drop columns in my pyarrow table that are null type. Basically NullType columns are columns where all the rows have null data. I would like to drop them since they are not used by me and they cause a conflict when I import them in Spark. Here is an exemple of how I do this right now:
import pyarrow as pa

def drop_na_columns(df):
    null_columns = []
    schema = df.schema
    for (name_, type_) in zip(schema.names, schema.types):
        if type_ == pa.null():
          null_columns.append(name_)
    return df.drop(null_columns)

def create_dataframe(list_dict: dict) -> pa.table:
    fields = set()
    for d in list_dict:
        fields = fields.union(d.keys())
    dataframe = pa.table({f: [row.get(f) for row in list_dict] for f in fields})
    return drop_na_columns(dataframe)

This works fine for most of my use cases but I also have nested structures in my tables and sometimes one column in a nested structure is a null type column.
My question is to know if there is a way to identify the type of every sub-column struct, and then to drop a column in a nested structure. If any of you have an idea or has already tackled this problem I would be delighted to hear about it.
Thanks

A: It's reasonalby easy to identify which of your table columns are struct and which fields among these structs are null.
It's a bit harder to remove them though.
Here's an example:
struct_type = pa.struct([
    pa.field('ok', pa.string()),
    pa.field('bad', pa.null())
])

schema = pa.schema([
    pa.field('col1', pa.string()),
    pa.field('col2', struct_type),
])

table = pa.Table.from_arrays(
    [
        ["#0", "#1"],
        [
            ("OK1", None),
            ("OK2", None),
        ]

    ],
    schema=schema
)

You can tell that the second column is a struct by doing:
pa.types.is_struct(table.schema[1].type)
>>> True

And you can iterate through its fields:
[field.name for field in table.schema[1].type]
>>> ['ok', 'bad']

And tell which one are null:
[pa.types.is_null(field.type) for field in table.schema[1].type]
>>> [False, True]

Here's the code to recursively do what you are trying to achieve:
def get_clean_array(array):
    if pa.types.is_struct(array.type):
        if isinstance(array, pa.ChunkedArray):
            array = array.combine_chunks()
        arrays = [
            get_clean_array(array.field(index))
            for index, field in enumerate(array.type)
            if not pa.types.is_null(field.type)
        ]
        names = [
            field.name
            for field in array.type
            if not pa.types.is_null(field.type)
        ]
        return pa.StructArray.from_arrays(arrays, names)
    else:
        return array

def get_clean_table(table):

    return pa.Table.from_pydict({
        field.name: get_clean_array(table[field.name])
        for field in table.schema if not pa.types.is_null(field.type)
    })


text:
Q: ViewPager Indicator with custom ListView First, I apologise for my English since it's not really good. Thanks.
My application contains few ListWiews with Adapters. Data for the ListViews are taken from a parsed XML file located in Internet.
Now I have one TabHost with three tabs and different ListViews in each tab.
I want to change TabHost to new and slighty method - ViewPager Indicator by Jake Wharton (https://github.com/JakeWharton/Android-ViewPagerIndicator), 'cause there is awsome sliding effect.
I tried to include this code in a sample project and it's running good.
For now I have a ListView in one fragment of ViewPager and simple TextView in two others fragments. It's working.
Code of ViewPagerAdapter is shown below:
package com.formatbce.pager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.viewpagerindicator.TitleProvider;

public class ViewPagerAdapter extends PagerAdapter
implements TitleProvider
{
    private int[] scrollPosition = new int[titles.length];
private static String[] titles = new String[]
{
    "News",
    "Bio",
    "Music"
};
private final Context context;

public ViewPagerAdapter( Context context )
{
    this.context = context;
    for ( int i = 0; i < titles.length; i++ )
    {
        scrollPosition[i] = 0;
    }
}

@Override
public String getTitle( int position )
{
    return titles[ position ];
}

@Override
public int getCount()
{
    return titles.length;
}

@Override
public Object instantiateItem( View pager, final int position )
{
    if (position == 0) {
     ListView v = new ListView( context );
        String[] from = new String[] { "str" };
        int[] to = new int[] { android.R.id.text1 };
        List<Map<String, String>> items =
            new ArrayList<Map<String, String>>();
        for ( int i = 0; i < 20; i++ )
        {
            Map<String, String> map =
                new HashMap<String, String>();
            map.put( "str", String.format( "Item %d", i + 1 ) );
            items.add( map );
        }
        SimpleAdapter adapter = new SimpleAdapter( context, items,
            android.R.layout.simple_list_item_1, from, to );
        v.setAdapter( adapter );
        ( (ViewPager) pager ).addView( v, 0 );
        v.setOnScrollListener( new OnScrollListener()
        {

            @Override
            public void onScroll( AbsListView view,
                int firstVisibleItem,
                int visibleItemCount,
                int totalItemCount )
            {
                scrollPosition[ position ] = firstVisibleItem;
            }

            @Override
            public void onScrollStateChanged(AbsListView view,
                    int scrollState) {
                // TODO Auto-generated method stub

            }
        } );
        return v;}
    else {
        TextView v = new TextView( context );
        v.setText( titles[ position ] );
        ((ViewPager)pager).addView( v, 0 );
        return v;
    }
}

@Override
public void destroyItem( View pager, int position, Object view )
{
    if (position == 0){
    ( (ViewPager) pager ).removeView( (ListView) view );}
    else {
    ( (ViewPager) pager ).removeView( (TextView) view );}

}

@Override
public boolean isViewFromObject( View view, Object object )
{
    return view.equals( object );
}

@Override
public void finishUpdate( View view ) {}

@Override
public void restoreState( Parcelable p, ClassLoader c ) {}

@Override
public Parcelable saveState() {
    return null;
}

@Override
public void startUpdate( View view ) {}
}

So, with sample ListView all is good.
But my problems are starting, when I try to put there my custom ListView. In my old project this ListView has code:
package com.formatbce.mdrive;

import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class Concerts extends ListActivity {

private ArrayList<Rss_PostItem> messages;
private Rss_PostAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        messages = savedInstanceState.getParcelableArrayList("messages");
        adapter = new Rss_PostAdapter(Concerts.this, R.layout.post_entry,
                messages);
        setListAdapter(adapter);
    } else
        new GetParserResult().execute();
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Intent postActivity = new Intent(this, Rss_PostActivity.class);
    Bundle store = new Bundle();
    store.putString("title", messages.get(position).title);
    store.putString("description", messages.get(position).description);
    store.putString("link", messages.get(position).link);
    postActivity.putExtras(store);
    startActivity(postActivity);
}

protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putParcelableArrayList("messages", messages);
}

private class GetParserResult extends
        AsyncTask<Context, Integer, ArrayList<Rss_PostItem>> {
    private ProgressDialog loadingDialog;
    private Concerts_Parser parser;

    protected void onPreExecute() {
        parser = new Concerts_Parser();
        loadingDialog = ProgressDialog.show(Concerts.this, "",
                "Loading concerts list...", true);
    }

    @Override
    protected ArrayList<Rss_PostItem> doInBackground(Context... arg0) {
        return parser.parse();
    }

    protected void onPostExecute(ArrayList<Rss_PostItem> result) {
        if (result == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    Concerts.this);
            builder.setMessage(
                    "Cannot load list... \nIs Internet ON?")
                    .setCancelable(false)
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                    loadingDialog.dismiss();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            messages = result;
            loadingDialog.dismiss();
            adapter = new Rss_PostAdapter(Concerts.this,
                    R.layout.post_entry, messages);
            setListAdapter(adapter);
        }
    }
}
   }

So I don't understand, how to put it correctly in ViewPager code.
I tried to set up ListFragment, but it's a pretty new for me, so I can't get it working.
Google can't help me too, same as various developer forums.
Truly, the question is: how to get a custom ListView to be shown in ViewPager?
Thank you, I'm hope for you're help.
UPD:
Thanks to first answer, i tried to convert one of my activities to fragment with this tutorial: http://www.e-nature.ch/tech/?p=55.
First at all, it was one error that I couldn't pass: this variable isn't converted, and I don't know, how to get it working.
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

Now one other thing: when I tried to put result Fragment to FragmentPagerAdapter - I stuck finding correct code here:
@Override
public Fragment getItem(int arg0) {
    // TODO Auto-generated method stub
    return ?????????;
}

Tell me, please, what this method have to return?
Thanks!

A: you said

i have one TabHost with three tabs, and different ListView in each tab

I assume u have three different listActivity and its passed to tabHost. So convert the three activity into three Fragments.
Based on the folllowing sample code change your ViewPagerAdapter
class GoogleMusicAdapter extends FragmentPagerAdapter implements
        TitleProvider {
    public GoogleMusicAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
                    if(position ==0 )
        // return your Fragment1
                    else if(position==1)
                    // return your Fragment2
                    else
                    // return fragment3
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public String getTitle(int position) {
        if(position ==0 )
                    return "One"
                    else if(position ==1)
                    return "two"
                    else
                    return "three"
    }
}


text:
Q: Overriding SilverStripe 3 CommentsInterface.ss I've installed the comments module for my SS 3.0 blog and it's working.
But I want to override the CommentsInterface.ss template and I can't figure out where to put the overriding file. I've tried in themes/mytheme/template and themes/mytheme/templates/Includes and neither seem to work.
This should not be hard, so I must be missing something easy.
Clues?
Bob

A: Place your CommentsInterface.ss in /themes/mytheme/templates/.
Then run ?flush=all to flush your template cache so Silverstripe starts using the new template.

A: As long as I believe this need to put into mysite/templates instead of /themes/mytheme/templates/ . Not sure about the exact reason but it works for me.


text:
Q: How we get Uninstallation App Cancel event in an android I have problem in App Uninstallation. My Application Need is When user want to do application uninstall then open a login screen. when user press your right Password then show a Uninstall  App System Alert. And That Alert Have two condition (1) OK
(2) cancel. when user click "OK" then app uninstall correctly. When App Uninstalled Correctly them get a BroadcastReciver Like "android.intent.action.PACKAGE_REMOVED" . if User click a Cancel Button "How we get Any BroadcastReciver Or Notification in an android".
public class CustomBroadcastReceiver extends BroadcastReceiver {
/**
 * This method captures the event when a package has been removed
 */
@SuppressWarnings("static-access")
@Override
public void onReceive(Context context, Intent intent)
{
    System.out.println("Hello from CustomBroadcastReceiver");
    if (intent != null) {
        String action = intent.getAction();
        System.out.println("L1123 : "+action);
        if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED"))
        {
            SMContants.Removed_Apps=true;
            //Log the event capture in the log file ...
            SMContants.App_uninstalled=false;          /// Important Line
            System.out.println("The package has been removed");
        }

        else
        {
            SMContants.App_uninstalled=false;
        }
    }
}

}
when I am Write a Important Line
I want when user click on Cancel Button then value of Variable
SMContants.App_uninstalled=false;
How we Get the App Uninstallation Cancel Button Event


text:
Q: Could PCA be used to combine multiple rankings? I have n (in my case just 9) different ranking of the same items. Now, I'm trying to find a combination using PCA (Principal Component Analysis), in order to improve the accuracy of my ranking. The method should be unsupervised, that is I'd like to generate new ranking based.
My idea is to try all the possible subset (without repetitions) of the 9 different ranking and run PCA for every of that. There for I will come out with 501 different new ranking (in the case of n=9). With different subset I obtain better results.
When I say better results I mean that I have the true ranking and when I finish the combination I compare the result of all the ranking (combined and the original 9).
Is this method makes sense?

A: Your question involves a subset of voting theory and there are many possibilities on how to solve this. Some of the techniques are more flexible than others. For example, some techniques can accomodate ordered rankings of variable sizes (imagine one ranking only contained 5 ordered items, while the other rankings contained 9 ordered items) while others cannot. Some techniques can assign variable weights to the different reviewers. Netflix has very complex proprietary algorithms they use to combine multiple users' movie rankings into overall rankings. That being said, I would say your combinatorial PCA approach does not strike me as either computationally efficient or terribly relevant. If you are taking information from only a subset of your 9 rankings, you are potentially discarding useful (although perhaps subtle) information.

*

*Schulze method: Somewhat complex, but widely regarded as one of the best ways to pick a single winner from a set of rankings. Could be applied iteratively or otherwise modified to get an ordered list of winners.

*Borda count: Several variations, all of which are quite simple and intuitive and usually lead to reasonable results.

Perhaps the biggest problem with the Borda count is that it does not adaquately handle the different standard deviations of two items that may have very similar average rankings. If we constrain ourselves to the subset of problems where all ordered rankings are of the same size and all have equal weight, I can recommend one method that is intuitive and leads to very good results across a wide range of cases: Aggregate Z-score Minimization.  This works as follows:

*

*For each one of the ranked items, compute the mean μ and standard deviation σ of its rankings (assume a Gaussian distribution).

*Next compute the |z-score| "distance" matrix for every item to every possible ranking position. Z-score = (proposed ranking position - μ) / σ

*Then exhaustively calculate which set of ranking positions give the lowest aggregate (total) z-score distance.

Effectively, the ranking problem is converted into a classification problem where we are trying to classify each ranking position into the best fitting sampled distribution of each item. The constraint is that only one ranking position can be assigned to each Gaussian item distribution. By minimizing the aggregate z-score distance globally, we are finding the most statistically likely configuration for the "true" ranking.
If you don't want to do the programming to exhaustively calculate the combinatorial sums of step 3, there is a heuristic method I'll demonstrate here that usually gives good results (but not guaranteed to be the best solution).
Consider we have 4 independent rankings of 6 items (A-F) here. Assume the first item listed in each ranking is at ranking position #1:
 1. A,C,F,E,B,D
 2. D,B,C,E,F,A
 3. F,A,B,C,D,E
 4. E,A,C,B,D,F

Next compute the mean and standard deviation of each item's ranking positions:

A: (#1, #6, #2, #2); μ = 2.75, σ = 2.217
  B: μ = 3.5, σ = 1.291
  C: μ = 3.0, σ = 0.816
  D: μ = 4.25, σ = 2.217
  E: μ = 3.75, σ = 2.062
  F: μ = 3.75, σ = 2.217

We can see from the relatively tight spread of means (2.75 to 4.25) that all of the items are contending for about the same average, middle positions. This is a case where the Borda count may tend to perform poorly because the standard deviations become extra important when the averages are all so close. So next, we create the matrix of z-score distances from each item to each possible ranking position:
A: 0.7892, 0.3382, 0.1127, 0.5637, 1.0147, 1.4657
B: 1.9365, 1.1619, 0.3873, 0.3873, 1.1619, 1.9365
C: 2.4495, 1.2247, 0.0000, 1.2247, 2.4495, 3.6742
D: 1.4657, 1.0147, 0.5637, 0.1127, 0.3382, 0.7892
E: 1.3339, 0.8489, 0.3638, 0.1213, 0.6063, 1.0914
F: 1.2402, 0.7892, 0.3382, 0.1127, 0.5637, 1.0147

It's probably obvious, but in the event you had any item with σ = 0, you can assign that item to its exclusive ranking position immediately. Now if you don't want to exhaustively solve this matrix for the ranking combination with the lowest possible aggregate z-score assignment, you can use this heuristic. Sum each column, and then subtract the minimum value from that column to get a value we can call "savings":
sum: 9.2151, 5.3777, 1.7658, 2.5225, 6.1344, 9.9718
min: 0.7892, 0.3382, 0.0000, 0.1127, 0.3382, 0.7892
savings: 8.4259, 5.0395, 1.7658, 2.4098, 5.7962, 9.1826

Take the column with the largest "savings" value and assign the item with the min value to that position. In our example here, this means we will assign the item "D" to the 6th position. After doing this, recompute the sum, min, and savings values, but first remove the "D" item's row and also remove the 6th column (because they have already been assigned). Then assign the new largest "savings" value to the item with the min value in that column. Continue until all rankings are assigned. In this example, the final (heuristic) ranking will be as follows: A, E, C, B, F, D (aggregate z-score: 3.3783). I didn't check my work, but it looks like the exhaustively solved solution of A, F, C, B, E, D (aggregate z-score: 3.3612) might be 0.5% better than the heuristic solution.
It's worth noting that the naive solution where we just simply ordered the means A, C, B, E, F, D (aggregate z-score: 3.8754) is substantially less likely (statistically) to be the best ranking.


text:
Q: zgrep for multiple pipe symbols in a bunch of gz files I have a lot of .gz files in a folder
/a/b/c1.gz
/a/b/c2.gz
/a/b/c3.gz

and so on.
Some of the files have a single pipe delimiter, some have two, three and four and so on, in such a way:
xyz|abc
xyz|abc|wty
xyz|abc|wty|asd

and so on.
How do I find all the files that have two pipe delimiters overall, three delimiters overall etc ?

A: Assuming that in any given file, the number of |-delimited columns is constant, then it's enough to inspect the first line of a file to determine the number of columns in it.
The following will do that for a file called name.gz:
gzip -dc name.gz | awk -F '|' -v name="name.gz" '{ print NF, name } { exit }'

So, with a simple loop, you would be able to output the number of columns and the filenames of, e.g., all files matching the pattern /a/b/c*.gz:
for name in /a/b/c*.gz; do
    gzip -dc "$name" |
    awk -F '|' -v name="$name" '{ print NF, name } { exit }'
done

If you want to only output the names of the files with a certain number of columns (n=3, for example), then use
n=3
for name in /a/b/c*.gz; do
    gzip -dc "$name" |
    awk -F '|' -v n="$n" -v name="$name" 'NF == n { print name } { exit }'
done

A: You can pipe file names to awk and find number of |-s in each.  For example:
echo 'A|B|C' |awk -F\| '{print NF-1}'

A: Let's create three test files:
echo 'xyz|abc' > c1
echo 'xyz|abc|wty' > c2
echo 'xyz|abc|wty|asd' > c3
gzip c*

Files containing one pipe in a line:
$ zgrep '^[^|]*|[^|]*$' *.gz
c1.gz:xyz|abc

For any other numbers (including one pipe in a line), you can use the following pattern:
Two pipes in a line:
$ zgrep -E '^([^|]*\|){2}[^|]*$' *.gz
c2.gz:xyz|abc|wty

Three pipes in a line:
$ zgrep -E '^([^|]*\|){3}[^|]*$' *.gz
c3.gz:xyz|abc|wty|asd

Two or three pipes in a line:
$ zgrep -E '^([^|]*\|){2,3}[^|]*$' *.gz
c2.gz:xyz|abc|wty
c3.gz:xyz|abc|wty|asd

Max. three pipes in a line:
$ zgrep -E '^([^|]*\|){,3}[^|]*$' *.gz
c1.gz:xyz|abc
c2.gz:xyz|abc|wty
c3.gz:xyz|abc|wty|asd

If you only need the filename, add option -l, i.e. zgrep -lE ...

My zgrep version doesn't support the recursive -r option.
You could use find for a recusive search and run zgrep on the result:
$ find . -type f -name '*.gz' -exec zgrep -lE '^([^|]*\|){3}[^|]*$' {} \;
./c3.gz


text:
Q: adding Colon (:) in each line of the file Input :
126211  consecutive prog runs error logged debug core
126262  manual change memory view propagated views like variable view expression view

Output
126211 : consecutive prog runs error logged debug core
126262 : manual change memory view propagated views like variable view expression view

Code
def function_1():
    filename = open('input.txt', 'r')
    for line in filename:
        #print line
        line = line.rstrip('')
        #line1= re.sub('[^\w ]','',line)[8:]
        #print line1

Problem is I need to read the first digit of each line and add a Colon (:) with space in both sides. Any suggestion will be appreciated. Thanks.

A: Split on the first whitespace encountered:
def function_1():
    with open('input.txt') as f:
        for line in f:
            number, rest = line.split(None, 1)
            print '{} : {}'.format(number, rest.rstrip())

.split(None, 1) splits on arbitrary-width whitespace, but only once, leaving you with the number and the rest of the line in two variables.

A: @Martijn Pieters already gave the right answer, but just in case there are always 6 digits and 2 spaces, note that you can use print line[:6], ':', line[8:] too.


text:
Q: xslt: convert elements to attributes - returns last elements as attributes only Attempting to convert elements to attributes of the elements parent node but the code only returns the last elements in the list as attributes
Sample of XML
    <?xml version="1.0" encoding="UTF-8"?>
<NB xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Users/xXXXXXX/Documents/xxxxx%20Profile%20XML/Untitled13.xsd">
    <Profile>
        <PName>165370 - XXX - XXXXXX</PName>
        <OrderID>165370</OrderID>
        <Status>I</Status>
        <OrderInst/>
        <TopicInst>OMIT MERE MENTIONS</TopicInst>
        <KeywordInst>
            <OrderKWs>
                <KW>KEEPHILLS</KW>
                <KWInst>ICW KEEPHILLS POWER PLANT
OR ICW POWER GENERATION AT KEEPHILLS PLANT</KWInst>
                <KW>SUN 7 PLANT</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE 7 GAS PLANT</KW>
                <KWInst>ICW POWER PLANT
OR ICW POWER GENERATION</KWInst>
                <KW>SUNDANCE AND COAL</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE AND ELECTRIC</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE AND ELECTRICAL</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE AND ELECTRICITY</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE AND GAS</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE AND GENERATION</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE AND PLANT</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE AND POWER</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>SUNDANCE UNIT</KW>
                <KWInst>ICW SUNDANCE GAS FIRED POWER PLANT
OR ICW SUNDANCE COAL FIRED POWER PLANT
OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT
OMIT SUNDANCE FILM FESTIVAL</KWInst>
                <KW>WABAMUN</KW>
                <KWInst>ICW WABUMUM POWER PLANT
OR ICW POWER GENERATION AT WABUMUM PLANT</KWInst>
            </OrderKWs>
        </KeywordInst>
    </Profile>
</NB>

XSD
    <?xml version="1.0" encoding="UTF-8"?>
<!-- W3C Schema generated by XMLSpy v2018 sp1 (http://www.altova.com) -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="KW" type="xs:string"/>
    <xs:element name="NB">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="Profile"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="PName">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="165370 - XXX - XXXXXX"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="KWInst" type="xs:string"/>
    <xs:element name="Status">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="I"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="OrderID" type="xs:int"/>
    <xs:element name="Profile">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="PName"/>
                <xs:element ref="OrderID"/>
                <xs:element ref="Status"/>
                <xs:element ref="OrderInst"/>
                <xs:element ref="TopicInst"/>
                <xs:element ref="KeywordInst"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="OrderKWs">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
                <xs:element ref="KW"/>
                <xs:element ref="KWInst"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="OrderInst">
        <xs:complexType/>
    </xs:element>
    <xs:element name="TopicInst">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="OMIT MERE MENTIONS"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="KeywordInst">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="OrderKWs"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSLT
    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:math="http://www.w3.org/2005/xpath-functions/math" xmlns:array="http://www.w3.org/2005/xpath-functions/array" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:err="http://www.w3.org/2005/xqt-errors" exclude-result-prefixes="array fn map math xhtml xs err" version="3.0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <xsl:apply-templates mode="copy" select="."/>
    </xsl:template>
    <xsl:template match="*|text()|@*" mode="copy">
        <xsl:copy>
            <xsl:apply-templates mode="copy" select="@*"/>
            <xsl:apply-templates mode="copy"/>
        </xsl:copy>
    </xsl:template>
 <xsl:template match="//KeywordInst" mode="copy">
        <xsl:copy>
            <xsl:apply-templates mode="convert-to-attr" select="OrderKWs/*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*" mode="convert-to-attr">
        <xsl:attribute name="{name()}" select="text()"/>
    </xsl:template>
</xsl:stylesheet>

The Output XML
    <?xml version="1.0" encoding="UTF-8"?>
<NB xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Users/gary.larose/Documents/Newbase%20Profile%20XML/Untitled13.xsd">
    <Profile>
        <PName>165370 - XXX - XXXXXX</PName>
        <OrderID>165370</OrderID>
        <Status>I</Status>
        <OrderInst/>
        <TopicInst>OMIT MERE MENTIONS</TopicInst>
        <KeywordInst KW="WABAMUN" KWInst="ICW WABUMUM POWER PLANT
OR ICW POWER GENERATION AT WABUMUM PLANT"/>
    </Profile>
</NB>

Expected Output:
    <?xml version="1.0" encoding="UTF-8"?>
<NB xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Users/gary.larose/Documents/Newbase%20Profile%20XML/Untitled13.xsd">
    <Profile>
        <PName>165370 - XXX - XXXXXX</PName>
        <OrderID>165370</OrderID>
        <Status>I</Status>
        <OrderInst/>
        <TopicInst>OMIT MERE MENTIONS</TopicInst>
        <KeywordInst  KW="KEEPHILLS" KWInst="ICW KEEPHILLS POWER PLANT OR ICW POWER GENERATION AT KEEPHILLS PLANT"</>
        <KeywordInst KW="SUN 7 PLANT" KWInst="ICW SUNDANCE GAS FIRED POWER PLANT OR ICW SUNDANCE COAL FIRED POWER PLANTOR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANTOMIT SUNDANCE FILM FESTIVAL"</>
        <KeywordInst KW="SUNDANCE 7 GAS PLANT" KWInst="ICW POWER PLANT OR ICW POWER GENERATION"</>
        <KeywordInst KW="SUNDANCE AND COAL" KWInst="ICW SUNDANCE GAS FIRED POWER PLANT OR ICW SUNDANCE COAL FIRED POWER PLANT OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT OMIT SUNDANCE FILM FESTIVAL"</>
        <KeywordInst KW="SUNDANCE AND ELECTRIC" KWInst="ICW SUNDANCE GAS FIRED POWER PLANT OR ICW SUNDANCE COAL FIRED POWER PLANTOR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANTOMIT SUNDANCE FILM FESTIVAL"</>
        <KeywordInst KW="SUNDANCE AND ELECTRICAL" KWInst="ICW SUNDANCE GAS FIRED POWER PLANT OR ICW SUNDANCE COAL FIRED POWER PLANT OR ICW ELECTRICAL POWER GENERATION AT SUNDANCE PLANT OMIT SUNDANCE FILM FESTIVAL"</>
        ......
        <KeywordInst KW="WABAMUN" KWInst="ICW WABUMUM POWER PLANT
OR ICW POWER GENERATION AT WABUMUM PLANT"/>
    </Profile>
</NB>

The attribute KW="WABAMUN" and KWInst="ICW...." are the last pair in the sample xml file.  My target file has 150k lines of the same structure, and when I run this XSLT on the target file, the Output (as sampled) appears to always be the last pair of KW and KWInst in the list within the Profile entity.
thank you for your help.
G

A: If you know the name of the (first) element (e.g. KW) to form a new KeywordInst element then I think with XSLT 2 or 3 the easiest way is to use e.g. for-each-group starting-with="KW" so with XSLT 3 this becomes
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:output indent="yes"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="KeywordInst">
      <xsl:for-each-group select="OrderKWs/*" group-starting-with="KW">
          <xsl:copy select="../..">
              <xsl:apply-templates select="current-group()" mode="element-to-attribute"/>
          </xsl:copy>
      </xsl:for-each-group>
  </xsl:template>

  <xsl:template match="*" mode="element-to-attribute">
      <xsl:attribute name="{name()}" select="."/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/nc4NzPY
With XSLT 2 you need to spell out the identity transformation instead of using the xsl:mode declaration and you don't have xsl:copy select so you need to use other means like e.g. hardcoding the name with
  <xsl:template match="KeywordInst">
      <xsl:for-each-group select="OrderKWs/*" group-starting-with="KW">
          <KeywordInst>
              <xsl:apply-templates select="current-group()" mode="element-to-attribute"/>
          </KeywordInst>
      </xsl:for-each-group>
  </xsl:template>

but the grouping remains the same.


text:
Q: Slow DTLS handshake in case of packet loss I implemented a DTLS server using openssl. (I have an udp socket and I am using a memory bio to communicate with openssl.) However if there is packet loss the DTLS handshake could take 1-2 seconds, which is a lot in my case.
The normal flow when there is no packet loss: (few milliseconds)
Client Hello ------------------------->
             <------------------------- Server Hello
Rest of the handshake ---------------->
                      <---------------- Rest of the handshake

The flow I am experiencing: (few seconds)
Client Hello ------------------------->
             <-------(lost)------------ Server Hello
Client Hello ------------------------->
Client Hello ------------------------->
Client Hello ------------------------->
             <------------------------- Server Hello
Rest of the handshake ---------------->
                      <---------------- Rest of the handshake

I can easily reproduce it even in local environment directly dropping the first Server Hello.
I am curious why the server does not respond to some several upcoming Client Hello's.
If it would answer the handshake could complete well below 1 second but this way it takes up 1-2 seconds, when it finally answers again for later Client Hello's.
How could I make the DTLS handshake complete faster? (by enabling answer for all Client Hello's for example, is there a way?)

A: In OpenSSL the default DTLS rentransmit timer starts at 1 second and periodically doubles that if it has not received a response. In your case the server has sent its ServerHello (and presumably ServerHelloDone and maybe other messages - but you don't show that) and is now waiting for the ClientKeyExchange message. Any subsequent ClientHellos received from the same peer are assumed to be stale retransmits and ignored.
You can get the server to operate statelessly using DTLSv1_listen() which means that the server will listen for connections from any peer and assume any ClientHello coming in is from a new peer and immediately respond to it - although in this case it adds an additional roundtrip because all ClientHello's are required to have a "cookie" in them. It also wouldn't solve any issues with packet loss later in the handshake - so it doesn't really help your problem here.
From OpenSSL 1.1.1 you can use a custom DTLS timer callback to control the timeouts on the timer via DTLS_set_timer_cb():
https://www.openssl.org/docs/man1.1.1/man3/DTLS_set_timer_cb.html
Here's an example which sets the initial timer to be 50ms and periodically doubles it (50ms is probably too short for a network based implementation - but this particular example is an "in memory" test):
https://github.com/openssl/openssl/blob/20c98cd45399423f760dbd75d8912769c6b7b10e/test/dtlstest.c#L45-L53
Be careful not to set the timeout too low because you might start flooding your network with large numbers of spurious retransmits.