Q: ошибка Android resource linking failed
По книге  Head First Android делаю программу, выдает ошибку, при нажатии на ошибку показывает на обьект Spinner в activity_find_beer.xml . из названия ошибки думаю что причина в неправильно указанной ссылке.
Прошу направить на правильный путь
Заранее спасибо за ответы!
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.beeradviser2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".FindBeerActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_find_beer.xml
        <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Spinner
        android:id="@+id/color"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="37dp"
        android:entires="@array/beer_colors"/>

    <Button
        android:id="@+id/find_beer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/color"
        android:layout_below="@+id/color"
        android:text="@string/find_beer"
        android:onClick="onClickFindBeer"/>
    <TextView
        android:id="@+id/brands"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/find_beer"
        android:layout_below="@id/find_beer"
        android:layout_marginTop="18dp"
        android:text="@string/brands" />
</RelativeLayout>

strings.xml
   <resources>
    <string name="app_name">Beer Adviser2</string>
    <string-array name="beer_colors">
        <item>light</item>
        <item>amber</item>
        <item>brown</item>
        <item>dark</item>
    </string-array>
    <string name="find_beer">Find Beer!</string>
    <string name="brands" />
</resources>

FindBeerActivity.java
    package com.example.beeradviser2;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;

public class FindBeerActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedIntanceState) {

        super.onCreate(savedIntanceState);
        setContentView(R.layout.activity_find_beer);
    }
    public void onClickFindBeer(View view) {
        TextView brands = (TextView) findViewById(R.id.brands);
        Spinner color = (Spinner) findViewById(R.id.color);
        String beerType = String.valueOf(color.getSelectedItem());
        brands.setText(beerType);
    }

}

A: Опечатка в
android:entires="@array/beer_colors"
Должно быть entries.


Q: How can I create a function similar to current_user? In Flask, I would like to understand how to create a function that behaves similar to current_user in the sense that it is available everywhere (controllers and views) but I'm struggling to actually know what to search for to find the answer.
The closest post on SO that I've been able to find is this one, but it's for Ruby rather than Python, could someone point me in the right direction? Thanks!

What I have so far:
In my __main__.py I have this:
@app.context_processor
def foo_processor():
    def foo():
        return 'Hello World'

The result of this is that I can access {{ foo }} in my Jinja templates without having to send it through from my controller. Unfortunately, I can't access foo within my controllers, and this is what I would like to also be able to do. Do I need to import it somehow, and if I do, how?

A: If I understand this correctly, you want a variable you can use in your templates and the controllers without having to pass it into the templates each time. To do this, first, create a function to get the variable. This could be something like getting a user's setting. Then in the context processor, you pass the result of this function through. To access it in your controllers as well, create an additional variable that holds the value of the getter. Note that if the function returns different values, you may need to call the function instead of using a variable.
# create a getter function, this returns the property's value.
def get_property():
  return "Test Text"

property = get_property() # this is only to make code pretty later on.

# the context processor passes the property to the templates.
@app.context_processor
def property_processor():
  return dict(property=get_property())

In your controllers, you can access the variable created earlier.
def view():
  if property == true:
    return redirect(url_for('index'))
  else:
    return redirect(url_for('access_denied'))

Note that if your value will change, you may need to use the function instead and recall the getter each time you render a view. This would make the first if statement into if get_property() == true: instead.


Q: How to update srore after fetching data with RTK i am learning react js by doing a project wher i am using RTK to manipulate the state of my app . The problem is after fetching data i want my store to change automatically . this is my server
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const openSeaApi = createApi({
  reducerPath: "collectionsApi",
  baseQuery: fetchBaseQuery({
  baseUrl: `https://testnets-api.opensea.io/api/v1`,
}),

 endpoints: (builder) => ({
 retreiveCollections: builder.query({
  query: ({ asset_owner, offset, limit }) =>
    `collections?asset_owner=${asset_owner}&offset=${offset}&limit=${limit}`,
 }),
 }),
 });

  export const { useRetreiveCollectionsQuery } = openSeaApi;

This is my slice file:
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
 allCollections: [],
 isError: false,
 isSuccess: false,
 isLoading: false,
  message: "",
};

  export const collectionsSlice = createSlice({
    name: "collection",
    initialState,
reducers: {
  appendCollections: (state, action) => {
   state.allCollections = { ...state.allCollections, ...action.payload };
  },
 },
});

 export const { appendCollections } = collectionsSlice.actions;
 export default collectionsSlice.reducer;

this my store.js
import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/dist/query";
import collectionReducer from "../features/collections/collectionSlice";
import { openSeaApi } from "../services/openseaService";

export const store = configureStore({

reducer: {
collection: collectionReducer,
[openSeaApi.reducerPath]: openSeaApi.reducer,
 },

  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(openSeaApi.middleware),
   });
       setupListeners(store.dispatch);

and my component
  const user = JSON.parse(localStorage.getItem("user"));

   const { data, isError, isLoading } = useRetreiveCollectionsQuery({
   asset_owner: user?.account,
    offset: 0,
    limit: 300,
 });

So when i look in my store i fiend the collection reducer but it doesn't get the data even after the action is fulfilled . how can i put the data into the collections array in the store . thank you .

A: That data is already in the store. The point is that RTK Query manages the data for you - you don't have to write a slice by hand any more. Just use the hook in your component and you're done.


Q: $.ajax({ }) Post request to a PHP file is returning a null value I have been looking at this problem for quite a while now and cannot seem to figure out why I keep receiving null after my $.ajax function is called.I input an associative array that contains my method name and then call my method in PHP to return a j son string back to the front end. I receive null when I call alert in my java script. Here is my code
Java script:
   $(document).ready(function()
   {
     var data = {};
     data["Method"] = "test";
     $.ajax({

            url:"test.php/test",
            data: data,
            type:"POST",
            contentType:"application/json",
            dataType:"json",
            success: function(data){

            alert(data);

            },
            error:function(data, textStatus, error)
            {

            }
     });
});

PHP:
   <?

    //require_once("database.php");

    class methods
    {
      function __contructor()
      {
        if(isset($_POST["Method"]))
        {
              $function = $_POST["Method"];
              call_user_func($function);
        }
        else
        {
              echo "{\"status\":\"false\"}";
        }
     }

      function test()
      {
            $json = array(
            "kyle" => "broflowksi",
            "eric" => "cartman",
            "stan" => "marsh"
             );
            echo json_encode($json);
      }

   }

     $method = new methods();

   ?>

A: What you are trying to call is an instance method. Call it this way:
if(isset($_POST["Method"]))
{
      $function = $_POST["Method"];
      $method = new ReflectionMethod('methods', $function);
      $method->invoke($this);
}

A: Try forcing a content-type header before sending the output,
header("Content-type: application/json");

A: There's simply a typo in your class constructor method, it should be
function __construct()

One other thing to keep in mind is that I'm not sure you should be setting the contentType to json, as that variable is for what you're sending... not what you're receiving.
So if you end up having a situation where the post variables are being stripped, try and remove the contentType form your ajax call.

A: Try removing the echo in test method. You are calling
 call_user_func($function);

and your $function is not returning but echoing, .i.e
function test() {
        $json = array(
        "kyle" => "broflowksi",
        "eric" => "cartman",
        "stan" => "marsh"
         );
        echo json_encode($json);          // This line should be returning
}

I had dealt with similar issue earlier with a php function call (not in ajax particular).to catch.


Q: geomintersect function I am using geomintersect code in QGIS to only retrieve a target field from a target point layer if the target point layer intersects with the start point or endpoint of the line layer. or Vice versa (retrieving a target field from a target line layer if only the start point or endpoint intersects with the point layer).
I tried to use this function startpoint(geomintersects('targetLayer','targetField')) but I got no result.
what is the most recommended function to retrieve a field when only a point intersects a start or endpoint of a line?

A: You can not do this directly using fieldcalculator and expressions, unfortunately. This is because you can not tell geomintersects() to be something else than the geometry itself, like a start_point of this geometry. You could only get the geometry of the intersecting point this way, by using intersection(start_point($geometry),geom_from_wkt(geomintersects('pointlayer','$geometry'))), but there is no chance to get a value of another layer by intersects(), intersection() or geomintersects(). You can only get its geometry. Therefore get_feature() or get_feature_by_id() cannot be used.

So you need to use a workaround. One could be to build a virtual layer, like this:
select linelayer.lineid, pointlayer.id, pointlayer.geometry from linelayer, pointlayer where st_intersects(st_startpoint(linelayer.geometry), pointlayer.geometry)

In this example I create a new pointlayer with the geometry of the intersecting points of the pointlayer with startpoints of the linelayer having attributes from both, the pointlayer and the linelayer. Of course you could also make this virtual layer a line, by using
select linelayer.lineid, pointlayer.id, linelayer.geometry from linelayer, pointlayer where st_intersects(st_startpoint(linelayer.geometry), pointlayer.geometry)

instead.
A great advantage of virtual layers is, that they get updated automatically if you change your point- or polygonlayer.


Q: How do I incorporate await sleep(milliseconds) between two set of messages in MS Bot Framework? I am developing a Bot using NodeJs which should ask the user a set of questions and then after a break, ask the same another of questions again.
I am using await sleep(milliseconds) in between.
While testing using the Emulator, I noticed that the questions from the first set are sent one by one, saving the user's response. The second set is sent all at once without allowing the user to respond to each question of the second set individually.
 await turnContext.sendActivity(askFirstSetOfQuestions(question));
 await sleep(60000);
 await turnContext.sendActivity(askSecondSetOfQuestions(question));

 await next();

image - screen capture from emulator

Quite lost here..
any help would be appreciated.

A: There are two things to consider here. First, if you truly need a delay, it is better to await a promise than use sleep. You can do this via await new Promise (resolve => setTimeout(resolve, DELAY_LENGTH);. I use this frequently in conjunction with typing indicator to give the bot a more natural feeling conversation flow when it sends two or more discrete messages without waiting for user input.
However, as Eric mentioned, it seems like you might want a waterfall dialog instead for your use case. This sample from botbuilder-samples is a good example. Each step would be a prompt, and it will wait for user input before proceeding. I won't try to write an entire bot here, but a single question-answer step would look something like:
async firstQuestion(stepContext) {
    return await stepContext.prompt(TEXT_PROMPT, 'Question 1');
}

async secondQuestion(stepContext) {
    stepContext.values.firstAnswer = stepContext.result;
    return await stepContext.prompt(TEXT_PROMPT, 'Question 2');
}

and so forth. Not sure what you are doing with the responses, but in the example above I'm saving it to stepContext.values so that the answers are all available in later steps as part of the context object.
If you can detail more of what your use case/expected behavior and share what askFirstSetOfQuestions is, we could provide further assistance.


Q: Как скачать файл по URL на C# Core? Есть список с ссылками, на скачивание файлов (к примеру, https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2002.xml.zip). Мне нужно скачать все файлы из этого списка в определённую папку. Как это сделать на C# Core?
Полагаю, что нужно использовать HttpClient() вместо, ранее используемого, WebClient().
На старых версиях C# можно было выполнить так:
var сlient = new WebClient();
string path = "some/path/to/download";
webClient.DownloadFile("https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2002.xml.zip", path);

Как выполнить скачивание в C# Core? Он не поддерживает класс WebClient().

A: Решил данный вопрос:
public static async void DownloadFile(string url, string path)
{
    byte[] data;

    using (var client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(url))
    using (HttpContent content = response.Content)
    {
        data = await content.ReadAsByteArrayAsync();
        using (FileStream file = File.Create(path)) //path = "wwwroot\\XML\\1.zip"
            file.Write(data, 0, data.Length);
    }
}


Q: Proving that $\frac{\pi ^2}{p}\neq \sum_{n=1}^{\infty }\frac{1}{a_{n}^2}$ we have many formula for $\pi ^2$ as follow $$\frac{\pi ^2}{6}=\frac{1}{1^2}+\frac{1}{2^2}+\frac{1}{3^2}....$$
and $$\frac{\pi ^2}{8}=\frac{1}{1^2}+\frac{1}{3^2}+\frac{1}{5^2}....$$ and for $\frac{\pi ^2}{9}$, $\frac{\pi ^2}{12}$, $\frac{\pi ^2}{16}$,$\frac{\pi ^2}{24}$.. and so on. If you see the number in denominator is not prime.Now we want to prove that
  $$\frac{\pi ^2}{p}\neq \sum_{n=1}^{\infty }\frac{1}{a_{n}^2}$$ Where $p$ is a prime number and $a_{n}$ a positive integer number

A: I ran the greedy algorithm from the previous question for the first 1000 primes with the added caveat that the terms in the sequence have to be distinct. It appears that your statement is only true for the primes 2, 3, 5, 11, 13 and false for the rest! I've only used 40 terms in the algorithm for each of the primes. For those that work, the accuracy is quite good (hundreds of digits for the larger primes). For example if $A_p$ stands for the terms for prime p then
$$A_7 = \{1, 2, 3, 5, 11, 42, 991, 59880, 21165404, 81090759408,\ldots \}$$
and if $S_p(n)$ stands for the partial sum we have
$$S_7(10) = \frac{9409086091684410250487330038662170074145032522104397}{66733781786148561048500788381308231
   67971682291718400} $$
with
$$\frac{\pi^2}{7}- S_7(10) \approx 3.0292 \cdot 10^{-34}$$
EDIT: I ran the algorithm again but this time with the integers from 1 to 100 because I suspected the problem is not just with the primes themselves. The algorithm failed to converge within 15 terms for the numbers
$$E = \{1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15\}$$
The algorithm is way off for these integers. I'm willing to conjecture that for every integer $k\notin E$ there exists a sequence of positive integers $a_{n,k}$ such that
$$\frac{\pi^2}{k} = \sum_{n = 1}^{\infty} \frac{1}{a_{n,k}^2}$$

A: If you don't want to put any restrictions on the $a_n$, there is no number theory here, only analysis. If I may quote from my previous answer:

Theorem: Let $\sum_k s_k$ be a convergent sum of positive numbers, say $S=\sum_k s_k$. Suppose that, for all $n$, we have $s_n < \sum_{k=n+1}^\infty s_k$. Then there is a subsequence of $s_k$ whose sum converges to $x$ for any positive $x < S$.

Intuitively, say we're trying to construct a subsequence. The sum is convergent, so its terms must become arbitrarily small and thus allow us to approach $x$ arbitrarily closely. The only thing that can go wrong is that at some point all the  terms we have left aren't big enough to get us to $x$. The condition $s_n < \sum_{k=n+1}^\infty s_k$ ensures that, whenever this happens, we'll have room to use the earlier term $s_n$ without exceeding $x$, and so the only way we can't get to $x$ is if we were already using all the earlier terms (i.e., $x>S$).
The series $\sum_{k=2}^\infty \frac{1}{n^2}$ satisfies the hypotheses of this theorem, and so we can write any number less than $\sum_{k=2}^\infty \frac{1}{n^2}=\frac{\pi^2}{6}-1$ as a sum of the reciprocals of distinct squares (with $a_1>1$). Similarly, if $1 < x < \frac{\pi^2}{6}$, we can write $x-1$ as a sum of the reciprocals of distinct squares, and then throw in a $1$ at the beginning to get such a representation for $x$ (with $a_1=1$).
In particular, if $p$ is prime, $\frac{\pi^2}{p}$ can be written in the form you want unless $p \in \{2,3,5,11,13\}$. But that has nothing to do with their primality: it's all about the gross size of $\frac{\pi^2}{p}$.
The interesting number theory happens when you put further conditions on the $a_n$, such as requiring them to be in arithmetic progression...


Q: Where are results stored when opt_output_files() = "" in the lidR package? I'm revisiting code where I've set opt_output_files() <- ""; i.e., no specified location or name. (I would have found this usage online somewhere but can't find the source now.)
Is output stored in a temporary directory? I don't see anything in folder indicated by tempdir().
The pixel_metrics() function has stopped midway, and I am hoping to recover what has been processed so far.
bigCat <- readLAScatalog("F:/working/las")
opt_output_files(bigCat) <- ""
metrics_w2w <- pixel_metrics(bigCat, .stdmetrics_z, res = 20, pkg = "terra")

A: When the successive outputs are not written to disk they are stored in R memory as regular R objects like any classical code.
When a function processing a catalog fails midway it does not actually fails programmatically speaking and it returns a partial output. In your case metrics_w2w is not empty which would have been the case in an actual failure scenario.
With opt_restart(bigCat) = 42 you can redo the computation starting at chunk 42. However there is no function to merge the first partial output with the second. You must do some processing yourself. But at least the 42 first chunks are not supposed to be lost.


Q: What is the meaning of mode(x).mode[0]? I am trying to find mode along a column(named Outlet_Size) of a dataset using pandas library of python which contains values in the form of {small, medium,large} corresponding to 10 different outlet stores with total of 1000+ rows.enter image description here.
For Finding the mode along that column for each store type the following code was used:
Determing the mode for each type of outlet(10 different types)
outlet_size_mode = data.pivot_table(values='Outlet_Size', columns='Outlet_Type',aggfunc=(lambda x:mode(x).mode[0]) ) .
However I am unable to understand the format of using the lambda function mode(x).mode[0]. What is the meaning of that?

A: For a column having several rows mode(x) can be an array as there can be multiple values with high frequency. We will take the first one by default always using: mode[0] at the end.


Q: Creating a COM port out of a ttyUSB port in Ubuntu The Question
I'm having to work with a rather awkward API at the moment which insists on me giving the address of a device, linked via USB port, in the form COM*. However, on the Ubuntu machine on which I'm working, and have to use, if I plug in this device it will automatically be assigned an address in the form /dev/ttyUSB*.
Given that I can't modify the source code of the API - which I would dearly like to do! - what is the least painful way getting the API to talk to said device?
Extra Detail
An example of how to use the API from the manual:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.caen.RFIDLibrary;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      CAENRFIDReader MyReader = new CAENRFIDReader();
      MyReader.Connect(CAENRFIDPort.CAENRFID_RS232, "COM3");
      CAENRFIDLogicalSource MySource = MyReader.GetSource("Source_0");
      CAENRFIDTag[] MyTags = MySource.InventoryTag();

      if (MyTags.Length > 0)
      {
        for (int i = 0; i < MyTags.Length; i++)
        {
          String s = BitConverter.ToString(MyTags[i].GetId());
          Console.WriteLine(s);
        }
      }
      Console.WriteLine("Press a key to end the program.");
      Console.ReadKey();
      MyReader.Disconnect();
    }
  }
}

The line MyReader.Connect(CAENRFIDPort.CAENRFID_RS232, "COM3"); is where I'm running into problems.
A little later in the manual, it states that the Connect method is to have two parameters:

ConType: The communication link to use for the connection.
Address: Depending on ConType parameter: IP address for TCP/IP communications ("xxx.xxx.xxx.xxx"), COM port for RS232 communications ("COMx"), an index for USB communications (not yet supported).

Bonus Question
The API in question seems to have been written on the assumption that it would be run on a Windows machine. (It's in C#.) The COM* format seems to be favoured - I'm happy to be corrected on this point - by Windows architectures, whereas Ubuntu seems to favour the ttyUSB* format. Assuming that I can funnel the data from my device from a ttyUSB* port to a COM* port, will the API actually be able to find said data? Or will it incorrectly follow the default Windows path?

A: Given the new information i suspect you can just give the ttyUSB as the parameter, mono will handle the connection correctly. However the same caution for the line endings below still applies. You might also consider making the parameter a command-line parameter thus making your code run on any platform by being able to supply the COM/USB through the command line parameters. I see no other issues using this code. Did you try it yet?
PS: i think your confusion is actually the statement usb id's are not supported yet, i suspect that is because the library relies on a (text-based) serial connection wich are fundamentally different from direct USB connections (wich drivers normally handle) that handle the connection in a more direct way. The ttyUSB ports on linux however DO represent the (UART) serial connections the same way as windows COM-ports, these are not direct USB connections.
Some handy info about the differences: https://rfc1149.net/blog/2013/03/05/what-is-the-difference-between-devttyusbx-and-devttyacmx/
Old answer
I am assuming you run this program on Mono?
Mono expects the path to the port, so COM* will not do. You could try creating a symlink named COM* to the ttyUSB*. Preferrably located in the environment directory. Once you get them linked the program should see no difference. However line endings in the data/program might be different than on windows. If the device expects CRLF and the program uses Environment.NewLine you might get unexpected behaviour too. It might just be easier if you have the permission/rights to edit the assembly with recompilation tools.


Q: Python Socket Programming: Upload files from Client to Server I'm looking to find some assistance in my python socket programming.
Objective: upload a file from the Client to the Server. My current setup involves two virtual machines, a Server and a Client, where the respective .py files will reside; server.py and client.py . The issues I'm experiencing is, that when I go to choose the upload option, the output reads "File uploading.... File successfully uploaded" But when I look on the server side, the file doesn't exist - nor do I receive an error. The server shows that it received a connection when I send the file to upload. What I have currently is below... Any assistance would be greatly appreciated.

Server.py
import config, protocol
import os
from socket import *
import threading
import time
import sys

class server():

    # Constructor: load the server information from config file
    def __init__(self):
        self.port, self.path, self.path2 = config.config().readServerConfig()

    # function to receive file data from client
    def receiveFile(self, serverSocket, fileName):
        serverSocket.connect()
        serverSocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
        with open(fileName, 'wb') as f:
            print('file incoming...')
            while True:
                print('receiving data...')
                data = serverSocket.recv(1024)
                if not data:
                    break
                f.write(data)
        print(fileName + " has been Received!")
        serverSocket.close()

    # Main function of server, start the file sharing service
    def start(self):
        serverPort=self.port
        serverSocket=socket(AF_INET,SOCK_STREAM)
        serverSocket.bind(('',serverPort))
        serverSocket.listen(20)
        print('The server is ready to receive')
        while True:
            connectionSocket, addr = serverSocket.accept()
            print("**Conn. to ", addr)
            dataRec = connectionSocket.recv(1024)
            header,msg= protocol.decodeMsg(dataRec.decode()) # get client's info, parse it to header and content
            # Main logic of the program, send different content to client according to client's requests
            if(header== protocol.HEAD_REQUEST):
                self.listFile(connectionSocket)
            elif(header == protocol.HEAD_DOWNLOAD):
                self.sendFile(connectionSocket, self.path+"/"+msg)
            elif(header == protocol.HEAD_UPLOAD):
                self.receiveFile(connectionSocket, self.path2+"/"+msg)
            else:
                connectionSocket.send(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
            connectionSocket.close()

def main():
    s=server()
    s.start()

main()

Client.py
import config, protocol
from socket import *
import threading
import time
import os
import sys

class client:

    fileList=[] # list to store the file information
    uploadFileList = []

    #Constructor: load client configuration from config file
    def __init__(self):
        self.serverName, self.serverPort, self.clientPort, self.downloadPath, self.uploadPath = config.config().readClientConfig()

    # Function to produce user menu
    def printMenu(self):
        print("Welcome to simple file sharing system!")
        print("Please select operations from menu")
        print("--------------------------------------")
        print("3. Upload File")
        print("5. Quit")

    # Function to get user selection from the menu
    def getUserSelection(self):
        ans=0
        # only accept option 1-4
        while ans>5 or ans<1:
            self.printMenu()
            try:
                ans=int(input())
            except:
                ans=0
            if (ans<=5) and (ans>=1):
                return ans
            print("Invalid Option")

    # Build connection to server
    def connect(self):
        serverName = self.serverName
        serverPort = self.serverPort
        clientSocket = socket(AF_INET, SOCK_STREAM)
        clientSocket.connect((serverName,serverPort))
        return clientSocket

    def getUploadFileList(self):
        self.uploadFileList = os.listdir(self.uploadPath)

    def printUploadFileList(self):
        count = 0
        for f in self.uploadFileList:
            count += 1
            print('{:<3d}{}'.format(count, f))

    def selectUploadFile(self):
        if (len(self.uploadFileList)==0):
            self.getUploadFileList()
        ans=-1
        while ans<0 or ans>len(self.uploadFileList)+1:
            self.printUploadFileList()
            print("Please select the file you want to upload from the list (enter the number of files):")
            try:
                ans=int(input())
            except:
                ans=-1
            if (ans>0) and (ans<len(self.uploadFileList)+1):
                return self.uploadFileList[ans-1]
            print("Invalid number")

    def uploadFile(self, fileName):
        mySocket=self.connect()
        mySocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
        f = open(fileName, 'rb')
        l = f.read(1024)  # each time we only send 1024 bytes of data
        while (l):
            print('File uploading...')
            mySocket.sendall(l)
            l = f.read(1024)
        f.close()
        print("File Uploaded Successfully!")

    # Main logic of the client, start the client application
    def start(self):
        opt=0
        while opt!=5:
            opt=self.getUserSelection()
            if opt==3:
                self.uploadFile(self.selectUploadFile())
            else:
                pass

def main():
    c=client()
    c.start()

main()

I've defined modules in the protocol file that I have...

Protocol.py
HEAD_LIST='LST'
HEAD_REQUEST='REQ'
HEAD_DOWNLOAD='DLD'
HEAD_UPLOAD='ULD'
HEAD_FILE='FIL'
HEAD_ERROR='ERR'

# we prepare the message that are sent between server and client as the header + content
def prepareMsg(header, msg):
    return (header+msg).encode()

def prepareFileList(header,fList):
    '''
    function to prepare file list to msg
    '''
    msg=header
    for i in range(len(fList)):
        if (i==len(fList)-1):
            msg+=fList[i]
        else:
            msg+=fList[i]+','
    return msg.encode()

# Decode the received message, the first three letters are used as protocol header
def decodeMsg(msg):
    if (len(msg)<=3):
        return HEAD_ERROR, 'EMPTY MESSAGE'
    else:
        return msg[0:3],msg[3:len(msg)]

I've also defined my config file as follows...

Config.py
class config:
    #define header
    server_port='SERVER_PORT'
    path="PATH"
    path2="PATH2"
    server="SERVER"
    client_port="CLIENT_PORT"
    download="DOWNLOAD"
    upload="UPLOAD"
    serverConfig="server.config"
    clientConfig="client.config"

    def __init__(self):
        pass
    def readServerConfig(self):
        try:
            with open(self.serverConfig,'r') as f:
                serPort=0
                sharePath=""
                sharePath2=""
                for l in f:
                    sub=l.strip().split("=")
                    if(sub[0]==self.server_port):
                        serPort=int(sub[1])
                    elif(sub[0]==self.path):
                        sharePath=sub[1]
                    elif (sub[0] == self.path2):
                        sharePath2 = sub[1]

                    else:
                        pass
                return serPort, sharePath, sharePath2
        except:
            print(Exception.message())

    def readClientConfig(self):
        '''
        This function read client configuration file, return four values
        @return: serverName
        @return: serverPort
        @return: clientPort
        @return: downloadPath
        '''
        try:
            with open(self.clientConfig,'r') as f:
                serPort=0
                serName=""
                clientPort=0
                downPath=""
                upPath=""
                for l in f:
                    sub=l.strip().split("=")
                    if(sub[0]==self.server_port):
                        serPort=int(sub[1])
                    elif(sub[0]==self.server):
                        serName=sub[1]
                    elif(sub[0]==self.client_port):
                        clientPort=sub[1]
                    elif(sub[0]==self.download):
                        downPath=sub[1]
                    elif(sub[0]==self.upload):
                        upPath=sub[1]
                    else:
                        pass
                return serName, serPort, clientPort, downPath, upPath
        except:
            print(Exception.message())

# The function to test the configuration class
def test():
    conf=config()
    client=conf.readClientConfig()
    server=conf.readServerConfig()
    print(client)
    print(server)

The above code will return a file list, I can choose which file I'd like to upload, and the code will state its complete but I cannot find the files on the server. I have test files set up in directories paths on both machines. in addition, my server.config and client.config files are set up as:
server.config
SERVER_PORT=12007
PATH=/root/serverFiles
PATH2=/root/files

client.config
SERVER=192.168.10.1
SERVER_PORT=12007
CLIENT_PORT=12006
DOWNLOAD=/root/Downloads
UPLOAD=/root/Upload

A: Your uploadFile() method will connect() to the server and then sendall() the file content (in 1024 byte chunks).
Your server, on the other hand, will receive the first 1024 bytes (i.e. the first 1024 bytes of file content), and interpret it according to the protocol, looking at the first three bytes of the file content. The client, however, never sends protocol.HEAD_UPLOAD as the server expects.
(BTW, I would really recommend you PEP8 the code, and refrain from * imports. It makes the code much easier to read, and thus to help.)


Q: Jquery ui Selectable() cant properly unselect outside the method I have a table with selectable objects as follow :
/* ESPACE OU LES TATOUAGES SONT SELECTABLE */
$(".tatooInk > tbody").bind("mousedown", function(e) {
  e.metaKey = true;
}).selectable();
 $( ".tatooInk > tbody" ).selectable({
        filter: ":not(td, img ,b,span,div)",
        /* Quand on select un tatoo */
        selected: function( e, ui ) {
                if(tatoos.length < 28){
                    // JSON.stringify(ui.selected);
                    console.log($( ui.selected ).html());
                    $( ui.selected ).addClass( "ui-state-highlight" );
                    getAllTats( $(ui.selected) );
                    updateCode();
                }
                else{
                    alert('trop de tatouages');
                    $(ui.selecting).removeClass("ui-selecting");
                }
            },
        unselected: function( e, ui ) {

                $( ui.unselected ).removeClass( "ui-state-highlight" );
                removeTat( $(ui.unselected) );
                updateCode();
            }
     });

This code works great, when i select an item in my list it looks like this :
At another place in my code, i do some modification depending what has been selected
At another, another, place in my code, if the conditions are meeted i unselect manually using this code
function TabletatooDel(url){
    $('.tatooInk tr').each(function(){
        var lien = $(this).children(':nth-child(1)').children().attr('src');
        if(lien == url){
            $(this).removeClass('ui-selected ui-state-highlight');
            $(this).trigger('unselecting');
            $(this).trigger('unselected');

        }
    });
}

When passing through that, this is what i think happens :

Even if i removed every Class, when i click on the previously unselected element, even if it goes like this again
The modifications depending on my select DOESNT run.
I have to unselect it again, by clicking on it, and reselect it again in order to have the modifications running.
Any idea how to properly unselect out of the method ?

A: ... It's ok ! I found my problem. I forgot to erase the tatoo out of a json list containing them all.
It looks like this now :
for(var i=0; i< tatoos.length; i++){

                if(tatoos[i].url === url ){
                    tatoos.splice(i, 1);
                }
            }
            $(this).removeClass('ui-state-highlight');
            $(this).removeClass('ui-selected');
            $(this).children(':nth-child(4)').removeClass( "tatooSelect" );


Q: GLSL compute world coordinate from eye depth and screen position I'm trying to recover WORLD position of a point knowing it's depth in EYE space, computed as follow (in a vertex shader) :
float depth = - uModelView * vec4( inPos , 1.0 ) ;

where inPos is a point in world space (Obviously, I don't want to recover this particular point, but a point where depth is expressed in that format).
And it's normalized screen position (between 0 and 1), computed as follow (in a fragment shader ) :
vec2 screen_pos = ( vec2( gl_FragCoord.xy ) - vec2( 0.5 ) ) / uScreenSize.xy ;

I can access to the following info :

*

*uScreenSize : as it's name suggest, it's screen width and height

*uCameraPos : camera position in WORLD space

and standard matrices :

*

*uModelView : model view camera matrix

*uModelViewProj : model view projection matrix

*uProjMatrix : projection matrix

How can I compute position (X,Y,Z) of a point in WORLD space ? (not in EYE space)
I can't have access to other (I can't use near, far, left, right, ...) because projection matrix is not restricted to perspective or orthogonal.
Thanks in advance.

A: I get your question right, you have x and y as window space (and already converted to normalized device space [-1,1]), but z in eye space, and want to recosntruct the world space position.

I can't have access to other (I can't use near, far, left, right, ...)
  because projection matrix is not restricted to perspective or
  orthogonal.

Well, actually, there is not much besides an orthogonal or projective mapping which can be achieved by matrix multiplication in homogenous space. However, the projection matrix is sufficient, as long as it is invertible (In theory, a projection matrix could transform all points to a plane, line or a single point. In that case, some information is lost and it will never be able to reconstruct the original data. But that would be a very untypical case).
So what you can get from the projection matrix and your 2D position is actually a ray in eye space. And you can intersect this with the z=depth plane to get the point back.
So what you have to do is calculate the two points
vec4 p = inverse(uProjMatrix) * vec4 (ndc_x,  ndc_y, -1, 1);
vec4 q = inverse(uProjMatrix) * vec4 (ndc_x,  ndc_y,  1, 1);

which will mark two points on the ray in eye space. Do not forget to divide p and q by the respective w component to get the 3D coordinates. Now, you simply need to intersect this with your z=depth plane and get the eye space x and y. Finally, you can use the inverse of the uModelView matrix to project that point back to object space.
However, you said that you want world space. But that is impossible. You would need the view matrix to do that, but you have not listed that as a given. All you have is the compisition of the model and view matrix, and you need to know at least one of these to reconstruct the world space position. The cameraPosition is not enoguh. You also need the orientation.


Q: Accessing 32 bit hive in .Net Core Application What is the correct way to access 32 bit registry hive on a 64 bit machine? I tried the following code to set some value in HKCU\Software 32 bit hive but it still gets the 64 bit hive. I couldnt find any alternate api to pass RegistryView enum, In C++ the Wow64 flag can be specified when opening/creating a key but I dont find similar usage in Microsoft.Win32 library.
[SupportedOSPlatform("Windows")]
void SetValue()
{
    using var key = GetOrCreateKey(RegistryHive.CurrentUser,
            RegistryView.Registry32,
            @"SOFTWARE\MyApp\Key"
            );

    key?.SetValue("Value", 1);
}

[SupportedOSPlatform("Windows")]
static RegistryKey? GetOrCreateKey(RegistryHive hive, RegistryView view, string keyPath)
{
    using var baseKey = RegistryKey.OpenBaseKey(hive, view);
    var subKey = baseKey?.OpenSubKey(keyPath);
    if (subKey != null)
    {
        return subKey;
    }

    return baseKey?.CreateSubKey(keyPath);
}

On 64 bit machine, I want the value to be set on key on HKEY_CURRENT_USER\Software\Wow6432Node\MyApp\Key but its getting written on HKEY_CURRENT_USER\Software\MyApp\Key


Q: Invalid Argument Error while installing Ubuntu 11.10 I got this error when I was installing ubuntu directly from CD choosing the option 'inside windows' [XP] , I had tested several times on C drive [30 GB free space] as well as on other drives with minimum 20 GB free space. how can I fix this problem ?

A: you used wubi app to that this program very good but still have problem with somebody i'm one of them
try another partition
see that first may help you https://wiki.ubuntu.com/WubiGuide
then do that
1.with any program partition tools liked parted magic or acrions or other make unallocated free space partition take al least 5 giga free space
2.create any partition in that new unallocated space and make it fat32 not ntfs because ntfs make problem sometimes
3.make this new partition primary
4.format it with slow format from partiton program or if you hard drive old you can do that with this command in cmd format X:
x refer to new hard drive
5.after that make defragmentation for it
6.now try to install it
if problem continue change step number 2 and make it ntfs if still change step number 3 and make it logical
i know that wubi must be found to don't do any of above any install ubuntu like any software in windows but as i said it still have problem with it
so it's many solution that other advise us to do and you can search in google about wubi problem to see that
and the best is install ubuntu with default way as any operting system or install it in virtualbox and i see the second idea is best beacuse you will can use windows and linux in same time


Q: visibility map: all visible pages The relallvisible field in pg_class view display the Number of pages that are marked all-visible in the table's visibility map.
When I try this example:
INSERT INTO foo (x) SELECT n FROM generate_series(1, 10000000) as n;

analyze table foo;

select nspname, relpages, reltuples, relallvisible, relfrozenxid, relminmxidfrom pg_class as c
join pg_namespace as ns on c.relnamespace = ns.oid
where relname = 'foo';
 nspname | relpages |  reltuples  | relallvisible | relfrozenxid | relminmxid
---------+----------+-------------+---------------+--------------+------------
 public  |    44248 | 9.99998e+06 |             0 |        60995 |          1
(1 row)

Why is relallvisible field equal to 0 and not equal to the total number of pages that is 44248?

A: Because VACUUM has never run on the table. That command builds and maintains the visibility map.
You are probably on PostgreSQL v12 or lower, and the table not received enough updates or deletes to trigger autovacuum. If your use case involves insert-only tables, upgrade – from v13 on, autovacuum will also run on insert-only tables.


Q: When an iOS application goes to the background, are lengthy tasks paused? Yes, I know if I wish my app to be responsive to users' multitasking actions, such as switch to another app, I should deal with
- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidBecomeActive:(UIApplication *)application

What if my app is doing a quite-long time consuming operation (like downloading a big file) and the user causes my app to enter the background? Will that operation automatically be suspended and resumed when the user comes back to my app?
What exactly will happen behind the scene when my app enters the background or resumes in the foreground?
What if when users let my app go to the background my app's execution is just in the middle of a method?
For e.g., my app is doing
for (int i = 1 to 10000K) {
    do some calculation;
}

When i== 500K, user switches to another app. What happens to the for-loop in my app?

A: From the documentation:

Return from applicationDidEnterBackground(_:) as quickly as possible. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method doesn’t return before time runs out, your app is terminated and purged from memory.

If you need additional time to perform any final tasks, request additional execution time from the system by calling beginBackgroundTask(expirationHandler:). Call beginBackgroundTask(expirationHandler:) as early as possible. Because the system needs time to process your request, there’s a chance that the system might suspend your app before that task assertion is granted. For example, don’t call beginBackgroundTask(expirationHandler:) at the very end of your applicationDidEnterBackground(_:) method and expect your app to continue running.

If the long-running operation you describe above is on the main thread and it takes longer than 5 seconds to finish after your application heads to the background, your application will be killed.  The main thread will be blocked and you won't have a chance to return from -applicationDidEnterBackground: in time.
If your task is running on a background thread (and it really should be, if it's taking long to execute), that thread appears to be paused if the application returns from -applicationDidEnterBackground: (according to the discussion in this answer).  It will be resumed when the application is brought back to the foreground.
However, in the latter case you should still be prepared for your application to be terminated at any time while it's in the background by cleaning things up on your way to the background.

A: If you are doing some operation which might consume time and you don't want to kill it then you can extend the time for your operation by executing in UIBackground Task i
{
    UIBackgroundTaskIdentifier  taskId = 0;
    taskId = [application beginBackgroundTaskWithExpirationHandler:^{
        taskId = UIBackgroundTaskInvalid;
    }];

// Execute long process. This process will have 10 mins even if your app goes in background mode.

}

The block argument called "handler" is what will happen when the background task expire (10min).
Here is a link to the documentation

A: Like mentioned above, there are a few cases where your app runs in the background and apple can allow or deny depending on what you are doing.
https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
More importantly if you do fit into one of these categories your app refresh rate is determined by an apple algorithm that takes into consideration your app usage on that device vs other apps. If your app is used more often then it gets more background time allotted. This is just one variable but you get the idea that background time allocation varies app to app and not under your control.


Q: Packet Tracer 7.3.0 cannot be installed on Ubuntu I noticed that Ubuntu 20 Release, comes with many unmet dependencies with some of them already deprecated and almost impossible to install. I see this when I try to install Packet Tracer and it outputs that requires many dependencies that at the same time need to install other dependencies.
Note: If you have a solution, I hope it worked out for you on a VM with Ubuntu 20 before suggesting it.
m@m:~/Desktop$ sudo dpkg -i PacketTracer_730_amd64.deb
Selecting previously unselected package packettracer.
(Reading database ... 207479 files and directories currently installed.)
Preparing to unpack PacketTracer_730_amd64.deb ...
Unpacking packettracer (7.3.0) ...
dpkg: dependency problems prevent configuration of packettracer:
 packettracer depends on libdouble-conversion1; however:
  Package libdouble-conversion1 is not installed.
 packettracer depends on qt-at-spi; however:
  Package qt-at-spi is not installed.

dpkg: error processing package packettracer (--install):
 dependency problems - leaving unconfigured
Processing triggers for gnome-menus (3.36.0-1ubuntu1) ...
Processing triggers for desktop-file-utils (0.24-1ubuntu2) ...
Processing triggers for mime-support (3.64ubuntu1) ...
Processing triggers for shared-mime-info (1.15-1) ...
Errors were encountered while processing:
 packettracer
EDIT: The main problem, is with qt-at-spi, libdouble-conversion1 I was able to install manually.
The following packages have unmet dependencies:
 qt-at-spi : Depends: libqt4-dbus (>= 4:4.8.0) but it is not installable
             Depends: libqtcore4 (>= 4:4.8~) but it is not installable
             Depends: libqtgui4 (>= 4:4.8~) but it is not installable

A: I had the same difficulty. After spending a few days googling and trying various suggestions, the following solved most of the problems.

*

*Downloaded and installed libdoule-conversion1 from this link:
https://packages.ubuntu.com/bionic/libdouble-conversion1

*Downloaded PacketTracer_730_amd64.deb from
https://www.netacad.com/portal/resources/packet-tracer

*Unpacked the .deb file and edited the file named control in the DEBIAN folder. I simply opened with text editor and deleted qt-at-spi from the "Depends: libdouble-conversion1, qt-at-spi" line, and saved, repacked as fixed.deb.
Find detailed instructions here.

*Installed the fixed .deb.

*Rebooted.
Now Packet Tracer can only be launched from the terminal, the shortcut icon is not working. I remember seeing a solution for that somewhere, but I don't really mind.


Q: Clear log files on OpenShift - RedHat Debugging my apps on OpenShift is becoming difficult due to excessive log data.
I'm using the terminal command  rhc tail -a appname to view logs
Is there a way to clear the log files via a rhc command? (or any other method)
Any other recommendations for viewing / handling log data on OpenShift?

A: You can use rhc app-tidy <yorApp> to delete the logs and contents of the /tmp directory on the gears (this is used primarily in order to free up some disk space).
You can also ssh into your app rhc ssh <yourApp> and check individual logs in ~/app-root/logs/, which may bring some clarity if you are reading only the log that interests you.

A: Configure logs
To set

*

*maximum file size

*maximum number of files

The maximum file size and maximum number of files can be configured
  with the LOGSHIFTER__MAX_FILESIZE and
  LOGSHIFTER__MAX_FILES environment variables.

$ rhc env set LOGSHIFTER_PHP_MAX_FILESIZE=5M LOGSHIFTER_PHP_MAX_FILES=5 -a myapp
Setting environment variable(s) ... done
$ rhc app stop
RESULT:
myapp stopped
$ rhc app start
RESULT:
myapp started

The exact variable names depend on the type of cartridge; the value of
   is DIY, JBOSSAS, JBOSSEAP, JBOSSEWS, JENKINS, MONGODB,
  MYSQL, NODEJS, PERL, PHP, POSTGRESQL, PYTHON, or RUBY as appropriate.

copied from:
https://developers.openshift.com/managing-your-applications/log-files.html
https://developers.openshift.com/managing-your-applications/environment-variables.html


Q: Draggable elements hang in IE I've got a bug from testers when they double clicked on element or something like then dragged it to the bottom of page,even if draggable element has containment set,mouse goes down than the element. After that you can release mouse click and draggable element hang on mouse pointer. Only in IE :( has anyone any ideea why or how to stop this?
My code looks like :
EDIT: http://jsfiddle.net/j2GyK/
function dragNdrop(){
    for(var i = 0; i < 3; i++){
       dragObjects.push(document.getElementById("box" + i));

    $(dragObjects[i]).css( 'cursor', 'pointer' );
    $(dragObjects[i]).draggable({
            containment:'#decor',
            zIndex: 1000,
            revert: true,

            start: function(event, ui) {
                dragTarget = event.currentTarget; // luam date despre obiectul curent tras
            }
        });
    }

        $("#drop").droppable({
         drop: function( event, ui )
            {
                    dropTarget = event.target; // luam date despre drop target
                    $(dropTarget).prop('src', dragTarget.src);
                    $(dragObjects).css("visibility", "visible");
                    $(dragTarget).css("visibility", "hidden");
                    thisSRC = dropTarget.src.charAt(dropTarget.src.length-5);
                    checkBtn.disabled = false;
        }
    });
}


Q: Is there a way to override a specific keyword color in VS CODE theme (Material Theme)? I'm trying to override specific keywords (import, export, try, catch, await, return etc) of a VS Code "Material Theme"... There's a way to overwrite all the keywords like so
"editor.tokenColorCustomizations": {
    "[Material Theme Darker]": {
        "keywords": "#1ed680"
    }
},

But this overwrites every keyword, and I just need those of a specific blue color... Is there any way to do so? VS Code documentation didn't specify it for certain keywords/tokens

But obviously there's a way to do it... Thanks a lot


Q: String to DateTime conversion in .NET compact Framework I am using .NET compact Framework, more precisely using Windows mobile 6.0 and
was trying to convert a string to datetime but seems it is not supported.
Any help would be appreciated.
Dim provider AS CultureInfo = New CultureInfo("en-US")
Dim dt AS DateTime = Convert.ToDatetime("5/2/2013 5:15:03 PM")

Getting a formatexception issue.

A: Please see the following .NET Fiddle here.
Imports System
Imports System.Globalization

Public Module Module1
    Public Sub Main()
        Dim provider AS CultureInfo = New CultureInfo("en-US")
        Dim dt AS DateTime = Convert.ToDatetime("5/2/2013 5:15:03 PM")
        Console.WriteLine(dt)
        Console.WriteLine(dt.ToString("d",provider))
    End Sub
End Module

Output:


Q: Why vxlan tunnel disappear after ifdown bond? I created a vxlan tunnel using the iprouter2 tool. The command was:
ip link add vxlan2 type vxlan id 2 group 233.1.1.1 dev bond0 dstport 4789

But when I restart network or "ifdown bond0", vxlan2 disappears. It's why? There will be no such problems on CentOS.
I checked the system log and found this information:
Jul 18 11:38:04 ubuntu-22 named[2184]: configuring command channel from '/etc/bind/rndc.key'
Jul 18 11:38:04 ubuntu-22 named[2184]: configuring command channel from '/etc/bind/rndc.key'
Jul 18 11:38:04 ubuntu-22 named[2184]: reloading configuration succeeded
Jul 18 11:38:04 ubuntu-22 kernel: [ 6361.308330] bonding: bond0 is being deleted...
Jul 18 11:38:04 ubuntu-22 kernel: [ 6361.308609] device vxlan2 left promiscuous mode
Jul 18 11:38:04 ubuntu-22 kernel: [ 6361.308733] bond0 (unregistering): Released all slaves
Jul 18 11:38:04 ubuntu-22 named[2184]: any newly configured zones are now loaded

It seems like it was deleted by kernel. I don't want my vxlan tunnel to disappear because of "ifdown bond0". What should I do?
My Ubuntu server information is as follows:
root@ubuntu-22:~# cat /etc/issue
Ubuntu 16.04.2 LTS \n \l
root@ubuntu-22:~# uname -a
Linux ubuntu-22 4.4.0-62-generic #83-Ubuntu SMP Wed Jan 18 14:10:15 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

"bond0" information is as fallows:
root@ubuntu-22:~# cat /proc/net/bonding/bond0
Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)

Bonding Mode: load balancing (round-robin)
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0

Slave Interface: eno1
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: ac:1f:6b:12:57:b4
Slave queue ID: 0

Slave Interface: eno2
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: ac:1f:6b:12:57:b5
Slave queue ID: 0

A: I downloaded the source code of ifupdown to find out the reason. I found that the "/etc/network/if-post-down.d/ifenslave" script was invoked using "/bin/run-parts" when "iface_postdown". At the end of the script, the program will remove the master itself:
# Remove the master itself
echo "-$IFACE" > /sys/class/net/bonding_masters
rm /run/network/ifenslave.$IFACE

When I comment out "echo "-$IFACE" > /sys/class/net/bonding_masters", bond0 will not be deleted.


Q: Cassandra nodetool rebuild_index stuck in 100% in nodetool compactionstats, how to refresh it and to force complection? I have a DC/OS cluster running Cassandra framework, three masters and six workers, after a framework   crash due to registry issues, the Cassandra nodes are not synced with the data, in order to sync it i tried to repair the Keyspaces one by one and check the "./nodetool compactionstats" status.
after the repair i got in the "./nodetool compactionstats" a stuck task:
[root@server-worker1 bin]# ./nodetool compactionstats
pending tasks: 2
- system.IndexInfo: 1
- my_app_prod.profile_activation_history: 1

id                                   compaction type       keyspace          table                      completed total   unit  progress
0d49d3d0-19d6-11eb-a65c-f71e0bcef8b1 Secondary index build my_app_prod profile_activation_history 3010912   3010912 bytes 100.00%
Active compaction remaining time :   0h00m00s
[root@server-worker1 bin]#

the task is stuck in 100%, how can i force it to finish ? or refresh the status of the "./nodetool compactionstats" ?
I checked in the nodes and no such process is running in memory in any node. I need to continue repairing the keyspaces but this task is standing in front of it because until this task is over the repair will wait.

A: Secondary index builds are part of the normal operation of Cassandra when you have secondary indexes on tables. Any new mutation that a node receives will get indexed.
It runs as a compaction thread within the same JVM as the Cassandra process so you won't see a separate process running on a machine's process table.
There's no operation to "force" them to finish. They will finish when the required indexing of data has completed.
Repairs are also part of the normal operation of Cassandra. When new data is streamed to a node during a repair, that data will also be indexed by the receiving node. What I'm getting at is that those operations go hand-in-hand and one does not prevent the other from working. Cheers!


Q: Sorting of an array using merge sort I have implemented  for merge sort in c , although the code seems to be correct the code does not give me the sorted array rather returns the same array that is given to it, that means my merge function  in not working
#include<stdio.h>
#include<stdlib.h>

void re_sort(int arr[],int size);
void merge(int left[],int right[],int arr[],int rightlen,int leftlen);

int main(void)
{
  int a[10];
  int n;

  printf("enter the number\n");

  scanf("%d",&n);

    printf("enter the elements\n");
    for(int i=0;i<n;i++)

      {
         scanf("%d",&a[i]);
      }

    re_sort(a,n);          //merge sort using recursion

    printf("the sorted list is:\n");
    for(int i=0;i<n;i++)

      {  printf("%d\t",a[i]);

      }

    return 0;
}

void re_sort(int arr[],int size)

{  int mid,*left,*right;
   int k=0;
  if(size<2)
    return;

  else
  mid=size/2;
  left=(int*)(malloc(mid*(sizeof(int))));          // two sub arrays left and right
  right=(int*)(malloc((size-mid)*(sizeof(int))));

  for(int i=0;i<mid;i++)
  {
    left[i]=arr[k++];
  }

  for(int j=0;j<(size-mid);j++)
  {
    right[j]=arr[k++];
  }

  re_sort(left,mid);                 //recursion until size becomes less than 2
  re_sort(right,size-mid);
  merge(left,right,arr,size-mid,mid); //both the elements in left and right are merged

}
void merge(int left[],int right[],int arr1[],int rightlen,int leftlen)

{   int arr[100];
    int k=0,i=0,j=0;
    while(i<leftlen && j<rightlen)
    {
      if(left[i]<= right[j])

      arr[k++]=left[i++];

      else

      arr[k++]=right[j++];

    }

    while(i<leftlen)
    {
        arr[k++]=left[i++];
    }
    while(j<rightlen)

    {
       arr[k++]=right[j++];
    }

    for(int l=0;l<(rightlen+leftlen);l++)
    {
      arr1[l]=arr[l];
    }
    free(left);
    free(right);
}

A: Here
  if(left[i]<= right[j])
      arr[k++]=left[i++];
  else
      arr[k++]=left[j++];

last left should be right.
Anyway, where do you free the memory you malloc-ed...?

A: It is a very bad idea to malloc a new buffer for each sub-array on every recursive call. Remember, malloc is quite expensive action, and free costs even much more than malloc!
The subarrays resulting from recursive splitting do not overlap (except for the result of merge spans over two merged parts). So you never need more than one buffer at a time for the merge result and that merge does not interfere with any other merge (except with those for which it is a sub-range). As a result it's enough to create just a single copy of the whole input array and use both arrays alternatively as a source place and destination place for recursive merges:
void merge( int dst[], int src[], int idx1, int idx2, int end2)
{
    int idx = idx1;
    int end1 = idx2;

    while(idx1 < end1 && idx2 < end2)
        dst[idx++] = src[idx1] <= src[idx2] ? src[idx1++] : src[idx2++];
    while(idx1 < end1)
        dst[idx++] = src[idx1++];
    while(idx2 < end2)
        dst[idx++] = src[idx2++];
}

void mrgsrt( int dst[], int src[], int begin, int len)
{
    if(len == 1)
        dst[begin] = src[begin];
    if(len > 1) {
        int mid = len/2;
        mrgsrt(src, dst, begin, mid);
        mrgsrt(src, dst, begin+mid, len-mid);
        merge(dst, src, begin, begin+mid, begin+len);
    }
}

void sort( int a[], int len)
{
  int *tmp;
  if((tmp = malloc(len*sizeof(*a))) != NULL) {
    memcpy(tmp, a, len*sizeof(*a));
    mrgsrt(a, tmp, 0, len);
    free(tmp);
  }
}


Q: Error:Cause: org.gradle.api.internal.ExtensibleDynamicObject I am trying to use NDK in Android Studio, but an error occurs:
Error:Cause: org.gradle.api.internal.ExtensibleDynamicObject
My Android Studio version is 2.2 preview 1, and Gradle version is 2.10.
gradle-experimental version is 0.7.0
I have tryed this Gradle build Error:Cause: org.gradle.api.internal.ExtensibleDynamicObject  but it did not work.
Anyone knows how to resolve it?
Here are my build.gradle file contents:
apply plugin: 'com.android.model.application'
model {
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "me.stupideme.shuclass"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    android.ndk {
        moduleName "ndktest"
        ldLibs.addAll(['log'])
        cppFlags.add("-std=c++11")
        cppFlags.add("-fexceptions")
        platformVersion 16
        stl 'gnustl_shared'
    }

    buildTypes {
        release {
            minifyEnabled false
            //proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            proguardFiles  += file('proguard-rules.pro')

        }
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'io.github.yavski:fab-speed-dial:1.0.1'
    compile 'com.github.akashandroid90:imageletter:1.5'
    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support:support-annotations:23.4.0'
}
buildTypes {
    release {
        minifyEnabled false
        //proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        proguardFiles  += file('proguard-rules.pro')
    }
}

}

A: minSdkVersion.apiLevel 16
targetSdkVersion.apiLevel 21

instead of
minSdkVersion 16
targetSdkVersion 21

and
moduleName = 'ndktest'

instead of
moduleName "ndktest"

it should be
apply plugin: 'com.android.model.application'
model {
    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.3"
        defaultConfig {
            applicationId "me.stupideme.shuclass"
            minSdkVersion.apiLevel 16
            targetSdkVersion.apiLevel 21
            versionCode 1
            versionName "1.0"
            vectorDrawables.useSupportLibrary = true
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }

        android.ndk {
            moduleName = 'ndktest'
            ldLibs.addAll(['log'])
            cppFlags.add("-std=c++11")
            cppFlags.add("-fexceptions")
            platformVersion 16
            stl 'gnustl_shared'
        }

        buildTypes {
            release {
                minifyEnabled false
                //proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                proguardFiles += file('proguard-rules.pro')

            }
        }
        dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:23.4.0'
            compile 'com.android.support:design:23.4.0'
            compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1'
            compile 'com.android.support:support-v4:23.4.0'
            compile 'com.android.support:cardview-v7:23.4.0'
            compile 'io.github.yavski:fab-speed-dial:1.0.1'
            compile 'com.github.akashandroid90:imageletter:1.5'
            testCompile 'junit:junit:4.12'
            androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
            androidTestCompile 'com.android.support.test:runner:0.5'
            androidTestCompile 'com.android.support:support-annotations:23.4.0'
        }
        buildTypes {
            release {
                minifyEnabled false
                //proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
                proguardFiles += file('proguard-rules.pro')
            }
        }
    }
}


Q: Reboot and Select proper boot device after installation (dual boot) I've installed ubuntu 18.04 lts alongside windows 10. I partitiond a disk of 80 GB on windows. Then i booted ubuntu from a usb pendrive, and did the following steps. 76GB partition for the root system, logical, ext4 system. Then another 4GB for swap area. When I wanted to continue, it said:

No partition detected for EFI, your system might not boot. Please create a partition for the EFI or continue at own risk.

So I went back and created a EFI System type partition with 200MB as recommended. Then the installation went properly, but after it, when the system restarted the boot failed with the following message

Reboot and Select proper Boot device or Insert Boot Media in selected Boot device and press a key.

What I tried: disabling the UEFI/Legacy mode.
My boot order: 1)HDD 2)CD/DVD 3)PXE network
I also did a boot info with the log at: boot log
I didn't find any other suggestions with this topic, so I'm asking for your help. I don't want to loose data and programs on win10 if it's possible, but I would definitely like to have a dual boot option with Ubuntu being the other OS
EDIT: So I discovered in GParted that the boot flag from sda1 ntfs (Win 10 boot) came off, so I added it. Now I can access WIN 10, but still not Ubuntu.

A: While I do not know the detailed list of events that led to the issue, I believe the root cause is that your Windows installation boots in legacy (BIOS) mode, and your Ubuntu installation is using UEFI. The UEFI/Legacy option that you tried disabling, stands for BIOS mode. In my experience, different boot modes don't work well together, you should use the same for both.
There are two ways to achieve that.
One is that you reinstall Ubuntu in legacy mode. I believe that the installer pendrive is able to boot from both UEFI and BIOS mode, and that it installs Ubuntu so that it can boot the same way as you booted to the installer. Consequently you should turn the UEFI/Legacy boot mode back on, and boot the installer in legacy mode, get rid of the EFI partition and install Ubuntu as you originally intended. Then after you try to boot Ubuntu, GRUB should detect the Windows installation and offer you to boot into that.
The other way would be to reinstall Windows in UEFI mode. As far as I know, Windows boot mode is entirely dependent on the type of the partition table, which can be MBR (labeled as dos in fdisk) or GPT. When you install it on a drive with an MBR partition table, it will boot in BIOS mode, which is your case currently, but when you install it on a drive with a GPT partition table, it will boot in UEFI mode.
Thus, to do this you would have to create a new partition table (causing you to lose all data on the drive), install Windows 10 then install Ubuntu. In both cases you should make sure that you boot into the pendrive in UEFI mode.

A: I had the same problem. I fixed it by selecting the USB without UEFI option, instead of let it boot automatically.


Q: Babel doesn't ingore files outside the directory Here is my directory structure:
root/
└── nodejs_project/
    ├── node_modules/
    ├── src/
    ├── babel.config.json
    ├── package.json
    └── package-lock.json
└── another_project/
    └── folder1/
        └── static/
    └── folder2/
        └── static/

Here is my babel.config.json
{
    "presets": ["@babel/react", "minify"],
    "ignore": ["**/*.min.js"]
}

Ignoring works well when .js files are in src/ directory:
...\root\nodejs_project>npx babel src/ --out-dir src/ --out-file-extension .min.js

But ignore rule stops working when .js files are in another_project/ directory:
...\root\nodejs_project>npx babel ../another_project/ --out-dir ../another_project/ --out-file-extension .min.js

How can I set babel.config.json to ignore all of the *.min.js files in another_project/ directory?

A: This helped me in any directories:
{
    "presets": ["@babel/react", "minify"],
    "ignore": ["../**/*.min.js"]
}


Q: Vertical spacing inside mathtools's multlined The code
\documentclass{article}
\usepackage{mathtools}
\begin{document}
  \begin{align*}
  f(1) &= g(1) + g(2) + g(3) \\
  f(1) &= g(1) + g(2) + g(3) \\
  f(1) &= \!\begin{multlined}[t]g(1) + g(2) + g(3) + g(1) + g(2) + g(3)\\
          g(1) + g(2) + g(3) + g(1) + g(2) + g(3)
          \end{multlined}
          \\
  f(1) &= g(1) + g(2) + g(3) \\
  f(1) &= g(1) + g(2) + g(3)
  \end{align*}
\end{document}

produces
I looked in the mathtools's code and could not see how to set things up so that the vertical spacing between multlined lines is exactly the same as between other amsmath constructs. I know I can say \\[10pt] to adjust one instance, but I'd like to set this up once and for all for all multlineds in the whole document.
Any ideas?

A: This might help
\usepackage{mathtools}
\MHInternalSyntaxOn
\def\MT_mult_invisible_line: {
  \crcr
  \global\MH_set_boolean_F:n {mult_firstline}
  \hbox to \l_MT_multwidth_dim{}\crcr
  \noalign{
    \vskip-\baselineskip
    %\vskip-\jot
    \vskip-\normallineskip
  }
}
\MHInternalSyntaxOff

Not quite sure why \jot was added in the first place, probably because of spreadlines.

A: Here, I substituted the multilined with a \Longunderstack, where you can set the interline baselineskip explicitly with \setstackgap{L}{...}.  I loaded tabstackengine (instead of stackengine), in case you wanted to employ additional tabbing features in your stacks.
\documentclass{article}
\usepackage{mathtools,tabstackengine}
\stackMath
\setstackgap{L}{\baselineskip}
\begin{document}
  \begin{align*}
  f(1) &= g(1) + g(2) + g(3) \\
  f(1) &= g(1) + g(2) + g(3) \\
  f(1) &= \Longunderstack[l]{ g(1) + g(2) + g(3) + g(1) + g(2) + g(3)\\
          \quad g(1) + g(2) + g(3) + g(1) + g(2) + g(3)
          }
          \\
  f(1) &= g(1) + g(2) + g(3) \\
  f(1) &= g(1) + g(2) + g(3)
  \end{align*}
\end{document}


Q: Linux fedora - httpd package and router, how to make it work? I installed HTTPD package to setup private web server in my house on one of the computers. The server is up and running, but I can't access the server from outside by using my external IP address.
I think it's because of my router, I have 3 computers in the house connected through router, and one of them is the web server, what I need to do to make it work?

A: You need to forward port 80 from your external IP address to this internal system running Apache.
Typically this is done through your router's web interface. The rule will say something like:
external port: 80
external IP:  Often this is referred to as WAN IP.
internal IP:  Often this is referred to as LAN IP. Something like 192.168.1.X.
internal port: 80
The rule will forward any traffic coming in on external IP @ port 80 to internal IP @ port 80. The addresses don't have to be 80, they can be any IP's. The only consideration is that the Apache web server is "listening" on this internal LAN port. This can be configured in Apache's httpd.conf file.


Q: Ubiquity install wizard crashes; cannot install ubuntu-MATE 18.04.4 I've tried several times now to install Ubuntu-MATE version 1804.4 from a live USB.
Every time I hit "install," nothing happens. A circle spins for a few seconds, then stops.
I get an error message saying that ubiquity has crashed.
In the terminal I checked for ubiquity using:
Code:
dpkg -l ubuiquity
sudo apt update
sudo apt install ubiquity

and saw that the live USB already has the latest version of ubuquity, which is 18.04.14.14.
I have a System76 Wild Dog, 64-bit desktop workstation, 4-core Q9650 3GHz, 8 GB ram. It has a BIOS, not UEFI.
Graphics: PNY Nvidia GeForce GTS 450, driver v. 367.44.
OSs: Ubuntu-MATE 16.04 & 14.04. Drives: 2 960-GB Sandisk SSDs.
I want to install Ubuntu-MATE 18.04.4 onto one of the SSDs (A standalone 960-GB SSD in an enclosure, that I later want to move into the Desktop box and boot directly from.)
Here is some of the lengthy error message report:
ExecutablePath:
/usr/lib/ubiquity/bin/ubiquity
Package:
ubiquity 18.04.14.14
ProblemType:
Crash
Title:
ubiquity crashed with PermissionError in___init___(): [Errno 13]
Permission denied '/cdrom/.disk/info'
How can I get a functioning ubiquity in the live USB and get the install wizard to open so I can complete the installation?

A: SOLVED: My live USB drive itself had permissions enabled for user only.  I created read and execute permissions for group and other:
chmod go+rx /media/name-of-live-USB-stick


Q: Google sheets calculations for dates before 1900 - A possible solution I am trying to do calculations without scripts. A solution can be to sum a far in the future date (31/12/9999) +1 and use that value to do calculations
Cell A1 = 1/2/1872 -> -10.194,00
Cell A2 = 31/12/9999 -> 2.958.465,00
Cell A3 = A1-A2+1 -> 2.948.270,00 -> 01/02/9972

I can adjust the year to a more confortable, year that is distant from edges (99999 and 1900) -> I use as offset 4000 which should preserve original leap year. A4: =DATE(YEAR(A3)-8100+4000;MONTH(A3);DAY(A3)) -> 01/02/5872
at this point I can use A4 to do most of calculations on dates and calculate back any adjusted date by using DATEVALUE()
This does of course take into consideration past dates that have issues with current official calentars; it seems that 19th century is ok.
I haven't tested/ported it to Excel.
Does anybody confirm it works?

A: the logic of your formula may be correct, but more factors must be considered when playing with the calendar as humanity likes to adjust even the rules of adjustment. here are a few examples:

*

*the longest year in history: 46 BCE (708 AUC) lasting 445 days known as "the last year of confusion" as Ceasar added 3 more months (90 days) so that the next year (45 BCE) would start right after the winter solstice.

*the shortest year in history: 1582 CE lasting 355 days where October had only 21 days (4th Oct. was followed by 15th Oct.) but also it depends where you are
because British Empire decided to reinvent the wheel by accepting the "1582-wheel" in the year 1752 CE where September had only 19 days (2nd Sep. was followed by 14th Sep.) resulting the year to have 355 days as well. however, if we are technical, the British Empire also had a year that lasted only 282 days because their "old" new year started on 25 March and not 1 January therefore the year 1751 CE started on 25th Mar and ended on 31st Dec. Turkey, for example, joined the "gregorian train" in 1st Jan 1927 CE after their December of 1926 CE had only 18 days so that year was long only 352 days. the latest country to adopt the gregorian calendar was Saudi Arabia in 2016 CE when they jumped from 1437 AH

*the year zero: does not exist. 31st Dec. 1 BCE was followed by 1st Jan. 1 CE
753 AUC = 1 BCE
754 AUC = 1 CE

also, dude who invented this nonsense was born around 1223 AUC (470 CE) so that speaks for itself. this is important because offsetting DATEVALUE needs to be done in such a way that the calculation will not cross 0 eg. not drop bellow -693593:
=TO_DATE(-694324)   -   incorrect datevalue   -   01/01/00-1

=TO_DATE(-693678)   -   incorrect datevalue   -   08/10/0000

=TO_DATE(-693593)   -   1st valid datevalue   -   01/01/0001

=TO_DATE(35830290)  -   last valid datevalue  -   31/12/99999

*it's also worth mentioning that 25th Dec. 200 CE was not Friday on the Roman peninsula because people in that era used 8-day system

*there are many calendar systems each with its own set of rules and up to this date there are still countries that do not recognize the gregorian calendar as a standard so if you want to re-live the year 2021 go to Ethiopia where today's 9 Oct. 2022 CE = 29 Mes. 2015 EC on the other hand if you prefer to live in the future try Nepal where today's 9 Oct. 2022 = 23 Ash. 2079 BS


Q: How to Edit existing google form item (question) using google Apps Script I have a Google script to construct a google form. The script fills the form using a Spreadsheet which contains the questions and corresponding options.
The question displayed in the form needs to be updated at regular intervals.
I hope to update the question in the form by changing the question in the Spreadsheet as follows:

*

*I use onOpen() for the script, so that each time the form is accessed the script reconstructs the most updated form.

However, currently each time I run the Script a new question is added to the form and the previous outdated questions still stay on the form.
I need to edit the existing question on the Form using the script to update it to show the latest question.
I could not find a way to edit an existing form question using google script.
Anyone know how?
The question and options are updated in the spreadsheet at regular intervals.
I want the script to be able to edit the question automatically.
All my attempts to find a function which is able to edit an already available question on a Form have been in vain!
(PS : All functions I found are able to create a new question and its options/ but not able to edit an existing form question/option)

A: In order to update an existing item (question), the code must first get that item by it's item type, and there are many different methods for getting items by their type.
There is a different method for each type of question.  The types of questions are:

*

*CHECKBOX

*DATE

*DATETIME

*DURATION

*GRID

*LIST

*MULTIPLE_CHOICE

*PARAGRAPH_TEXT

*SCALE

*TEXT

*TIME

In order to update an existing item, the code must first get that item by it's item type.  Here are some examples:

*

*asCheckboxItem()

*asDateItem()

*asListItem()

*Etc

For example:
var myCheckBoxItem = FormApp.openById(id).getItemById(id).asCheckboxItem();

Once the code has obtained an item as the correct item, you can change it the same way that you created it in the first place.
function editFormItem() {
  var form = FormApp.getActiveForm();
  var allItems = form.getItems();
  var i,
      L=0,
      thisItem,
      thisItemType,
      myCheckBoxItem;

  L = allItems.length;

  for (i=0;i<L;i++) {
    thisItem = allItems[i];
    thisItemType = thisItem.getType();
    //Logger.log('thisItemType: ' + thisItemType);

    if (thisItemType===FormApp.ItemType.CHECKBOX) {
      myCheckBoxItem = thisItem.asCheckboxItem();
      myCheckBoxItem.setChoiceValues(values)
    };
  };
};

The above script is not complete.  You need to somehow match up what item goes with the new changes.  If all your Form questions are the same item type, then you won't need to test for what the item type is.
There are 3 item types that get returned by getItems() that are not question items.  They are:

*

*IMAGE

*PAGE_BREAK

*SECTION_HEADER

So, if you have any of those 3 in your form, you should check the item type.


Q: Java program for Adding Digits Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
but my function returns 11 ? what is wrong with my logic? Help !!
public class Solution {
    public int addDigits(int num) {
    int result=doSum(num);
    return result;
    }

    public static int doSum(int num){
        int sum=0,digit;
        while(num!=0){
            digit=num%10;
            sum+=digit;
            num=num/10;
        }
        if(sum/10!=0){
            doSum(sum);
        }
        return sum;
    }
}

A: if(sum/10!=0){
    doSum(sum);
}

This is what is wrong with your logic. You recursively call doSum() on the new sum but you do nothing with the result. So you need to change this to:
if(sum/10!=0){
   sum = doSum(sum);
}


Q: Loading data from SQL Server to Elasticsearch Looking for suggesting on loading data from SQL Server into Elasticsearch or any other data store. The goal is to have transactional data available in real time for Reporting.
We currently use a 3rd party tool, in addition to SSRS, for data analytics. The data transfer is done using daily batch jobs and as a result, there is a 24 hour data latency.
We are looking to build something out that would allow for more real time availability of the data, similar to SSRS, for our Clients to report on. We need to ensure that this does not have an impact on our SQL Server database.
My initial thought was to do a full dump of the data, during the weekend, and writes, in real time, during weekdays.
Thanks.

A: ElasticSearch's main use cases are for providing search type capabilities on top of unstructured large text based data. For example, if you were ingesting large batches of emails into your data store every day, ElasticSearch is a good tool to parse out pieces of those emails based on rules you setup with it to enable searching (and to some degree querying) capability of those email messages.
If your data is already in SQL Server, it sounds like it's structured already and therefore there's not much gained from ElasticSearch in terms of reportability and availability. Rather you'd likely be introducing extra complexity to your data workflow.
If you have structured data in SQL Server already, and you are experiencing issues with reporting directly off of it, you should look to building a data warehouse instead to handle your reporting. SQL Server comes with a number of features out of the box to help you replicate your data for this very purpose. The three main features to accomplish this that you could look into are AlwaysOn Availability Groups, Replication, or SSIS.
Each option above (in addition to other out-of-the-box features of SQL Server) have different pros and drawbacks. For example, AlwaysOn Availability Groups are very easy to setup and offer the ability to automatically failover if your main server had an outage, but they clone the entire database to a replica. Replication let's you more granularly choose to only copy specific Tables and Views, but then you can't as easily failover if your main server has an outage. So you should read up on all three options and understand their differences.
Additionally, if you're having specific performance problems trying to report off of the main database, you may want to dig into the root cause of those problems first before looking into replicating your data as a solution for reporting (although it's a fairly common solution). You may find that a simple architectural change like using a columnstore index on the correct Table will improve your reporting capabilities immensely.

I've been down both pathways of implementing ElasticSearch and a data warehouse using all three of the main data synchronization features above, for structured data and unstructured large text data, and have experienced the proper use cases for both. One data warehouse I've managed in the past had Tables with billions of rows in it (each Table terabytes big), and it was highly performant for reporting off of on fairly modest hardware in AWS (we weren't even using Redshift).


Q: Managing string resources in Qt I have a string that I need at various points in my program. I know that Qt can manage image resources, but I need similar functionality for a couple of strings. Currently I'm using a string resource class, which is a sloppy solution.
class StringRes {
public:
    static const QString& appName() { return _appName; }
    static const QString& appVersion() { return _appVersion; }
private:
    static const QString _appName;
    static const QString _appVersion;
};

Besides, this solution causes a segfault at a certain point in my code.
_fileStream << QString("This is ")
               + StringRes::appName()
               + " "
               + StringRes::appVersion()
               + " reporting for duty.\n";

How do Qt programmers (or C++ programmers in general) manage their string resources?

A: For storing just application's name and version and organization's name and domain you can use QCoreApplications's properties applicationName, applicationVersion, organizationDomain and organizationName.
I usually set them in main() function:
#include <QApplication>
#include "MainWindow.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // These functions are member of QCoreApplication, QApplication's
    // parent class:
    app.setApplicationName("My Application");
    app.setApplicationVersion("3.5.2");
    app.setOrganizationName("My Company, or just My Name");
    app.setOrganizationDomain("http://example.com/");

    MainWindow window;
    window.show();

    return app.exec();
}

And I can use them to show a nice about message:
#include "MainWindow.h"
#include <QCoreApplication>

...

// Slot called when ? -> About menu is clicked.
void MainWindow::on_aboutAction_triggered()
{
    QString message = tr("%1 %2
"
                         "Developed by %3")
            .arg(QCoreApplication::applicationName())
            .arg(QCoreApplication::applicationVersion())
            .arg(QString("%2")
                .arg(QCoreApplication::organizationDomain())
                .arg(QCoreApplication::organizationName()))
            ;

    QMessageBox::about(this, tr("About"), message);
}


Q: AKS Storage Class network acl I'm trying to create a storage class in AKS that needs to have the public access disabled and the specific vnet and subnet allowed. Basically using service endpoint.
I can create the storage account with specific params like storage type, but the other settings dont apply.
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: ######files2
provisioner: file.csi.azure.com
allowVolumeExpansion: true
mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=0
  - gid=0
  - mfsymlinks
  - cache=strict
  - actimeo=30
parameters:
  skuName: Standard_GRS
  vnetResourceGroup: r##########
  vnetName: v#######-#####
  subnetName: s############s
  allowBlobPublicAccess: false

this link seems to imply its possible:
https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/aks/azure-files-csi.md
But I can't get it working and I can't have storage accounts exposed to the internet.
Any ideas?
Thanks


Q: How to compile sqlite with ICU? I downloaded sqlite from http://www.sqlite.org/sqlite-autoconf-3070701.tar.gz
How can I compile sqlite with icu ?

A: Whether you build the amalgamation with icu enabled or just icu extension depends on what you want to do with icu.
If you need an icu tokenizer (to do fts) you need to build amalgamation, if you just need the icu functions as https://www.sqlite.org/cgi/src/dir?ci=6cb537bdce85e088&name=ext/icu list then icu extension is enough.
When building icu extension I find I can not name it libSqliteIcu.so as that readme said b/c when I load it I got this error
sqlite> .load ./libSqliteIcu.so
Error: dlsym(0x7fa073e02c60, sqlite3_sqliteicu_init): symbol not found

After asking the question at sqlit mail list  I was told that, which I have confirm.
The symbol name is sqlite3_icu_init.  When you load module lib<x>.so the symbol sqlite3_<x>_init is called.  You need to either (a) rename the shared library to the correct name (libicu.so) or pass the name of the init function (sqlite3_icu_init) to the loader when you load the module, or (b) change the name of the sqlite3_icu_init function in the icu.c source so that it matches the name that the module loader is looking for ...

A: 1) You can compile it as dynamic extension of SQLite
Citing http://www.sqlite.org/cvstrac/fileview?f=sqlite/ext/icu/README.txt

The easiest way to compile and use the ICU extension is to build
    and use it as a dynamically loadable SQLite extension. To do this
    using gcc on *nix:
gcc -shared icu.c `icu-config  --cppflags --ldflags` -o libSqliteIcu.so

You may need to add "-I" flags so that gcc can find sqlite3ext.h
    and sqlite3.h. The resulting shared lib, libSqliteIcu.so, may be
    loaded into sqlite in the same way as any other dynamically loadable
    extension.

(loading is  .load libSqliteIcu.so in SQLite prompt)
2) You can compile SQLite with ICU enabled. According to http://www.sqlite.org/compile.html
 you should define macro SQLITE_ENABLE_ICU:
Add -DSQLITE_ENABLE_ICU to the CFLAGS variable or add #define SQLITE_ENABLE_ICU in some config file.
Okay, there is something here not described in standard documentation. Here is an example of calling configure with ICU enabled:
 CFLAGS='-O3 -DSQLITE_ENABLE_ICU' CPPFLAGS=`icu-config --cppflags` LDFLAGS=`icu-config --ldflags` ./configure

You also should have icu-config program installed (it is from  libicu or  libicu-dev package)

A: To compile SQLite with ICU enabled, you should define macro SQLITE_ENABLE_ICU.
Make sure that you have libicu-dev (on Debian/Ubuntu) installed.
As @osgx wrote, the standard documentation is lacking ICU-specific flags that you also need to set. icu-config is deprecated and is missing on Ubuntu 20.04 onwards, thus you should use pkg-config instead:
CFLAGS="-O2 -DSQLITE_ENABLE_ICU `pkg-config --libs --cflags icu-uc icu-io`" ./configure
make

See:

*

*How To Use ICU - C++ Makefiles

*Compile-time Options of SQLite


Q: Qt 5.2.0 ftp and QNetworkAccessManager I need to be able to create directories on my ftp server.
I know that there's no QFtp in the 5.2.1 qt, so how do I mkdir with QNetworkAccessManager?

A: QNetworkAccessManager doesn't support that

A: Although it is recommended to use QNetworkAccessManager as much as possible, you always fall back to the QtFtp add-on as follows:
QT += ftp

Then, you will be able to use the mkdir method of the QFtp class.


Q: @Destroy Annotation with Page Scoped Beans I have a page scoped Seam component and it has a no-parameter void method annotated with @Destroy as is shown below. My problem is that destroy method is never called even if the browser page is changed (i.e. page scope ended).
@Name("myPageBean")
@Scope(ScopeType.PAGE)
public class MyPageBean {

    @Destroy
    public void destroy {
        // Code runs when the component is destroyed.
    }

}

Do you have an idea for this issue?
Thanks in advance.

A:
When does the page context get destroyed?
The page scope is indistinguishable from the UI component tree.
  Therefore, the page context is destroyed when JSF removes the UI
  component tree (also called the view) from the session. However, when
  this happens, Seam does not receive a callback and therefore the
  @Destroy method on a page-scoped component never gets called. If the
  user clicks away from the page or closes the browser, the page context
  has to wait to get cleaned up into JSF kills the view to which it is
  bound. This typically happens when the session ends or if the number
  of views in the session exceeds the limit. This limit is established
  using the com.sun.faces.numberOfViewsInSession and
  com.sun.faces.numberOfLogicalViews context parameters in the Sun
  implementation. Both default to 15. However, it's generally best not
  to mess with these values.
The page scope should be seen merely as a way to keep data associated
  with a view as a means of maintaining the integrity of the UI
  component. This focus is especially relevant for data tables, which
  have historically been problematic. I would not use the page scope as
  a general storage mechanism for use case or workflow data. A good way
  to think of it is as a cache.

http://www.seamframework.org/42514.lace

A: do you ever use this bean in a page?, if not, I guess the destroy will not be called because of it never be created.
or you can add @StartUp to force creating the bean when the Scope are initialized.


Q: jQuery selector - select new elements too after append/load within variable I have:
$elements = $('.elements');
$element = $('.element');

function appendText(element){
    element.append(' appended text');
}

appendText($element);

$('button').on('click', function(){
        $elements.append('Span Element Appended after load');
        appendText($element);
});

The appendText function, after button click, appends only to the initial element and that is due to JS cache I presume.
I know that I can do appendText($('element')); and the problem will be solved, but I don't want to change all my code now.
Is there any way to make jQuery consider this $element variable as not a cached element and look into the full DOM each time I call that variable?
Please find the jsfiddle if you wish to play or understand better: http://jsfiddle.net/adyz/733Xd/

A: If you add this:
$element = $('.element:last-child')

before
appendText($element);

I think will solve your problem
jsFindle here: http://jsfiddle.net/733Xd/5/.
Best regards!

A: That is an expensive thing to do. I would advise against it for performance reasons.
I did this pluggin in the beggining of last year https://github.com/fmsf/jQuery-obj-update
It doesn't trigger on every call, you have to request the update yourself:
$element.update();

The code is small enough to be pasted on the answer:
(function ( $ ) {
  $.fn.update = function(){
    var newElements = $(this.selector),i;
    for(i=0;i<newElements.length;i++){
      this[i] = newElements[i];
    }
    for(;i<this.length;i++){
      this[i] = undefined;
    }
    this.length = newElements.length;
    return this;
  };
})(jQuery);

A: I think below one will solve your problem
   appendText($element); //here you always referring to the node which was there initial.

   http://jsfiddle.net/s9udJ/

A: Possible Solution will be
$(function(){

$elements = $('.elements');
$element = $('.element');

function appendText(element){
    element.append(' appended text');
}

appendText($element);

$('button').on('click', function(){
        $elements.append('Span Element Appended after load');
        appendText($elements.find('span').last());
});

})

A: I don't think what you're asking is easily possible - when you call $element = $('.element'); you define a variable which equals to set of objects (well, one object). When calling appendText($element); you're operating on that object. It's not a cache - it's just how JS (and other programming languages) works.
The only solution I can see is to have a function that will update the variable, every time jquery calls one of its DOM manipulation methods, along the lines of this:

$(document).ready(function()
{
    var element = $('.a');

    $.fn.appendUpdate = function(elem)
    {
        // ugly because this is an object
        // also - not really taking account of multiple objects that are added here
        // just making an example

        if ($(elem).is(this.selector))
        {
            this[this.length] = $(this).append(elem).get(0);
            this.length++;
        }

        return this;
    }

    element.appendUpdate("

");
    console.log(element);
});

Then you can use sub() to roll out your own version of append = the above. This way your variables would be up to date, and you wouldn't really need to change your code. I also need to say that I shudder about the thing I've written (please, please, don't use it).
Fiddle