text:
Q: Running commands on OS terminal after creating ubuntu via webtop Is there any way to modify this docker-compose file so to be able to make a few commands to be executed after the Ubuntu instance boots up?
version: "2.1"
services:
  webtop:
    image: linuxserver/webtop:ubuntu-mate
    container_name: webtop
    security_opt:
      - seccomp:unconfined #optional
    environment:
      - PUID=1000
      - PGID=1000
      - TZ=Europe/Spain
      - SUBFOLDER=/ #optional
      - KEYBOARD=en-us-qwerty #optional
      - TITLE=Webtop #optional
    volumes:
      - /path/to/data:/config
      - /var/run/docker.sock:/var/run/docker.sock #optional
    ports:
      - 3000:3000
    devices:
      - /dev/dri:/dev/dri #optional
    shm_size: "1gb" #optional
    restart: unless-stopped

For example, I want apt update and apt upgrade to be executed after Ubuntu boots up.


text:
Q: jquery sort a list according to div element status I have got a list contains a div on each line. One of the elements of each div is a label. Labels contain in/out information for markers located in a map (also in a shaded area). I want them to be sorted according to labels in/out status. What I have done so far is having the code below.
Users can change the scale of the shaded area which changes the status of the markers. Therefore, the list should be updated according to the markers' status on the map. All the markers IN should be on top of the list and the outs should be placed after 'INs'.
**I have got method doing this with 30 lines.I want to use this method.
A is my test loop code to ensure that I am having my in/Out labels html property correctly.
B is the code which is not working at the moment. Can anyone familiar please have a look what is missing in the code.
Thanks in advance.
Html  Code

    <input type="checkbox" name="checkbox_13A  North Buderim Bvd Buderim" id="4" value="13A North Buderim Bvd Buderim">
    13A  North Buderim Bvd Buderim
    In

PS: List is sth like this.
checkbox | address1 | In
checkbox | address2 | Out
checkbox | address3 | In
checkbox | address4 | Out
A)
$(this.children()).each(function (ind){

      var html = $(this).children().filter(".inOutControl").html();
      alert(html);
});

B)
   $("#list").sort(sortTest);

        var sortTest = function(a,b){
            //return $(a).find(".inOutControl").html() > $(b).find(".inOutControl").html() ? 1 : -1;
            return $(this, a).filter(".inOutControl").html() != $(this, b).filter(".inOutControl").html() ? 1 : -1;
        };

PS: Similar to this, but I don't know why it is not working.

A: This works..just in case if anyone needs it...
$("#list").sortList();

$.fn.sortList = function(){
        var $list = $(this);
        var listItems = $list.children().get();
        listItems.sort( function(a,b){
            return $( a).find(".inOutControl").html() > $( b).find(".inOutControl").html() ? 1 : -1;
        });
        $.each(listItems, function(idx, itm){$list.append(itm);});
        return this;
    };

redpajama_set_name: RedPajamaStackExchange


text:
Q: Не получается отправить картинку на socket клиент Java android с сервера Python Есть клиент на Java android socket и сервер на Python socket. С сервера я передаю массив байт на клиент, но после передачи, файл не полный и не открывается. Вот код:
Клиент:
//--подключение к серверу
BufferedReader In = new BufferedReader(new InputStreamReader(socket.getInputStream()));
FileOutputStream fos = openFileOutput("photo.png", MODE_PRIVATE); //создание файла
String in = In.readLine(); //чтение размера картинки
int size = Integer.parseInt(in); //преобразование в int
DataInputStream dIn = new DataInputStream(socket.getInputStream());
byte[] bytes = new byte[5*1024];
int count, total=0;
while ((count = dIn.read(bytes)) > -1) {
    total+=count;
    fos.write(bytes);
    if (total==size) break;
}
fos.close();

Сервер:
#-- создание сервера
f = open('photo.png', 'rb')
b = f.read()
conn.send((str(len(b)) + '\r\n').encode()) #отправка размера картинки
conn.send(b) #отправка байтов
conn.send('\r\n'.encode()) #завершение строки

Может я не так передаю или не так записываю в файл?


text:
Q: Como contar acessos únicos semanais em MySQL Tenho essa consulta em MySQL para verificar os acessos únicos a um sistema meu:
SELECT COUNT(DISTINCT id_usuario) AS total, dia FROM acesso
WHERE (dia BETWEEN '2018-01-21' AND '2019-01-21')
GROUP BY dia
ORDER BY dia ASC

E ao meu ver ele está listando certo os acessos únicos ao sistema.
Minha dúvida: o cliente pediu para checar os acessos únicos semanais, ou seja, se o usuário acessar ao menos 1 única vez durante o período de 1 semana, já contaria o acesso dele, como fazer? Tentei assim, mas o total acaba dando menor que o acesso único diário:
SELECT COUNT(DISTINCT id_usuario) AS total, dia FROM acesso
WHERE (dia BETWEEN '2018-01-21' AND '2019-01-21')
GROUP BY WEEK(dia)
ORDER BY dia ASC

A: Se você fizer esta query, vai criar uma tabela analítica com os distintos numa determinada semana, filtrando por intervalo de datas
SELECT id_usuario, week(dia) as semana FROM acesso
WHERE dia  BETWEEN '2019-01-01' and '2019-04-16'
group by id_usuario, week(dia)

Com base nestes resultados, você pode contar os distintos neste intervalo de tempo
SELECT count(distinct id_usuario) as total from (SELECT id_usuario, week(dia) as semana FROM acesso
WHERE dia  BETWEEN '2019-01-01' and '2019-04-16'
group by id_usuario, week(dia)) T

A: Se você deseja saber apenas o total de acessos nos últimos 7 dias, pode fazer desta forma:
SELECT COUNT(DISTINCT id_usuario) AS total FROM acesso
WHERE dia  >= (DATE(NOW()) - INTERVAL 7 DAY)


text:
Q: Showing a time-series track (moving object) in SVG I want to display a time series track using SVG in two different modes. One mode would show a dot where the location of the object is at different times, and another mode would show all the locations (every dot).
So, for example, at the bottom of the screen there might be 4 buttons: "Time 1", "Time 2" and "Time 3" and "Show All". If you clicked on one of the times, it would just show where the object was at that time, but if you click on the "show all" button, then all the dots are displayed at the same time.
What is the best way to set this up in SVG? I can draw dots, but I am unsure of the best methods for using Javascript to do animations/hidings like this.


text:
Q: How many partitions can be created for linux on GPT? I know it's up to 128 for windows OS. Does the same limit apply to Linux? So this limit is actually a limit of GPT?

A: The 128 is the default setting for number of entries in the partition table header. That controls how large the partition table & backup partition table is. It can default to smaller numbers for small drives and can be adjusted to have even more.
https://en.wikipedia.org/wiki/GUID_Partition_Table
Full specification is part of UEFI specification.
https://uefi.org/specifications
Apple information:
https://developer.apple.com/library/archive/technotes/tn2166/_index.html
Intel information:
https://www.intel.com/content/www/us/en/architecture-and-technology/unified-extensible-firmware-interface/efi-specifications-general-technology.html
See also
man gdisk

Gdisk will only convert 128 MBR partitions to gpt.

A: The Windows FAQ on this says

The specification allows an almost unlimited number of partitions. However, the Windows implementation restricts this to 128 partitions. The number of partitions is limited by the amount of space reserved for partition entries in the GPT.

so the 128 is Windows-specific.
For Linux, as explained here, the limitation comes usually from DISK_MAX_PARTS, which is 256, so 255 is the maximum number of partitions. I'd assume that this applies to all partition schemata, not only GPT.
I do not know if anything else would break if you just increase this number, and recompile the kernel with it.


text:
Q: IN mysql with fractional values SELECT * FROM salers WHERE comm IN (0.12, 0,13, 0.15);

query returns an empty set while any other queries returns values. Where do I make mistake here?

A: "Fractional" values are represented either as fixed-point values (decimal) or as floating point values.  The latter are very troublesome when used with equality operations.
So, in addition to the mistake with the comma, this can be dangerous if comm is double or float.  You may find that this works better:
where cast(comm as decimal(10, 2)) in (0.12, 0.13, 0.15)

Or, preferably, you can look for a range:
where comm > 0.11 and comm < 0.16

A: Your mistake is at : 0,13
Change to:
SELECT * FROM salers WHERE comm IN (0.12, 0.13, 0.15);


text:
Q: Unable to open vs2015 .net core 1.1 project after installing vs2017 I was working in vs2015 with .net core 1.1 a few months back.  I upgraded to vs2017.  I had some problems getting vs2017 to work while vs2015 was installed, I finally got it to work by uninstalling vs2015 and vs2017 and just installing vs2017.
Today I was tasked with working on a vs2015 project which they do not wish to upgrade to vs2017 at this time.
First obstacle was just organization - you see the TFS structure is like this:
-Root
+ Project A ( vs2015 )
+ Project B ( vs2015 )
+ Project C ( vs2017 )
+ Project D ( vs2015 )

VS and TFS will not allow me to change the local directory form c:\Root\Project C to c:\Root\VS2015\Project B -- oh well.
I reinstalled VS2015 with service pack 3.  Fired it up and downloaded a vs2015 project from TFS.  The problem comes when I try to open it.  When I open the Solution from Source Control Explorer I get this error:

Clicking OK opens the Migration report in my browser:

Clicking on any of the links (Migration Report Link) goes to a page about ".NET Core installation guide".
I navigated to the vs2015 version and re-downloaded the .net installation exe, but when I ran it I only had an option to repair, which I did but didn't help.
My solution remains in this broken state, unable to open the projects in the solution:

Right clicking on any of the projects and trying to reopen the project brings up the migration report error again.
I did find a similar reported issue at Visual Studio 2017 install breaks Visual Studio 2015 ASP.NET Core Projects

but my solution did contain a gloabl.json file in the root and changing the contents of the file from:
{
  "projects": [ "src", "test" ],
  "sdk": {
  }
}

to:
{
  "projects": [],
  "sdk": {
    "version": "1.0.0-preview2-003131"
  }
}

Didn't help.  I also ran a dotnet --version and got the result 1.03 and used that in the version string, but still no joy.
Any ideas on how to open these vs205 .net core projects?   I also read that others who have had this issue that uninstalling vs2015 and vs2017 and just reinstalling vs2015 does not help either.

A: The issue turned out to be an incompatible .net core installation.  I had the newest .net core installed but the project will only open with
"DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe".


text:
Q: nmcli for vpn pptp connection from command line . centos 7 i use to connection vpn from command line

my os centos 7
how i can install it org.freedesktop.NetworkManager.pptp
if i start connection

[root@vps4910 ~]# nmcli connection up VPN_2
    Error: Connection activation failed: The VPN service 'org.freedesktop.NetworkManager.pptp' was not installed.
    [root@vps4910 ~]#

A: Resolved by @annahri

just install this

yum install epel-release
sudo yum install NetworkManager-pptp


text:
Q: Java: Recursive reheapUp (bubbleUp) method for Heap data structure I've been trying to write a recursive method that reshapes a heap data structure when an element is enqueued, but I cannot get it to work correctly.
I was able to get a perfectly working recursive reheapDown method, so I have no idea why this one won't work. Here is the class I've been working on, which includes the iterative version of reheapUp which I'm using as a template for designing the recursive version:
public class Heap<T extends Comparable<T>> implements PriQueueInterface<T>
{
  private ArrayList<T> elements;  // priority queue elements
  private int lastIndex;          // index of last element in priority queue
  private int maxIndex;           // index of last position in ArrayList

  public Heap(int maxSize)
  {
    elements = new ArrayList<T>(maxSize);
    lastIndex = -1;
    maxIndex = maxSize - 1;
  }

  public boolean isEmpty()
  // Returns true if this priority queue is empty; otherwise, returns false.
  {
    return (lastIndex == -1);
  }

  public boolean isFull()
  // Returns true if this priority queue is full; otherwise, returns false.
  {
    return (lastIndex == maxIndex);
  }

  private void reheapUp(T element)
  // Current lastIndex position is empty.
  // Inserts element into the tree and ensures shape and order properties.
  {
    int hole = lastIndex;
    while ((hole > 0)    // hole is not root and element > hole's parent
           &&
      (element.compareTo(elements.get((hole - 1) / 2)) > 0))
      {
      // move hole's parent down and then move hole up
      elements.set(hole,elements.get((hole - 1) / 2));
      hole = (hole - 1) / 2;
    }
    elements.set(hole, element);  // place element into final hole
  }

  private void recReheapUp(T element)
  {
    int hole = lastIndex;

    //hole is not root and element > hole's parent
    if (hole > 0)
    {
      if (element.compareTo(elements.get((hole - 1) / 2)) > 0)
      {
        elements.set(hole,elements.get((hole - 1) / 2));
        hole = (hole - 1) / 2;
      }
    }

    //base condition
    if (hole == 0 && element.compareTo(elements.get((hole - 1) / 2)) <= 0))
    {
      elements.set(hole, element);  // place element into final hole
      return;
    }

    recReheapUp(element);
  }

  public void enqueue(T element) throws PriQOverflowException
  // Throws PriQOverflowException if this priority queue is full;
  // otherwise, adds element to this priority queue.
  {
    if (lastIndex == maxIndex)
      throw new PriQOverflowException("Priority queue is full");
    else
    {
      lastIndex++;
      elements.add(lastIndex,element);
      recReheapUp(element);
    }
  }

The reheapUp() and recReheapUp() methods are called whenever an item is enqueued into the heap. I've reworked the recReheapUp() method so many times it's not even worth posting all the changes I've attempted.
I will say that I think the issue lies in my base case, although there may be logical flaws in the general case as well.
I keep getting stack overflow errors no matter what I do, which tells me the recursive method isn't terminating properly. I just recently switched to nested if statements for my recursive method, but I'm not sure if that helped or hurt my cause.

A: Looks like you're getting stuck in unbounded recursive calls not because there's anything wrong with your base case (although I'm not sure I understand what the inner comparison is for), but because you're effectively calling Heapify on the same element. Your recursive algorithm should know the index of the current element that may need to sift. Something like this:
private void insert(ArrayList<T> heap, T element) {
  head.add(element);
  heapify(heap, heap.size() - 1);
}

private void heapify(ArrayList<T> heap, int location) {
  int parent = (location - 1) / 2; // -1 for zero-indexed language
  // same-element comparison is OK. This will always happen at the root.
  if (heap.get(parent).compareTo(heap.get(location)) > 0) {
    swap(heap, location, parent);
    heapify(heap, parent);
  }
}

private void swap(ArrayList<T> heap, int a, int b) {
  T temp = heap.get(a);
  heap.set(a, heap.get(b));
  heap.set(b, temp);
}

CLRS has a really excellent discussion on Heaps on pages 151-159.


text:
Q: CloudWatch Insights By Date I'm trying to create a CloudWatch Insights query for Amazon Connect that will give me call counts by date. I'm able to get the number of log messages by date, however, I need to only count unique ContactId's. The query I have has many duplicated ContactId's since each time Connect logs to CloudWatch, it uses ContactId to tie all of the events related to a contact together. Is there a way to modify this query to only show the count of the unique ContactId?
filter @message like /ContactId/
| stats count(*) as callCount by toMillis(datefloor(1d))
| sort callCount desc

A: Embarassingly enough, almost immediately after posting this, I found my answer. count_distinct() gets me what I needed.
filter @message like /ContactId/
| stats count_distinct(ContactId) as callCount by toMillis(datefloor(1d))
| sort callCount desc


text:
Q: Share dynamic tables between Flink programs I have a Flink job that creates a Dynamic table from a database changelog stream. The table definition looks as follows:
tableEnv.sqlUpdate("""
      CREATE TABLE some_table_name (
          id INTEGER,
          name STRING,
          created_at BIGINT,
          updated_at BIGINT
      )
      WITH (
          'connector' = 'kafka',
          'topic' = 'topic',
          'properties.bootstrap.servers' = 'localhost:9092',
          'properties.zookeeper.connect' = 'localhost:2181',
          'properties.group.id' = 'group_1',
          'format' = 'debezium-json',
          'debezium-json.schema-include' = 'true'
      )
    """)

When trying to reference that table in another running Flink application on the same cluster,  my program returns an error: SqlValidatorException: Object 'some_table_name' not found. Is it possible to register that table somehow such that other programs can use it? For example in a statement like this:
  tableEnv.sqlQuery("""
    SELECT count(*) FROM some_table_name
  """).execute().print()

A: Note that a table in Flink doesn't hold any data. Another Flink application can independently create another table backed by the same Kafka topic, for example . So not sharing tables between applications isn't as tragic as you might expect.
But you can share tables by storing them in an external catalog. E.g., you could use an Apache Hive catalog for this purpose. See the docs for more info.


text:
Q: RequireJS sometimes not loading modules I have a really strange issue that suddenly started happening, its probably some race condition or something--but it always worked perfectly fine...
And for some reason, all requirejs loaded modules are quircky.
Its probably something silly but im killing myself over this, especially since nothing has changed in months..
Not using data-main, legacy project.
<script type="text/javascript">
    var require = {
        baseUrl: '/path/to/js/files',
    };
</script>
<script src="require.js"></script>

Inline script tab
<script type="text/javascript">
    requirejs(['com/some/file']);
</script>

JS file
define(function() {
    console.log("this loads 50/50...");
});

A: After some divide and conquer it became clear the google webfont loader was the culprit.
<script type="text/javascript">
    WebFontConfig = {
        google: { families: [ 'Quicksand:400,700:latin' ] }
    };
    (function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
        '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
    })();
</script>


text:
Q: How does Idris avoid using dot patterns for inaccessible patterns? In Agda one had to use dot patterns to tell the compiler which parts of a function definition cannot be inspected, in particular which variables can be used for pattern matching and which cannot (in new releases it seems that dot patterns are just optional and one can use new variables instead).
Idris apparently does not use any mechanism of this sort, so how does the idris compiler guess which pattern are accessible and which are not in a function definition? How does it get which are the arguments on which pattern match?
Thanks in advance.


text:
Q: Salesforce search setting "Lookup Auto-Completion" not working inside jquery datatable.for page 2 and above for 1st page it's working fine I am using  Salesforce search setting "Lookup Auto-Completion",and i am populating multiple records and for dispaly i used JQuery Datatable.Autocomplete is working for page 1 but not for rest of the pages
this is jquery:

this is my html :

 Financial Accounts

 <apex:repeat value="{!accts}" var="a">
 <apex:inputField value="{!a.Financial_Accounts__c}"/>
 </apex:repeat>


text:
Q: Test consistency over different runs/processes with pytest I would like to write a test using pytest which fails when a function has a different outcome on different runs. An easy example would be hash("abc")
On the terminal:
$> python -c 'print(hash("abc"))'
7757446167780988571
$> python -c 'print(hash("abc"))'
-1754122997235049390

However in one run we have of course:
>>> hash("abc")
-2233283646379253139
>>> hash("abc")
-2233283646379253139

How can I write a test (using pytest) that tests the consistency of the outcome of a function using different processes/runs such that it would fail for hash("abc")?
Background is that I'm implementing a DB access function which compares the binary strings of pickled/dilled dictionaries. However these strings will vary from run to run for the same dictionary.
I want to test for consistency because the function should not add to the DB if the dict is already in it..

A: Its a hacked solution but you can use processes to achieve your goal.
import subprocess

def test_hash():
    # Create the command
    cmd = ['python', '-c', 'print(hash("abc"), end="")']

    # Run a sub-process
    other_hash = subprocess.check_output(cmd)

    assert hash('abc') != int(other_hash)

A: Based upon Dov Benyomin Sohacheskis answer, I ended up with the following solution to the more elaborate problem of testing the consistency of a function with test fixtures and all..
I'll post it here because it might be helpful to others as well.
I assume that fixture holds the args and kwargs to the function to be tested.
import tempfile
import dill
import functools
import subprocess

def test_consistency_of_f(fixture):

    args, kwargs = fixture

    f = functools.partial(function_to_be_tested, *args, **kwargs)

    with tempfile.TemporaryDirectory() as td:
        fn = os.path.join(td, 'test.dill')
        with open(fn, 'wb') as fi:
            dill.dump(f, fi)
        cmd = """import dill
with open('{}', 'rb') as fi:
    f=dill.load(fi)
print(f())
""".format(fn)
        cmd = ['python', '-c', cmd]
        s1 = subprocess.check_output(cmd)
        s2 = subprocess.check_output(cmd)
        if not s1 == s2:
            print(1, s1)
            print(2, s2)
        assert s1 == s2


text:
Q: SQL Server does not exist or access denied - for SQL Server Express I have a local SQL Server 2017 Express database which I can connect to from a C# console app with the connection string
SERVER=(LocalDB)\MSSQLLocalDB;DATABASE=brain;uid=brain;pwd=xxxxxx

It works fine from the .NET app.
However I wanted to quickly knock up an ASP classic page so I could see some of the data from a browser and it doesn't work using that connection string.
I tried changing the server to what
SELECT @@SERVERNAME

returned which was HP\LOCALDB#0B1B079F
However that didn't work either.
I looked at some other answers which were to add a pass in the firewall and I did that even though the SQL Server and app/web page are on the same machine, my laptop. However that did nothing either.
I am just wondering why the C# App works but the ASP page doesn't. The rest of the ASP executes just not the connection to the DB.
The ASP code is just
Set objCon = CreateObject("ADODB.Connection")
objCon.open "PROVIDER=SQLOLEDB;SERVER=(LocalDB)\MSSQLLocalDB;DATABASE=brain;uid=brain;pwd=xxxxxx;"
objCon.CommandTimeout = 0
Set objRS = objCon.Execute(strSQL)

It fails on the objCon.open line.
Just not sure why a command prompt running a console app (for the moment until its made into an APP), works but IIS ASP Classic using the same connection string doesn't.

A: We can take advantage of the SQL Server Object Explorer in VS to obtain the connection string. It should be in line with the norms. After we added the SQL Server by using Add Server wizard, we can check the connect string property of the SQL Server.

Under this circumstance, the ADO.Net library and Entity Framework can connect to the SQL Server properly on my side.
Feel free to let me know if the problem persists.


text:
Q: Best time to buy and sell stocks when allowing consecutive buys or sells Problem
You're given the n stock prices for n days. Output the maximum profit you can reach by trading stocks. You can only trade at most once a day: on each day you can choose to either buy a single stock, or sell a single stock (if you have one), or give up the trade for that day and do nothing.
Example 1:
Given a = [1,2,10,9], return 16
Explanation:
You can buy on day 1 and 2 and sell on day 3 and 4.
Profit: -1-2+10+9 = 16
Example 2:
Given a = [9,5,9,10,5], return 5
Explanation:
You can buy on day 2 and sell on day 4.
Profit: -5 + 10 = 5
My analysis
The difficult part is that you can engage in consecutive buys and/or sells, meaning that once you posses a stock, you don't necessarily have to sell it before buying another one.
My idea is the following algorithm:
Start from the largest price, and then match the smallest price that occurs before that maximum price in the input array. After matching, remove these two prices from the array and keep repeating this process until you can find no more match. It seems like this algorithm works, but it costs O(n2) time, which is not fast enough.
Question
How could this be solved with a better time complexity, such as O(nlogn)?

A: We can model this as a min-cost circulation problem and solve it optimally with a specialized O(n log n)-time algorithm similar to your idea.
In the flow network, there is a node for each day and a node representing the market. There are two unit-capacity arcs for each day, one from the market with cost equal to the price that day, one to the market with cost equal to minus the price. There are arcs of zero cost and unbounded capacity that can move flow from each day (except the last) to the one after it. These represent holding stock.
Using () to represent nodes, ==> to represent unbounded capacity arcs and --> to represent unit capacity arcs, and labeling the costs, your sample instance is
      0        0        0
 ()======>()======>()======>()
 ^\       ^\       ^\       ^\
1| |-1   2| |-2  10| |-10  9| |-9
  \v       \v       \v       \v
  (                            )

Technically it's possible in this reformulation to both buy and sell on the same day, but that's not a profitable move, so it doesn't matter.
Given a residual network, the theory (linear programming duality) says we're done if and only if there's no negative-cost simple cycle. The intuitive meaning of such cycles is exactly what you would expect: buying a share and selling it profitably later.
The algorithm works by successively eliminating all negative-cost simple cycles (profitable cycles from now on) on the first k days for k from 1 to n. In the base case k = 1, the first day alone is never profitable, so we can move along to the inductive step.
For the inductive step, we know that there are no profitable cycles in the first k-1 days and want to extend that to k. If there is a profitable cycle in the first k days, it involves selling on day k. But what to buy? We can answer that question efficiently by maintaining a min-priority queue of our residual buying opportunities. We compare the day k price to the queue min, and if it's higher we do the deal, which involves popping the min and pushing the day k price, since from the point of view of the residual network, canceling our sale later looks the same as buying a share. Then we push the day k price regardless to represent the possibility of actually buying on day k.
We have to be careful here and prove that we didn't just introduce another profitable cycle. That's the reason to choose the min: we can't combine the new "selling" (actually canceling the buy) opportunity profitably with any of the residual buying opportunities, because the new selling price was not greater than any of those opportunities.
The finished algorithm is pretty simple. In Python:
import heapq

def trading_profit(prices):
    profit = 0
    queue = []
    for price in prices:
        if queue and queue[0] < price:
            profit += price - queue[0]
            heapq.heapreplace(queue, price)
        heapq.heappush(queue, price)
    return profit

A: This is an O(n²) algorithm. So in that sense it does not answer your question for something asymptotically faster, but as in a comment you learned that you're algorithm won't work, I believe it may be useful nonetheless.
I'd go for dynamic programming. Iterate over the days, and maintain a list where the index describes the number of stock you have, and the value is the best cash balance to arrive in that situation. So start with the list being [0], i.e. a single entry indicating that you can have zero stock at balance zero.
For each day, you can buy, sell or skip. You can express all the together using something like this:
balance_new[i] = max(balance[i], balance[i-1] - quote, balance[i+1] + quote)

The first entry represents skip: you keep current stock and balance. The second entry represents buy: you gain one stock (from i-1 to i) but reduce balance by the day's price. The third entry is a sell: you reduce stock by one but gain the current price to your balance.
The balance_new you get from this becomes the balance for the next day. And you'll need to take some care around the boundary of the list, where one of the expressions becomes invalid because it would index out of bounds. You can't get to zero stock with a buy operation. The requested maximum profit is balance[0] after you've processed all days. It represents the maximum balance that leaves you with no stock.
You have an outer loop iterating over n days. And an inner loop iterating over the potential number of stock you might possess at that point. That number grows linear in each iteration. If you want you can try to be clever and reduce the number of steps for the inner loop by one after you reached half the steps of the outer loop. That's because it never pays to acquire more stock than you can sell by the end. So the number of steps in the inner loop would go from something like one to something like n/2 then back down again, for a total of n²/4 + O(n) but that's still in O(n²) over all.

A: Correction:  My logic failed (for [9, 12, 1, 18, 17, 13, 1, 2, 10] gave 29 instead of 35)...
Here's the logic I came up with:

*

*map arr a to arr of {value, day, and relation}.

*set 1st relation to "smaller", and the following to "smaller"|"equal"|"bigger" compared to prev.

*from start, find last consecutive "smaller"(and then "smaller"|"equal"), from there, find last consecutive "bigger", match (push to buy and sell arrays) and remove.

*repeat from 2, until all not "bigger", or length<2.

*you are left with buy and sell pairs in their respective arrays(which will yield the maximum profit).


text:
Q: Upload files from latest commit to Azure Storage using Azure CLI I have a Jenkins pipeline. Every time I check into git, I need to access the changed files (or all files in a particular directory) and upload them into my Azure Storage account.
I'm able to upload files into the storage account using Azure CLI but I'm unable to access the git files. When I try to use the following in my JenkinsFile, I get null and null for both values.
echo "The commit hash is ${env.GIT_COMMIT} ${env.GIT_PREVIOUS_SUCCESSFUL_COMMIT}"
Given my use case, what should be my best approach? Is there any way I can access the files so that I can upload them?
My Jenkins version - 2.214.

A: In your pipeline, if you are trying to echo valid ${env.GIT_xxxx} directly without obtaining and saving the Map returned by checkout then I believe you can try to obtain the Map returned by checkout and save the Map as environment variable.
stage('Checkout code') {
  steps {
    script {
      // Checkout the repository and save the resulting metadata
      def scmVars = checkout([
        $class: 'GitSCM',
        ...
      ])

      // Display the variable using scmVars
      echo "scmVars.GIT_COMMIT"
      echo "${scmVars.GIT_COMMIT}"

      // Displaying the variables saving it as environment variable
      env.GIT_COMMIT = scmVars.GIT_COMMIT
      echo "env.GIT_COMMIT"
      echo "${env.GIT_COMMIT}"
    }

    // Here the metadata is available as environment variable
    ...
  }
}

Just FYI, this is the source of the above information. Hope this helps!


text:
Q: How find first checked item index in a c# checkedlistbox with lambda I need to set the selectedIndex of MyCheckedListBox to the first Checked Item index of the list and highlight it.
How to write a lambda expression to Select Min Index of MyCheckedListBox.CheckedItems as an alternate for using loop.

A: You don't need a lambda or a loop. The SelectedIndex property does exactly that.
From MSDN:

ListControl.SelectedIndex Property
  Gets or sets the lowest ordinal index of the selected items in the list.


text:
Q: QtService application cannot connect to system bus when running as a service I have recompiled Qt with integrated dbus for windows.
Further, I have implemented a QtService application which registers a service and an object at the system bus as follows:
QDBusConnection::systemBus().registerService("com.mycompany.Configuration");
QDBusConnection::systemBus().registerObject("/com/mycompany/Configuration/MySetting", myObject);

Now when I am running the service application with the -e parameter (running as regular application) it works fine and both dbus-monitor and qdbus --system show me the registered service and object.
However, when I am running the application as a windows service it does not register anything at the system bus.
Debugging the service gives me the error message

Not connected to D-Bus server

when calling registerService(...) and registerObject(...).
I have set the environment variables:
DBUS_SYSTEM_BUS_ADDRESS = autolaunch:
DBUS_SYSTEM_BUS_DEFAULT_ADDRESS = autolaunch:

My system.conf file:
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>

  <type>system</type>

  <fork/>

  <pidfile>/pid</pidfile>

  <listen>autolaunch:</listen>

  <policy context="default">

    <allow user="*"/>

    <deny own="*"/>
    <deny send_type="method_call"/>

    <allow send_type="signal"/>
    <allow send_requested_reply="true" send_type="method_return"/>
    <allow send_requested_reply="true" send_type="error"/>

    <allow receive_type="method_call"/>
    <allow receive_type="method_return"/>
    <allow receive_type="error"/>
    <allow receive_type="signal"/>

    <allow send_destination="org.freedesktop.DBus"/>

    <deny send_destination="org.freedesktop.DBus"
          send_interface="org.freedesktop.DBus"
          send_member="UpdateActivationEnvironment"/>
  </policy>

  <includedir>system.d</includedir>

  <include ignore_missing="yes">system-local.conf</include>

  <include if_selinux_enabled="yes" selinux_root_relative="yes">contexts/dbus_contexts</include>

</busconfig>

Additionally, I have a com.mycompany.Configuration.conf file in the system.d folder:
<!DOCTYPE busconfig PUBLIC
      "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
      "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>

  <!-- Only root can own the service -->
  <policy context="default">
    <allow own="com.mycompany.Configuration"/>
    <allow send_interface="com.mycompany.Configuration"/>
    <allow send_destination="com.mycompany.Configuration"/>
    <allow receive_sender="com.mycompany.Configuration"/>
  </policy>

</busconfig>

The windows service itself is called com.mycompany.Configuration and is executed as the Local System account.
Moreover, dbus verbose output shows that something is going on when my windows service gets started:
[...]
1292: [dbus\dbus-connection.c(1154):_dbus_connection_release_io_path] locking io_path_mutex
1292: [dbus\dbus-connection.c(1160):_dbus_connection_release_io_path] start connection->io_path_acquired = 1
1292: [dbus\dbus-connection.c(1165):_dbus_connection_release_io_path] unlockingio_path_mutex
1292: [dbus\dbus-connection.c(1522):_dbus_connection_handle_watch] middle
1292: [dbus\dbus-connection.c(4222):_dbus_connection_get_dispatch_status_unlocked] dispatch status = complete is_connected = 1
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(1529):_dbus_connection_handle_watch] end
1292: [dbus\dbus-watch.c(696):dbus_watch_handle] After sanitization, watch flags on fd 1932 were 0
1292: [dbus\dbus-sysdeps-win.c(1110):_dbus_poll] select: to=7875
        R:1944 E:1944
        R:1936 E:1936
        R:1932 E:1932

[dbus\dbus-sysdeps-win.c(1162):_dbus_poll] select: = 1:
        R:1932
[dbus\dbus-connection.c(1503):_dbus_connection_handle_watch] start
1292: [dbus\dbus-connection.c(1505):_dbus_connection_handle_watch] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(1081):_dbus_connection_acquire_io_path] locking io_path_mutex
1292: [dbus\dbus-connection.c(1085):_dbus_connection_acquire_io_path] start connection->io_path_acquired = 0 timeout = 1
1292: [dbus\dbus-connection.c(1128):_dbus_connection_acquire_io_path] end connection->io_path_acquired = 1 we_acquired = 1
1292: [dbus\dbus-connection.c(1130):_dbus_connection_acquire_io_path] unlocking io_path_mutex
1292: [dbus\dbus-connection.c(1133):_dbus_connection_acquire_io_path] LOCK
1292: [dbus\dbus-transport-socket.c(919):socket_handle_watch] handling read watch 003d6f58 flags = 1
1292: [dbus\dbus-transport-socket.c(345):exchange_credentials] exchange_credentials: do_reading = 1, do_writing = 0
1292: [dbus\dbus-transport-socket.c(446):do_authentication]  server auth state:waiting for input
1292: [dbus\dbus-sysdeps-win.c(207):_dbus_read_socket] recv: count=2048 fd=1932
1292: [dbus\dbus-sysdeps-win.c(217):_dbus_read_socket] recv: = 153
1292: [dbus\dbus-transport-socket.c(263):read_data_into_auth]  read 153 bytes in auth phase
1292: [dbus\dbus-auth.c(2187):process_command] server: got command "DATA 30333432316532346364316236363730303938303934303836666364653631372063303064313764623036653935643732336665666330396131633131653265353030643632616237"
1292: [dbus\dbus-auth.c(1624):process_data] server: data: '03421e24cd1b6670098094086fcde617 c00d17db06e95d723fefc09a1c11e2e500d62ab7'
1292: [dbus\dbus-auth.c(2134):goto_state] server: going from state WaitingForData to state WaitingForBegin
1292: [dbus\dbus-auth.c(760):sha1_handle_second_client_response] server: authenticated client using DBUS_COOKIE_SHA1
1292: [dbus\dbus-transport-socket.c(345):exchange_credentials] exchange_credentials: do_reading = 1, do_writing = 0
1292: [dbus\dbus-transport-socket.c(460):do_authentication]  server auth state:bytes to send
1292: [dbus\dbus-transport-socket.c(180):check_read_watch] fd = 1932
1292: [dbus\dbus-transport-socket.c(226):check_read_watch]   setting read watch enabled = 0
1292: [dbus\dbus-watch.c(449):_dbus_watch_list_toggle_watch] Toggling watch 003d6f58 on fd 1932 to 0
1292: [dbus\dbus-transport-socket.c(165):check_write_watch] check_write_watch(): needed = 1 on connection 003d88b0 watch 003d7260 fd = 1932 outgoing messages exist 0
1292: [dbus\dbus-watch.c(449):_dbus_watch_list_toggle_watch] Toggling watch 003d7260 on fd 1932 to 1
1292: [dbus\dbus-transport-socket.c(703):do_reading] fd = 1932
1292: [dbus\dbus-connection.c(1154):_dbus_connection_release_io_path] locking io_path_mutex
1292: [dbus\dbus-connection.c(1160):_dbus_connection_release_io_path] start connection->io_path_acquired = 1
1292: [dbus\dbus-connection.c(1165):_dbus_connection_release_io_path] unlockingio_path_mutex
1292: [dbus\dbus-connection.c(1522):_dbus_connection_handle_watch] middle
1292: [dbus\dbus-connection.c(4222):_dbus_connection_get_dispatch_status_unlocked] dispatch status = complete is_connected = 1
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(1529):_dbus_connection_handle_watch] end
1292: [dbus\dbus-sysdeps-win.c(1110):_dbus_poll] select: to=5641
        R:1944 E:1944
        R:1936 E:1936
        W:1932 E:1932

[dbus\dbus-sysdeps-win.c(1162):_dbus_poll] select: = 1:
        W:1932
[dbus\dbus-connection.c(1503):_dbus_connection_handle_watch] start
1292: [dbus\dbus-connection.c(1505):_dbus_connection_handle_watch] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(1081):_dbus_connection_acquire_io_path] locking io_path_mutex
1292: [dbus\dbus-connection.c(1085):_dbus_connection_acquire_io_path] start connection->io_path_acquired = 0 timeout = 1
1292: [dbus\dbus-connection.c(1128):_dbus_connection_acquire_io_path] end connection->io_path_acquired = 1 we_acquired = 1
1292: [dbus\dbus-connection.c(1130):_dbus_connection_acquire_io_path] unlockingio_path_mutex
1292: [dbus\dbus-connection.c(1133):_dbus_connection_acquire_io_path] LOCK
1292: [dbus\dbus-transport-socket.c(948):socket_handle_watch] handling write watch, have_outgoing_messages = 0
1292: [dbus\dbus-transport-socket.c(345):exchange_credentials] exchange_credentials: do_reading = 0, do_writing = 1
1292: [dbus\dbus-transport-socket.c(460):do_authentication]  server auth state:bytes to send
1292: [dbus\dbus-sysdeps-win.c(267):_dbus_write_socket] send: len=37 fd=1932
1292: [dbus\dbus-sysdeps-win.c(277):_dbus_write_socket] send: = 37
1292: [dbus\dbus-auth.c(2506):_dbus_auth_bytes_sent] server: Sent 37 bytes of: OK 4d63998db68399d8b48494595200cd61

1292: [dbus\dbus-transport-socket.c(345):exchange_credentials] exchange_credentials: do_reading = 0, do_writing = 1
1292: [dbus\dbus-transport-socket.c(446):do_authentication]  server auth state:waiting for input
1292: [dbus\dbus-transport-socket.c(180):check_read_watch] fd = 1932
1292: [dbus\dbus-transport-socket.c(226):check_read_watch]   setting read watchenabled = 1
1292: [dbus\dbus-watch.c(449):_dbus_watch_list_toggle_watch] Toggling watch 003d6f58 on fd 1932 to 1
1292: [dbus\dbus-transport-socket.c(165):check_write_watch] check_write_watch(): needed = 0 on connection 003d88b0 watch 003d7260 fd = 1932 outgoing messages exist 0
1292: [dbus\dbus-watch.c(449):_dbus_watch_list_toggle_watch] Toggling watch 003d7260 on fd 1932 to 0
1292: [dbus\dbus-transport-socket.c(503):do_writing] Not authenticated, not writing anything
1292: [dbus\dbus-transport-socket.c(165):check_write_watch] check_write_watch(): needed = 0 on connection 003d88b0 watch 003d7260 fd = 1932 outgoing messages exist 0
1292: [dbus\dbus-connection.c(1154):_dbus_connection_release_io_path] locking io_path_mutex
1292: [dbus\dbus-connection.c(1160):_dbus_connection_release_io_path] start connection->io_path_acquired = 1
1292: [dbus\dbus-connection.c(1165):_dbus_connection_release_io_path] unlockingio_path_mutex
1292: [dbus\dbus-connection.c(1522):_dbus_connection_handle_watch] middle
1292: [dbus\dbus-connection.c(4222):_dbus_connection_get_dispatch_status_unlocked] dispatch status = complete is_connected = 1
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(1529):_dbus_connection_handle_watch] end
1292: [dbus\dbus-watch.c(696):dbus_watch_handle] After sanitization, watch flags on fd 1932 were 0
1292: [dbus\dbus-sysdeps-win.c(1110):_dbus_poll] select: to=3484
        R:1944 E:1944
        R:1936 E:1936
        R:1932 E:1932

[dbus\dbus-sysdeps-win.c(1162):_dbus_poll] select: = 1:
        R:1932
[dbus\dbus-connection.c(1503):_dbus_connection_handle_watch] start
1292: [dbus\dbus-connection.c(1505):_dbus_connection_handle_watch] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(1081):_dbus_connection_acquire_io_path] locking io_path_mutex
1292: [dbus\dbus-connection.c(1085):_dbus_connection_acquire_io_path] start connection->io_path_acquired = 0 timeout = 1
1292: [dbus\dbus-connection.c(1128):_dbus_connection_acquire_io_path] end connection->io_path_acquired = 1 we_acquired = 1
1292: [dbus\dbus-connection.c(1130):_dbus_connection_acquire_io_path] unlockingio_path_mutex
1292: [dbus\dbus-connection.c(1133):_dbus_connection_acquire_io_path] LOCK
1292: [dbus\dbus-transport-socket.c(919):socket_handle_watch] handling read watch 003d6f58 flags = 1
1292: [dbus\dbus-transport-socket.c(345):exchange_credentials] exchange_credentials: do_reading = 1, do_writing = 0
1292: [dbus\dbus-transport-socket.c(446):do_authentication]  server auth state:waiting for input
1292: [dbus\dbus-sysdeps-win.c(207):_dbus_read_socket] recv: count=2048 fd=1932
1292: [dbus\dbus-sysdeps-win.c(217):_dbus_read_socket] recv: = 135
1292: [dbus\dbus-transport-socket.c(263):read_data_into_auth]  read 135 bytes in auth phase
1292: [dbus\dbus-auth.c(2187):process_command] server: got command "BEGIN"
1292: [dbus\dbus-auth.c(2134):goto_state] server: going from state WaitingForBegin to state Authenticated
1292: [dbus\dbus-sysdeps-win.c(787):_dbus_getsid] _dbus_getsid() returns 1
1292: [dbus\dbus-transport.c(673):auth_via_default_rules] Client authorized as S    ID 'S-1-5-18' but our SID is 'S-1-5-21-4012214046-2405994403-1636280286-500', disconnecting
1292: [dbus\dbus-transport.c(503):_dbus_transport_disconnect] start
1292: [dbus\dbus-transport-socket.c(985):socket_disconnect]
1292: [dbus\dbus-transport-socket.c(76):free_watches] start
1292: [dbus\dbus-watch.c(417):_dbus_watch_list_remove_watch] Removing watch on fd 1932
1292: [dbus\dbus-watch.c(417):_dbus_watch_list_remove_watch] Removing watch on fd 1932
1292: [dbus\dbus-socket-set-poll.c(221):socket_set_poll_remove] after removing fd 1932 from 003d2430, 2 en/2 res/9 alloc
1292: [dbus\dbus-watch.c(628):dbus_watch_set_data] Setting watch fd -1 data to data = 00000000 function = 00000000 from data = 00000000 function = 00000000
1292: [dbus\dbus-transport-socket.c(98):free_watches] end
1292: [dbus\dbus-sysdeps-win.c(317):_dbus_close_socket] _dbus_close_socket: socket=1932,
1292: [dbus\dbus-transport.c(514):_dbus_transport_disconnect] end
1292: [dbus\dbus-transport-socket.c(180):check_read_watch] fd = -1
1292: [dbus\dbus-transport-socket.c(703):do_reading] fd = -1
1292: [dbus\dbus-watch.c(628):dbus_watch_set_data] Setting watch fd -1 data to data = 00000000 function = 00000000 from data = 00000000 function = 00000000
1292: [dbus\dbus-connection.c(1154):_dbus_connection_release_io_path] locking io_path_mutex
1292: [dbus\dbus-connection.c(1160):_dbus_connection_release_io_path] start connection->io_path_acquired = 1
1292: [dbus\dbus-connection.c(1165):_dbus_connection_release_io_path] unlockingio_path_mutex
1292: [dbus\dbus-connection.c(1522):_dbus_connection_handle_watch] middle
1292: [dbus\dbus-connection.c(4222):_dbus_connection_get_dispatch_status_unlocked] dispatch status = complete is_connected = 0
1292: [dbus\dbus-connection.c(4184):notify_disconnected_and_dispatch_complete_unlocked] Sending disconnect message
1292: [dbus\dbus-connection.c(567):_dbus_connection_queue_synthesized_message_link] Synthesized message 003d8948 added to incoming queue 003d88b0, 1 incoming
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(4299):_dbus_connection_update_dispatch_status_and_unlock] Notifying of change to dispatch status of 003d88b0 now 0 (data remains)
1292: [dbus\dbus-connection.c(1529):_dbus_connection_handle_watch] end
1292: [dbus\dbus-connection.c(4515):dbus_connection_dispatch]
1292: [dbus\dbus-connection.c(4517):dbus_connection_dispatch] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(4090):_dbus_connection_acquire_dispatch] locking dispatch_mutex
1292: [dbus\dbus-connection.c(4104):_dbus_connection_acquire_dispatch] unlocking dispatch_mutex
1292: [dbus\dbus-connection.c(4107):_dbus_connection_acquire_dispatch] LOCK
1292: [dbus\dbus-connection.c(3954):_dbus_connection_pop_message_link_unlocked]Message 003d8948 (signal /org/freedesktop/DBus/Local org.freedesktop.DBus.Local Disconnected '') removed from incoming queue 003d88b0, 0 incoming
1292: [dbus\dbus-connection.c(4563):dbus_connection_dispatch]  dispatching message 003d8948 (signal org.freedesktop.DBus.Local Disconnected '')
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(4630):dbus_connection_dispatch]   running filter on message 003d8948
1292: [dbus\dbus-connection.c(3126):dbus_connection_preallocate_send] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [bus\dispatch.c(216):bus_dispatch] DISPATCH: org.freedesktop.DBus.Local Disconnected (no error name) to peer
1292: [bus\connection.c(198):bus_connection_disconnected] (inactive) disconnected, dropping all service ownership and releasing
1292: [dbus\dbus-connection.c(5526):dbus_connection_remove_filter] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(4891):dbus_connection_set_watch_functions] LOCK
1292: [dbus\dbus-watch.c(347):_dbus_watch_list_set_functions] Removing all pre-existing watches
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(4954):dbus_connection_set_timeout_functions] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(5268):dbus_connection_set_unix_user_function] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(5367):dbus_connection_set_windows_user_function] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(5037):dbus_connection_set_dispatch_status_function] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [bus\connection.c(1587):bus_connection_drop_pending_replies] Dropping pending replies that involve connection 003d88b0
1292: [dbus\dbus-connection.c(4644):dbus_connection_dispatch] LOCK
1292: [dbus\dbus-connection.c(4653):dbus_connection_dispatch] filter handled message in dispatch
1292: [dbus\dbus-connection.c(4784):dbus_connection_dispatch]  ... done dispatching
1292: [dbus\dbus-connection.c(4123):_dbus_connection_release_dispatch] locking dispatch_mutex
1292: [dbus\dbus-connection.c(4131):_dbus_connection_release_dispatch] unlocking dispatch_mutex
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(4801):dbus_connection_dispatch] LOCK
1292: [dbus\dbus-connection.c(4807):dbus_connection_dispatch] before final status update
1292: [dbus\dbus-connection.c(4222):_dbus_connection_get_dispatch_status_unlocked] dispatch status = complete is_connected = 0
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(2670):_dbus_connection_last_unref] Finalizing connection 003d88b0
1292: [dbus\dbus-connection.c(5037):dbus_connection_set_dispatch_status_function] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(4991):dbus_connection_set_wakeup_main_function] LOCK
1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-connection.c(5268):dbus_connection_set_unix_user_function] LOCK

1292: [dbus\dbus-connection.c(413):_dbus_connection_unlock] UNLOCK
1292: [dbus\dbus-transport.c(484):_dbus_transport_unref] finalizing
1292: [dbus\dbus-transport-socket.c(106):socket_finalize]
1292: [dbus\dbus-transport-socket.c(76):free_watches] start
1292: [dbus\dbus-transport-socket.c(98):free_watches] end
1292: [dbus\dbus-auth.c(430):shutdown_mech] server: Shutting down mechanism DBUS_COOKIE_SHA1
1292: [dbus\dbus-sysdeps-win.c(1110):_dbus_poll] select: to=0
        R:1944 E:1944
        R:1936 E:1936

[dbus\dbus-sysdeps-win.c(1140):_dbus_poll] select: = 0
1292: [bus\connection.c(828):expire_incomplete_timeout] Running
1292: [bus\expirelist.c(111):bus_expire_timeout_set_interval] Disabled an expire timeout
1292: [dbus\dbus-sysdeps-win.c(1110):_dbus_poll] select: to=-1
        R:1944 E:1944
        R:1936 E:1936
[...]

I really don't know what the issue could be and would appreciate any help.
Edit:
This one seems to have the same issue: http://comments.gmane.org/gmane.comp.freedesktop.dbus/14895

A: In the end I solved the problem and my service is now able to connect to the system bus.
I made the following changes:
In system.conf I changed the listen property and the authentication property:
<listen>tcp:host=localhost,port=13337,family=ipv4</listen>
<auth>ANONYMOUS</auth>
<allow_anonymous/>

According to that changes I set the system environment variables analogously:
DBUS_SYSTEM_BUS_ADDRESS = tcp:host=localhost,port=13337,family=ipv4
DBUS_SYSTEM_BUS_DEFAULT_ADDRESS = tcp:host=localhost,port=13337,family=ipv4

This answer led me in the right direction.


text:
Q: Strange sql query with avg I'm trying to query my db with this:
SELECT ar.email, tr.trackid, al.albumtitle, al.albumid, al.publishingdate, tr.genre, tr.tracktitle, ar.artistname, tr.reproductions, CEIL(AVG(co.rating)) AS 'media'
FROM tsn_tracks tr, tsn_albums al, tsn_artists ar, tsn_comments co
WHERE al.email=ar.email AND tr.albumid=al.albumid  tr.trackid = co.trackid
GROUP BY tr.trackid
ORDER BY al.publishingdate desc
LIMIT 0, 20

I will explain the scheme very quickly: i want to retrive the first 20 songs in order of publishing date (from the most recent) with all the different attributes, in particualr, users can write comments about a track and leave a vote (from 1 to 5) in their comments, in my query I want to show the vote avg of each song, but when a song haven't recived any comment, it doesn't appear in the result set (beacause of the "tr.trackid = co.trackid"). I have tried in many different ways but without solving the problem. I want the my query will give me a particular value (for example 0) when a song doesn't have any comments.
Sorry for my english!

A: Using JOINs instead of using everthing in the FROM and WHERE will allow you to use LEFT JOINS.  This means that a row will be retrieved even if the the table (notionally) on the right doesn't have a matching record.
SELECT ar.email, tr.trackid, al.albumtitle, al.albumid,
        al.publishingdate, tr.genre, tr.tracktitle, ar.artistname,
        tr.reproductions, CEIL(AVG(co.rating)) AS 'media'
    FROM tsn_tracks tr
    JOIN tsn_albums al on tr.albumid=al.albumid
    JOIN tsn_artists ar ON al.email=ar.email
    LEFT JOIN tsn_comments co ON tr.trackid = co.trackid
    GROUP BY tr.trackid
    ORDER BY al.publishingdate desc
    LIMIT 0, 20


text:
Q: Automatically moving email from Deleted Items folder to another folder My company uses a cloud Exchange system that deletes emails when they have been in the Deleted Items folder for 30 days (we use Outlook 2010 clients).  I want a script that would move all email from the Deleted Items folder to a second folder called "Trash".  I was able to find most of the following script online but it isn't working for me and I'm not sure what is missing/incorrect.  Any help is appreciated...
Sub MoveDeletedItems()
Dim oSource As Outlook.MAPIFolder
Dim oTarget As OutlookMAPIFolder
Dim oDummy As Object
Dim oToMove As Object
Dim colItems As Outlook.Items
Dim i As Long

Set oSource = Application.Session.GetDefaultFolder(olFolderDeletedItems)
Set oTarget = oSource.Folders.Folder("Trash")

Set colItems = oSource.Items

For i = colItems.Count To 1 Step -1
Set oToMove = colItems(i)
Set oDummy = oToMove.Move(oTarget)
Next
End Sub

A: Fist you have a lot of stuff going on you dont need
Here is an example with comments that can be run as a macro within outlook.
Sub MoveDeletedItems()
'setup some error checking
On Error GoTo err_rpt
Dim oSource As Outlook.MAPIFolder
Dim oTarget As Outlook.MAPIFolder
Dim oItem

'get the deleted Items folder
Set oSource = Application.Session.GetDefaultFolder(olFolderDeletedItems)
'get the folder under the Deleted Items folder called Trash
Set oTarget = oSource.Folders("Trash")
'loop through all the items in the source folder
For Each oMailItem In oSource.Items
    'move the item to the target folder
    oItem.Move oTarget
Next

err_rpt:
If Err.Number > 0 Then
    MsgBox Err.Description
End If
'release the folders
Set oTarget = Nothing
Set oSource = Nothing
End Sub


text:
Q: Adding validation rule only if all other rules pass, or stop validating entire set of attributes on the first error in Laravel 5.7 I want to allow a user to create a folder on the local storage disk. So the form that is sent to the server quite is simple and has three attributes:

*

*new-folder-name - that is the name of the folder to be created,

*relative-path - a path to the directory inside which the new directory should be created relative to an asset root directory, and

*asset_id - the id of an asset, I need this id to get the asset's root directory.

The thing is when I validate these attributes I need to also check if the folder the user is going to create already exists. For this purpose I made a rule called FolderExists. So, before I run FolderExists, I have to be sure all other rules have passed successfully because my custom rule should accept relative-path and asset_id to be able to build the path to check against.
Here is my rules() function, I'm doing validation in custom form request:
public function rules()
{
    return [
        'asset_id' => ['bail', 'required', 'exists:assets,id'],
        'relative-path' => ['bail', 'required', 'string'],
        'new-folder-name' => ['bail', 'required', 'string', 'min:3', new FolderName, new FolderExists($this->input('asset_id'), $this->input('relative-path')]
    ];
}

So my question is:
Is it possible to add FolderExists only if all other validation rules pass?
Or maybe it's possible to stop entire validation when the validator encounters first error?
Both options should be fine here.
Thank you!

A: I have finally found the solution myself. Here is what I ended up with.
To achieve the desired result I created another validator in withValidator() method of my custom form request, this second validator will handle only the FolderExists rule and only if the previous validation fails.
public function rules()
    {
        return [
            'asset-id' => ['bail', 'required', 'integer', 'exists:assets,id'],
            'relative-path' => ['bail', 'required', 'string'],
            'new-folder-name' => ['bail', 'required', 'string', 'min:3', 'max:150', new FolderName]
        ];
    }

public function withValidator($validator)
    {
        if (!$validator->fails())
        {
            $v = Validator::make($this->input(),[
                'new-folder-name' => [new FolderExists($this->input('asset-id'), $this->input('relative-path'))]
            ]);
            $v->validate();
        }
    }

If our main validator passes, we make another validator and pass only FolderExists rule with its arguments, that have already been validated, and call validate() method. That's it.


text:
Q: How do i call async function xamarin I'm trying to call an async function but when I try and do it it has the red line underneath it. I want the function to be called when the page is opened, thanks in advance.
public partial class Home : ContentPage
{

    public class GoogleProfile
    {
        public string Id { get; set;}

    }

    public Home()
    {
        InitializeComponent();
    }

    protected override async void OnAppearing()
    {
        await Check(/*What do i put in here*/);

    }

    public async Task Check(GoogleProfile googleprofile)
    {

        if (String.IsNullOrEmpty(googleprofile.Id))
        {

        }
        else {
            await Navigation.PushAsync(new LoginPage());
        }
    }

}

how would i call this? Sorry im new to C# and xamarin

A: You should make your async calls in ContentPage.OnAppearing(). The OnAppearing() event will be called, as the name suggest, right when your page is being displayed. This is the expected behavior by the user. Also note that I changed your Check() method to return Task because, if you are able to edit the method signature, always try to change the return type of async methods from void to Task:
public partial class LoginPage : ContentPage {

    public LoginPage() {
        InitializeComponent();
    }

    protected override async void OnAppearing() {
        await Check(/* Add code here to get your GoogleProfile object */);
    }

    public async Task Check(GoogleProfile googleprofile) {
        var ID = googleprofile.Id;

        if (string.IsNullOrEmpty(ID)) {
            return;
        } else {
            await Navigation.PushAsync(new Home());
        }
    }
}

Technically, if you are dead set to not use OnAppearing() you could do the Check() before pushing your LoginPage, though without seeing more code, that would seem like it would defeat the purpose of the LoginPage.


text:
Q: Horizontal RecyclerView Acessibility order I setup a RecyclerView as horizontal, but the traversal order is completely messed up when using talkback.
Only the fully-visible views in RecyclerView's item views is being read by talkback. When talkback reaches the last fully-visible view at the item view, it scrolls to the next page instead of keep reading the remaining views on item view.

A: Item View:
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:layout_marginStart="@dimen/8_dp"
    android:focusable="false"
    android:orientation="vertical"
    android:importantForAccessibility="no"
    android:padding="@dimen/20_dp">

    <TextView
        android:id="@+id/tv_plan_coverage_title"
        style="@style/FonteItauBold"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/seguros_ff6800"
        android:textSize="@dimen/22_sp"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="@string/plans_card_title" />

    <TextView
        android:id="@+id/tv_plan_coverage_subtitle"
        style="@style/FonteItauBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/24_dp"
        android:layout_marginBottom="@dimen/18_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:text="@string/plans_card_subtitle"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/16_sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/tv_plan_characteristics_1"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_coverage_title" />

    <TextView
        android:id="@+id/tv_plan_characteristics_1"
        style="@style/FonteItauRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/tv_plan_characteristics_2"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_coverage_subtitle"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_characteristics_2"
        style="@style/FonteItauRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/10_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_1"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_characteristics_3"
        style="@style/FonteItauRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/10_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_2"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_characteristics_4"
        style="@style/FonteItauRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/10_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_3"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_characteristics_5"
        style="@style/FonteItauRegular"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/10_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_4"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_characteristics_6"
        style="@style/FonteItauRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/10_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_5"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_characteristics_7"
        style="@style/FonteItauRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/10_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_6"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_characteristics_8"
        style="@style/FonteItauRegular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/10_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:textColor="@color/seguros_262220"
        android:textSize="@dimen/componentesui_default_text_16_sp"
        tools:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_7"
        tools:text="@string/plans_card_coverage_tools" />

    <TextView
        android:id="@+id/tv_plan_value_title"
        style="@style/FonteItauBold"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/24_dp"
        android:layout_marginBottom="@dimen/24_dp"
        android:focusable="true"
        android:importantForAccessibility="yes"
        android:text="@string/plans_card_value_title"
        android:textSize="@dimen/text_14sp"
        app:layout_constraintBottom_toTopOf="@id/table"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_plan_characteristics_8"
        app:layout_constraintVertical_bias="0" />

    <TableLayout
        android:id="@+id/table"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/24_dp"
        android:stretchColumns="*"
        app:layout_constraintBottom_toTopOf="@id/bt_dental_plan_get_in_contact"
        app:layout_constraintVertical_bias="1">

        <TableRow>
            <TextView
                android:id="@+id/value_money"
                style="@style/FonteItauBold"
                android:focusable="true"
                android:importantForAccessibility="yes"
                android:textSize="@dimen/text_20sp"
                tools:text="R$ 269,90" />

            <TextView
                android:id="@+id/value_money_max"
                style="@style/FonteItauBold"
                android:focusable="true"
                android:gravity="start"
                android:importantForAccessibility="yes"
                android:textSize="@dimen/text_20sp"
                tools:text="R$ 269,90" />
        </TableRow>

        <TableRow>

            <TextView
                android:id="@+id/value_lifes"
                style="@style/FonteItauRegular"
                android:focusable="true"
                android:importantForAccessibility="yes"
                android:textSize="@dimen/text_14sp"
                tools:text="2-29 vidas" />

            <TextView
                android:id="@+id/value_lifes_max"
                style="@style/FonteItauRegular"
                android:focusable="true"
                android:gravity="start"
                android:importantForAccessibility="yes"
                android:textSize="@dimen/text_14sp"
                tools:text="30-99 vidas" />
        </TableRow>
    </TableLayout>

    <Button
        android:id="@+id/bt_dental_plan_get_in_contact"
        style="@style/BotaoSecundarioItau"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/16_dp"
        android:text="@string/plans_card_coverage_button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.6"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: How to create a WCF service without the need of a Service Certificate? I'm trying to create a basic webservice with WCF. It's small, and will only be used internally between two servers, so there is no need for security of any kind. Unfortunately WCF demands a certificate:

The service certificate is not provided. Specify a service certificate in ServiceCredentials.

I don't want to configure a certificate anywhere. Certificates are great for security, but also invariably come packaged with two days worth of headaches until you get them right just so, and I don't want that right now.
I'm googling all around but cannot find an answer anywhere - can you disable this feature of WCF?
Added: Almost forgot, here's my bindings 'n stuff, just in case they're useful:
<bindings>
  <wsFederationHttpBinding>
    <binding name="XXXServiceBinding" maxReceivedMessageSize="1073741824">
      <readerQuotas maxStringContentLength="1073741824" maxArrayLength="2147483647"/>
    </binding>
  </wsFederationHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="XXXServiceBehavior">
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service name="XXX.XXX" behaviorConfiguration="XXXServiceBehavior">
    <endpoint address="xxx" contract="XXX.IXXX" binding="wsFederationHttpBinding" bindingConfiguration="XXXServiceBinding">
      <identity>
        <dns value="XXX Test Service"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>
</services>

Added 2: Oh, right, VS2010, .NET 4.0. Windows 7, integrated VS webserver.

A: What does your web.config bindings section look like? Using basicHttpBinding with clientCredentialType="None" should as far as I know run without any certificates. Ie:
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IServiceWS">
          <security mode="None">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
   ....

A: If you don't want to use security why are you using WsFedarationBinding which is designed for federated security? Use BasicHttpBinding instead. It doesn't use any security by default or if all communication will be performed in the same windows domain with users and service using domain accounts you can use WsHttpBinding with default configuration - it will use Windows security without need for any certificate.

A: You are using wsFederationHttpBinding in the service. If it is not important to push in so much of security, you could have gone for simple HTTP binding called basicHTTP binding. Consider appropriate binding for the service.


text:
Q: How to access array in php by index based? I have a database table for User in that i have two fields USER_ID and USER_DESCRIPTION, If i run the bellow code i get array in the form.
Array ( [USER_ID] => 1 [USER_DESCRIPTION] => TAB )

But i want to access those value in index based like 0, 1.How to i get that.
while (($result = oci_fetch_array($data, OCI_ASSOC)) != false) {
    echo $result['USER_ID']. ' - ' .$result['USER_DESCRIPTION']; //This works
    echo $result[0]. ' - ' .$result[1]; //This is how i want to access the values
}

A: You have passed second parameter OCI_ASSOC to oci_fetch_array() which will fetch only associative array.
If you change that parameter to OCI_BOTH, it will return both numeric as well associative array.
OCI_BOTH is default. So, even you can put that parameter empty.
Change
while (($result = oci_fetch_array($data, OCI_ASSOC)) != false) {

To
while (($result = oci_fetch_array($data, OCI_BOTH)) != false) {

OR To (as OCI_BOTH is default):
while (($result = oci_fetch_array($data)) != false) {

Read it here:
http://php.net/manual/en/function.oci-fetch-array.php

A: You can try this -
$result= array_values($result); // Array with indexes you need

Or you can do another trick (assuming you are having those indexes dynamically) -
$keys = array(
    0 => 'USER_ID',
    1 => 'USER_DESCRIPTION',
);

while (($result = oci_fetch_array($data, OCI_ASSOC)) != false) {
    echo $result[$keys[0]]. ' - ' .$result[$keys[1]];
}

A: This works for me.
while (($result = oci_fetch_array($data, OCI_NUM)) != false){}


text:
Q: How do I escape a Unicode character in my Objective-C source code? I feel incredibly stupid for asking this, but the documentation and Google are giving me no love at all.
I have a Unicode character I want to insert into a string literal in the source code of my iPhone app.  I know its hex value.  What is the proper escape sequence to use?  And for that matter, what obvious source of information am I overlooking that would have told me this?

A: Example:
NSString *stuff = @"The Greek letter Beta looks like this: \u03b2, and the emoji for books looks like this: \U0001F4DA";

A: A more modern approach:
I'm not sure when this feature was added to the language, but as of 2015, at least, Objective-C string literals can contain any Unicode character. For instance, I mark my log lines with emoji because their distinctive colors are an easier way for me to pick them out:

So, if you have the character and not just the code point, and you want to use it in a static string and not dynamically generate it, this is a great approach, since you instantly know what character you're using just by looking at it.

A: If you don't want to put it directly in your string you can use a format specifier like this:
[string stringByAppendingFormat:@"%C", 0x2665];

A: The proper escape sequence would be something along the lines of
wchar_t * str = L"\x0627";

See this question: character constant:\000 \xhh
Edit: Oh, sorry, I missed the iPhone and Objective-C tags. The above is valid for generic C/C++, but I have not worked with iPhone development so your mileage may vary.

A: \ is the escape character in objective c, use it before the letter to be escaped like :
NSString temp = @" hello \"temporary.h\" has been inported";

Here if you print the temp string in textview or logs,  you will see " being printed as well because we have used the \ before them which is the escape character


text:
Q: Uncertainty relation of energy and time in stationary states The energy-time uncertainty tells us that if energy uncertainty is zero time uncertainty is infinite. Now for a higher energy stationary state energy spread is zero so accordingly its average life time i.e. time spread should be zero, but higher energy states are less stable than ground state. So its average life time is finite. My question is what is contradicting the time-energy uncertainty relation?

A: There are multiple reasons for the broadening of spectral lines.
The one you are referring to is what is called the natural width, and it varies for atomic spectra, for molecular spectra, and for nuclear. It is actually due to the fact that those energy states from and which they jump are not infinitely stable. The do have natural half life, so called lifetime, tau, which then through Planck's uncertainty principle determines their line widths. It is to be expected, higher energy levels will over time have a tendency to decay to lower levels. They are not perfectly stable.
There's other factors. They can also have their widths broadened by other effects, such as collisions and Doppler effects. Those can sometimes be much bigger effects.
You can google a lot of writings on this. I found a few, but keep loosing the links in my iPad. See one at http://www-star.stand.ac.uk/~kw25/teaching/nebulae/lecture08_linewidths.pdf
For spontaneous emission, i.e., the natural line width, you can not explain it from Schrodinger's equation and classical QM, which takes the nergy states as infinitely stable. You need to include the effect of the virtual photons around, in essence you need QED. See a little more in https://en.m.wikipedia.org/wiki/Spontaneous_emission


text:
Q: How can I stop Android WebView from changing the capitalization of the Headers? So With and Android WebVIew I am adding some Headers to a redirect like so.
webView?.webViewClient = object : WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        if(!url!!.contains("ourwebsite/redirect/"))
            return false

        val extraHeaders: MutableMap<String, String> = mutableMapOf()
        extraHeaders.put("Auth_Header, "some token")
        extraHeaders.put("Id_Header, "some username")

        view?.loadUrl(url, extraHeaders)
        return false

    }

But the authentication was failing so I got some logs from our server folks and The headers have had the capitalization removed so they look like this now:
    "auth_header, "some token"
    "id_header, "some username"

How can I make android WebView, respect the capitalization of my headers?!

A: From RFC 2616 - "Hypertext Transfer Protocol -- HTTP/1.1", Section 4.2 - "Message Headers":

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

The server needs to ignore the case for header names.


text:
Q: how to make tomcat 6 running mulitple domain with non ROOT application name I am trying to run multiple domain on a tomcat 6 on a linux server.
I got 404 Errors when I follow the steps here
http://tomcat.apache.org/tomcat-6.0-doc/virtual-hosting-howto.html
Here is the conf
server.xml
<Engine name="Catalina" defaultHost="a.mydomain.com">
    <Host name="a.mydomain.com" appBase="aapps" autoDeploy="true" unpackWars="true" />
    <Host name="b.mydomain.com" appBase="bapps" autoDeploy="true" unpackWars="true" />
</Engine>

<Tomcat>/conf/Catalina/a.mydomain.com/ROOT.xml
<?xml version='1.0' encoding='utf-8'?>
<Context docBase="/opt/tomcat/aapps/portal" reloadable="true" path=""></Context>

<Tomcat>/conf/Catalina/b.mydomain.com/ROOT.xml
<?xml version='1.0' encoding='utf-8'?>
<Context docBase="/opt/tomcat/bapps/portal" reloadable="true" path=""></Context>

What am I doing wrong here?
by the way, tomcat auto generated a portal.xml in the /conf/Catalina/a.mydomain.com/

A: What do your workers.properties and context maps look like?


text:
Q: Xml Requests do not work I cannot get a bare bones Asp.Net Core Web Api project to work using Xml instead of Json. Please help!
I have created a new project and the only adjustments to the default configuration were to add the Xml formatters...
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc(config =>
    {
        config.InputFormatters.Add(new XmlSerializerInputFormatter());
        config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });
}

My Controller also contains simple Get and Post methods:
[Route("api")]
public class MessageController : Controller
{
    [HttpPost]
    public void Post([FromBody] Message message)
    {

    }

    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new Message
        {
            TestProperty = "Test value"
        });
    }
}

When I try calling the POST method with Content-Type: application/xml, the API returns 415 Unsupported Media Type. I have tried adding the Consumes("application/xml") attribute to the controller and still it does not work.
The GET works and returns JSON. However, if I add the Produces("application/xml") attribute to the controller, the GET returns 406  Not Acceptable, even if I provide the Accepts: application/xml header.
For some reason, the API is completely rejecting anything related to xml even though the input and output formatters were added as I have seen in the very few examples I could find.
What am I missing?

A: I have following thing in my startup.cs and it works well with XML and JSON both.
Here I only stick with XML.
Note : ( I have consider my own class for sample)

*

*Startup.cs
public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
                .AddJsonFormatters().AddXmlSerializerFormatters();
    }

*My HttpClient Code ( You might have missed Content Type setting that I have done in StringCotent)

*

*Two header is important : Accept and Content-Type. Accept help in content negotiation and Content-Type is a way client tell server what type content client is posting.
 HttpClient client = new HttpClient();
 client.BaseAddress = new Uri( @"http://localhost:5000");
 client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));

 HttpContent content = new StringContent(@"<Product>
<Id>122</Id>
<Name>Computer112</Name></Product>",System.Text.Encoding.UTF8 , "application/xml");  // This is important.

var result = client.PostAsync("/api/Products", content).Result;

A: In ASP.Net Core 2.0 you can accept both XML and Json request almost out of the box.
In Startup class in ConfigureServices method, you should have:
services
    .AddMvc()
    .AddXmlSerializerFormatters();

And controller that accepts complex object looks like this:
[Route("api/Documents")]
public class DocumentsController : Controller
{
    [Route("SendDocument")]
    [HttpPost]
    public ActionResult SendDocument([FromBody]DocumentDto document)
    {
        return Ok();
    }
}

This is an XML to send:
<document>
    <id>123456</id>
<content>This is document that I posted...</content>
<author>Michał Białecki</author>
<links>
    <link>2345</link>
    <link>5678</link>
</links>

{
    id: "1234",
    content: "This is document that I posted...",
    author: "Michał Białecki",
    links: {
        link: ["1234", "5678"]
    }
}

And that's it! It just works.

Request with the same document either in XML or Json to api/documents/SendDocument endpoint is handled by one method. Only remember about correct Content-Type header in your request.
You can read the whole post at my blog: http://www.michalbialecki.com/2018/04/25/accept-xml-request-in-asp-net-mvc-controller/

A: For ASP.NET Core 2.2 use nuget package Microsoft.AspNetCore.Mvc.Formatters.Xml or Microsoft.AspNetCore.App
and add this in Startup.cs
      services.AddMvc()
       .AddXmlSerializerFormatters()
       .AddXmlDataContractSerializerFormatters();

Don't forget to use headers Accept application/xml to get response as xml and Content-Type application/xml for request with xml body.
Check example here http://www.devcode4.com/article/asp-net-core-xml-request-response


text:
Q: Joomla check for empty string with JInput Following this guide to sanitize my inputs, I'm wondering if an empty string is covered with this?
$jinput = JFactory::getApplication()->input;
$this->name = $jinput->get('name', '', 'STRING');

Typically without Joomla I'd be checking for an empty string as well. Something like:
if (!empty($_POST['name']))

Looking at the JInput get method I see that it checks if it is isset:
public function get($name, $default = null, $filter = 'cmd')
{
    if (isset($this->data[$name]))
    {
        return $this->filter->clean($this->data[$name], $filter);
    }

    return $default;
}

Not the same thing, as isset will only check for null. However that is the default value for using the get method. So if I specify an empty string for the second parameter am I covered here?
$this->name = $jinput->get('name', '', 'STRING');

A: It's not up to Joomla to decide whether your empty string is valid value or not. They have to use isset(), because if they would use empty() and you return '0' which you would expect as normal, Joomla would return default value instead of that '0'.
So it's completely normal that they just use isset() to check if variable is set, and it's up to you to decide what values you accept.
If the value isn't set, and you set as the second parameter empty string '', you'll get an empty string returned.
In your example an empty string would be returned, which is expected behaviour.


text:
Q: Excel Interop Sorting I have an c# project which automates excel using the excel interop. One issue that I am running into is sorting using the excel filters, when I protect the sheet using C#, I am disabling sorting, when I unprotect it I am able to use the filters in the ListObject to sort. Given that I need to protect the sheet is their a C# event that can tell me when a user selected the header of the list Object column and select Sort A to Z or Largest to smallest
Thanks

A: You're not going to get anything in C# that isn't available via the Excel object model. If such an event exists, it would probably have some form of it on the Application object (the Application object has events like SheetBeforeDoubleClick that are duplicates of the events that happen on the individual books/sheets like the BeforeDoubleClick event of the Worksheet object).
The SheetTableUpdate event may help you.
http://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.excel.application_events.aspx

A: This is kind of outdated and you mention no Excel version but from what I gather, I think this may be able to help you.
Sort Excel table (ListObject) on protected sheet using Excel Interop c#


text:
Q: Co-occurrence calculations from a presence-absence matrix I have this great presence-absence dataset in which I need to calculate a C score (CS) for each species pair (BABO, BW, RC, SKS, MANG) to measure species co-occurrences.

ki and kj denote the numbers of occurrences of species i and j
and K is the number of co-occurrences of both species.
I have looked at articles like Find the pair of most correlated variables and Turning co-occurrence counts into co-occurrence probabilities with cascalog but was unable to determine the most efficient way to go about it in R. I have tried creating a function but was unsuccessful.
My data:
data <- structure(list(group_id = c("2008-2-11.C3_900", "2008-2-11.C3_960",
"2008-2-11.C3_1200", "2008-2-11.C3_1230", "2008-2-11.C3_1460",
"2008-2-11.C3_1490", "2008-2-22.Mwani_0", "2008-2-22.Mwani_110",
"2008-2-22.Mwani_600", "2008-2-22.Mwani_1650", "2008-2-20.Sanje_150",
"2008-2-20.Sanje_410", "2008-2-20.Sanje_3000", "2008-5-9.C3_900",
"2008-5-13.Mwani_750", "2008-5-13.Mwani_800", "2008-5-13.Mwani_900",
"2008-5-13.Mwani_1080", "2008-5-13.Mwani_1800", "2008-5-13.Mwani_2200",
"2008-5-13.Mwani_2900"), BABO = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0), BW = c(1, 1, 1, 1, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1), RC = c(0, 0, 1,
1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0), SKS = c(0,
1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0),
    MANG = c(0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1)), row.names = c(NA, -21L), class = c("tbl_df",
"tbl", "data.frame"))

group_id               BABO BW RC SKS MANG
<chr>                  <dbl><dbl><dbl><dbl>
2008-2-11.C3_900        0   1   0   0   0
2008-2-11.C3_960        0   1   0   1   0
2008-2-11.C3_1200       0   1   1   1   0
2008-2-11.C3_1230       0   1   1   0   0
2008-2-11.C3_1460       0   0   1   0   0
2008-2-11.C3_1490       0   0   0   1   0
2008-2-22.Mwani_0       0   0   0   1   1
2008-2-22.Mwani_110     0   0   1   0   1
2008-2-22.Mwani_600     0   1   0   0   0
2008-2-22.Mwani_1650    0   0   0   1   0
2008-2-20.Sanje_150     0   1   0   1   0
2008-2-20.Sanje_410     0   0   1   0   0
2008-2-20.Sanje_3000    0   0   1   0   0
2008-5-9.C3_900         0   0   0   1   0
2008-5-13.Mwani_750     0   0   0   1   0
2008-5-13.Mwani_800     1   0   1   0   0
2008-5-13.Mwani_900     0   0   1   0   0
2008-5-13.Mwani_1080    0   1   1   0   0
2008-5-13.Mwani_1800    0   1   0   0   0
2008-5-13.Mwani_2200    0   1   0   0   0
2008-5-13.Mwani_2900    0   1   0   0   1

A: First define a function to compute CS for a given pair of species; then use combn() to generate all possible pairs; then pass each pair to the CS() function using purrr::map2_dbl().
library(dplyr)
library(purrr)

CS <- function(i, j, data) {
  K <- sum(data[[i]] == 1 & data[[j]] == 1)
  ki <- sum(data[[i]])
  kj <- sum(data[[j]])
  ((ki - K) * (kj - K)) / (ki * kj)
}

names(sp_data)[-1] %>%
  combn(2) %>%
  t() %>%
  as_tibble() %>%
  set_names(c("i", "j")) %>%
  mutate(CS = map2_dbl(i, j, CS, data = sp_data))

# A tibble: 10 × 3
   i     j        CS
   <chr> <chr> <dbl>
 1 BABO  BW    1
 2 BABO  RC    0
 3 BABO  SKS   1
 4 BABO  MANG  1
 5 BW    RC    0.467
 6 BW    SKS   0.438
 7 BW    MANG  0.6
 8 RC    SKS   0.778
 9 RC    MANG  0.593
10 SKS   MANG  0.583

(Side note: using the equation you provided, species with little co-occurrence end up with high CS scores, and vice versa. If this isn't what you expected, perhaps your equation should be subtracted from 1?)

A: In base R, we may use crossprod
t1 <- crossprod(as.matrix(data[-1]))
v1 <- diag(t1)
c1 <- v1[col(t1)]
r1 <- v1[row(t1)]
((c1 - t1) * (r1 - t1))/(c1 * r1)

-output
     BABO        BW        RC       SKS      MANG
BABO    0 1.0000000 0.0000000 1.0000000 1.0000000
BW      1 0.0000000 0.4666667 0.4375000 0.6000000
RC      0 0.4666667 0.0000000 0.7777778 0.5925926
SKS     1 0.4375000 0.7777778 0.0000000 0.5833333
MANG    1 0.6000000 0.5925926 0.5833333 0.0000000


text:
Q: Chart.js annotations in Vue.js break when defined in data () I've run into a problem using chartjs-plugin-annotations in a Vue.js application
We've been successfully embedding ChartJS charts in our Vue applications for a while with the config for the chart defined in the data () section of the components.
However when we have added in the chartjs-plugin-annotation plugin we have been unable to get the annotations working unless we define the config locally and return the new Chart directly. This obviously causes problems with updating the chart.
This is the basic model we are using with Annotations
  async setChart (ctx) {
   const config = {
     type: 'bar',
     data: {},
       ..
   }
   // populate the dateset for the chart
   await this.setChartData(config)
   // populate the annotations for the chart
   await this.setAnnotations(config)
   // create the chart
   return new Chart(ctx, config)
 }

A full example fiddle is here
This is fine (or at least works) when we are using the charts statically however we have at least page where we need to change the chart depending on selections on the page. In this instance the new Chart is rendering the new data but keeping the old chart as well. The browser then flicks between charts when moused over. This can be seen in the example above.
Ideally we should be using the update() method of chartJS in this case, but as we are not assigning the chart to a global we cannot access it after creation
Any thoughts?

A: This question: Annotations are not displayed in Chart.js links to the solution
There is an issue with annotation and Chart.js 2.9.4, the solution is to downgrade to Chart.js 2.9.3


text:
Q: Accidentally run command rm -R in Amazon EC2. Unable to login I'm using Amazon EC2 for Magento website and WinScp to access SFTP.
Sometimes I'm using terminal in WinScp to execute command.
Today I need to delete some files so I used rm -R /* and forget to mention folder name.
Now i am unable to login using winscp to my server and the website is not working. I am getting this error in winscp:
"Authentication log (see session log for details):
Using username "ubuntu".
Server refused our key.

Authentication failed."

How can I login again and undo the massive erase?

A: You can recover the instance data by deploying your SSH key to a new copy of the instance, see e.g. https://stackoverflow.com/questions/3260739/add-keypair-to-existing-ec2-instance


text:
Q: PPT and Excel not generating in Office 2013 I am working on report automation project (Windows Application) and my dev environment have Visual Studio 2010 Professional version, Office 2013 installed.
I am using Microsoft Office Interop DLL files. I used below DLLs for Interop: Microsoft.CSharp.dll, Microsoft.Office.Interop.Excel.dll, Microsoft.Office.Interop.PowerPoint.dll. All these versions are 12.0.0.0.
This setting is working fine for Office 2010. But for Office 2013 it is messing.
Now let me describe how this reports gets generated. Firstly it creates an Excel file (which I consider as Intermediate file and it contains data and other charts is not generating the excel file), then from there we take those data to PPT file and make the expected output. I tried 14.0.0.0 versions for above mentioned dll also.
My application target framework is ".Net Framework 4 Client Profile", Platform Target "x86".
I can not use any paid library/DLL files.

A: there is a easy way to work with Excel, by using EPplus open source library you can create and read excel file easy
use below command in your package manage console
Install-Package EPPlus

for creating PPT files also this link will be helfull : How to use Automation to create and to show a PowerPoint


text:
Q: How to HTTP POST a Blob to a different domain? I have some Blob() object. I want to upload somewhere else (a website that handle user upload through forms).
I can put them in a FormData and send them through an XMLHttpRequest object, but then I can't read the ajax response, because I'm blocked by the same origin policy of the ajax call.
How can I get around this? Is there some way to do a regular upload without using ajax? Is there a way to deal with that "same origin policy" that will work on recent versions of Chrome and Firefox?
edit: Not sure this is a duplicate: I don't control the server being posted, so I'm not OK with just "setting the same origin policy on both domains".

A: In most cases when someone is trying to use AJAX across domains but is blocked by the same origin policy, it is recommended to AJAX to your own PHP page, and then use cURL to send that data to a different site.
http://curl.haxx.se/


text:
Q: How to make web application as Use Application-owned Accounts in server side google drive PHP i wanna make web application use google drive sdk on PHP. when user login to my web using its own credential (ex username : lalala) will automatically login to user google account without user know like background login(silent mode) no redirect to google. username, email and password user save in mysql. user can upload file to google drive with my web application but not redirect to drive.google.com. how to make it? can someone give me an full example, please...

A: ClientLogin which implements basic authorization is deprecated across the Google products, you need to implement OAuth2 workflow for user accounts.