text:
Q: ORACLE Add new record if any field changes I'm trying to write an Oracle procedure.  I have a table and currently I'm using a merge statement.  When a record is changed, it updates it, if it is new, it adds it.
However, we want to keep track of changed records.  So I'm adding three fields: startdate, enddate, currentflag.  I don't want to update the record if there are any changes, I want to add a new record instead.  But I do want to add an enddate and change the flag on the old record.
So, if I have a table like this:
TableID
Field1
Field2
Field3
StartDate
EndDate
CurrentFlag

And it has data like this
TableID   Field1   Field2   Field3  StartDate   EndDate   CurrentFlag
001       DataA    Cow      Brown   3-Oct-18              Y
001       DataA    Cow      White   1-Sep-18    3-Oct-18  N
002       DataB    Horse    Dapple  3-Oct-18              Y

I want to merge in some data
TableID   Field1   Field2   Field3
001       NewData  Cow      Black
002       DataB    Horse    Dapple
005       Data3    Cat      Black

So that the final table looks like this
TableID   Field1   Field2   Field3  StartDate   EndDate   CurrentFlag
001       DataA    Cow      Brown   3-Oct-18    10-Oct-18 N
001       DataA    Cow      White   1-Sep-18    3-Oct-18  N
001       NewData  Cow      Black   10-Oct-18             Y
002       DataB    Horse    Dapple  3-Oct-18              Y
005       Data3    Cat      Black   10-Oct-18             Y

My pseudocode is
for each record in source file
   find current record in dest table (on ID and flag = Y)
   if any other fields do not match (Field1, Field2, Field3)
    then update current record, set enddate, current flag to n
        and add new record with startdate = sysdate, current flag is Y
   if no match found, then add new record with startdate = sysdate, current flag is Y

I'm not sure how to turn that pseudocode into Oracle SQL code.  Can I use the same MERGE statement, but in the WHEN MATCHED add a check to see if any of the other fields are different?
I will be doing this for several tables, a few of which have a lot of records and many fields.  So I need to figure out something that works and isn't as slow as molasses.
UPDATE
I have created a procedure as suggested, with some modifications, so it works:
CREATE OR REPLACE PROCEDURE TESTPROC AS

BEGIN
DECLARE
l_count NUMBER;
CURSOR TRN is
    SELECT * from sourceTable;

BEGIN
    FOR each_record IN TRN
    LOOP
        -- if a record found but fields differ ...
        l_count := 0;
        SELECT COUNT(*) INTO l_count
        FROM destTable DIM
        WHERE each_record.TableID = DIM.TableID
          and (each_record.Field1 <> DIM.Field1
          or each_record.Field2 <> DIM.Field2
          or each_record.Field13 <> DIM.Field3)
          AND DIM.CurrentFlag = 'Y';

        -- ... then update existing current record, and add with new data
        IF l_count > 0 THEN
            UPDATE destTable DIM
              SET EndDate = sysdate
                 ,CurrentFlag = 'N'
               WHERE each_record.TableID = DIM.TableID;

            INSERT INTO destTable
                     (TableID
                    , Field1
                    , Field2
                    , Field3
                    , StartDate
                    , CurrentFlag)
            VALUES (each_record.TableID
                    , each_record.Field1
                    , each_record.Field2
                    , each_record.Field3
                    , sysdate
                    , 'Y');
          COMMIT;
        END IF;

        -- if no record found with this key...
        l_count := 0;
        SELECT COUNT(*) INTO l_count
        FROM destTable DIM
        WHERE each_record.TableID = DIM.TableID;

        -- then add a new record
        IF l_count = 0 THEN
            INSERT INTO destTable
                     (TableID
                    , Field1
                    , Field2
                    , Field3
                    , StartDate
                    , CurrentFlag)
            VALUES (each_record.TableID
                    , each_record.Field1
                    , each_record.Field2
                    , each_record.Field3
                    , sysdate
                    , 'Y');
        END IF;
    END LOOP;
    COMMIT;
END;
END TESTPROC

And on my small table, it worked nicely.  Now I'm trying it on one of my larger tables (800k records, but by no means the largest table), and I'm updating this question while it runs.  It's been nearly an hour, and obviously that isn't acceptable.  Once my program comes back, I'll add indices on the TableID, and TableID and CurrentFlag.  If indices don't help, any suggestions for the slow as molasses aspect?

A: You can write a Simple procedure for the same:
DECLARE

l_count NUMBER;
CURSOR C1 is
-- YOUR DATA FROM SOURCE

BEGIN

 for each_record in c1
 l_count := 0;
   SELECT COUNT(*) into l_count from destination_table where field1=
  eachrecord.field1 and .... and flag = 'Y'; -- find current record in dest table (on ID and flag = Y)

--  if any other fields do not match (Field1, Field2, Field3)
IF L_COUNT > 0 THEN
   update current record, set enddate, current flag to n
END IF;
    INSERT new record with startdate = sysdate, current flag is Y
END;

Mod by OP: That led to the right direction.  The following code will do the trick, providing there is also an index on TableID and (TableID, CurrentFlag).
CREATE OR REPLACE PROCEDURE TESTPROC AS

BEGIN
DECLARE
l_count NUMBER;
CURSOR TRN is
    SELECT * from sourceTable;

BEGIN
    FOR each_record IN TRN
    LOOP
        -- if a record found but fields differ ...
        l_count := 0;
        SELECT COUNT(*) INTO l_count
        FROM destTable DIM
        WHERE each_record.TableID = DIM.TableID
          and (each_record.Field1 <> DIM.Field1
          or each_record.Field2 <> DIM.Field2
          or each_record.Field13 <> DIM.Field3)
          AND DIM.CurrentFlag = 'Y';

        -- ... then update existing current record, and add with new data
        IF l_count > 0 THEN
            UPDATE destTable DIM
              SET EndDate = sysdate
                 ,CurrentFlag = 'N'
               WHERE each_record.TableID = DIM.TableID;

            INSERT INTO destTable
                     (TableID
                    , Field1
                    , Field2
                    , Field3
                    , StartDate
                    , CurrentFlag)
            VALUES (each_record.TableID
                    , each_record.Field1
                    , each_record.Field2
                    , each_record.Field3
                    , sysdate
                    , 'Y');
          COMMIT;
        END IF;

        -- if no record found with this key...
        l_count := 0;
        SELECT COUNT(*) INTO l_count
        FROM destTable DIM
        WHERE each_record.TableID = DIM.TableID;

        -- then add a new record
        IF l_count = 0 THEN
            INSERT INTO destTable
                     (TableID
                    , Field1
                    , Field2
                    , Field3
                    , StartDate
                    , CurrentFlag)
            VALUES (each_record.TableID
                    , each_record.Field1
                    , each_record.Field2
                    , each_record.Field3
                    , sysdate
                    , 'Y');
        END IF;
    END LOOP;
    COMMIT;
END;
END TESTPROC

A: Maybe you could use triggers to perform that.
CREATE OR REPLACE TRIGGER insTableID
BEFORE INSERT OR UPDATE
ON tableID
FOR EACH ROW
DECLARE
    v_exists NUMBER := -1;
BEGIN
    SELECT COUNT(1) INTO v_exists FROM tableID t where t.Field1 = :new.Field1 and ... ;
    IF INSERTING THEN
        IF v_exist > 0 THEN
            null;--your DML update statement
        ELSE
            null;--your DML insert statement
        END;
    END IF;
    IF UPDATING THEN
        null;--your DML statement for update the old registry and a DML for insert the new registry.
    END IF;
END;

In this way, you can update the registry related to the old values and insert a new row with the new values.
I hope that this helps you to solve your problem.


text:
Q: Is every set comeagre in its closure? Let $A$ be a set in a topological space $X$. We know that $A$ is dense in its closure $\bar{A}$. This implies that $\bar{A} \setminus A$ is nowhere dense in $\bar{A}$ (using a characterisation of nowhere dense sets in Kechris' Classical Descriptive Set Theory, section 8.A, namely that a set is nowhere dense if and only if its complement is dense). Since every nowhere dense set is also meagre, we know that $\bar{A} \setminus A$ is meagre and therefore $\bar{A} \setminus (\bar{A} \setminus A) = A$ is comeagre in $\bar{A}$.
Does this argument work?
Edit: Just noticed that I misread Kechris' characterisation. It is that a set $A$ is nowhere dense if and only if $X \setminus \bar{A}$ is dense (i.e. not when its complement is dense). Then obviously, my argument doesn't work.

A: No, for instance take $\mathbb{Q}$. It is meager in its closure $\mathbb{R}$.
So your third sentence is already false, although it holds for open $A$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: exit function not being called when setinterval is running I'm trying to write code that will return whether the server is already running or not. However, my tests are not working.
I want on process.exit to write a file that says the server is no longer running, and for when the server starts up, it to write that the server is running:
const { readdir, writeFile, writeFileSync, readFileSync } = require('fs')
const IS_RUNNING_LOCATION = `${__dirname}/running.txt`
if (readFileSync(IS_RUNNING_LOCATION).toString() ===  'true')
  return
process.on('exit', () => {
  writeFileSync(IS_RUNNING_LOCATION, 'false', {}, (err) => {
    if (!err) return console.log('written')
    console.log(err)
  })
})
writeFileSync(IS_RUNNING_LOCATION, 'true')

setInterval(()=> console.log('running'), 1000)

However, with this code, when I exit with ^C, the on exit code is not run.
Can anyone tell me why this is the case or how I can fix it?

A: Found the answer here: doing a cleanup action just before node.js exits
This is the code I ended up using:
const { writeFileSync, readFileSync } = require('fs')
const IS_RUNNING_LOCATION = `${__dirname}/.running`
if (readFileSync(IS_RUNNING_LOCATION).toString() ===  'true')
  process.exit(0)

writeFileSync(IS_RUNNING_LOCATION, 'true')
function exitHandler(options, err) {
  writefilesync(is_running_location, 'false', {}, (err) => {
    if (!err) return if (!err) return console.log('written')
    console.log(err)
  })
  if (options.exit) process.exit();
}

process.on('exit', exitHandler.bind(null,{cleanup:true}))
process.on('SIGINT', exitHandler.bind(null, {exit:true}))
process.on('uncaughtException', exitHandler.bind(null, {exit:true}))


text:
Q: Lentitud en respuesta de base de datos SQL Server desde PHP con ODBC He instalado XAMPP en mi equipo para ejecutar un sitio web PHP que se conecta vía ODBC a SQL Server, para lo cual activo pdo_odbc en el php.ini, mi sitio se conecta correctamente, pero sin importar lo pequeña que sea la consulta, incluso de 3 registros de una tabla, se demora más de 4 segundos.
Para la consulta utilizo AJAX.
Cuando me llevo el sitio a producción, esto no sucede, las consultas se comportan con la velocidad correcta (obviamente ya cada una dependiendo de su complejidad).
En mi ambiente local ya verifiqué que si hago esa misma consulta SQL directamente en el Management Studio, no se demora nada prácticamente.
Es como si tuviera un especie de problema con el servidor Apache pero la verdad ya no se que probar.
También he probado usando WAMP, pero pasa lo mismo.
Este mismo sitio también se conecta a través de una API Rest a una base de datos MySQL, pero en este caso todo va bien, no hay lentitud.
Les comparto el código que estoy utilizando:
Petición AJAX:
function listarCompania() {
    $.ajax({
        url: "../../controller/compania.php",
        dataType: "json",
        type: "POST",
        async: false,
        data: {opcion: "listar"}
    })
    .done(function (data) {
        if (data.length > 0) {
            for (i = 0; i < data.length; i++) {
                $("#compania").append('<option value="'+ data[i].id +'">'+ data[i].nombre_comercial +'</option>');
            }
        }else{
            swal("Atención!", "No fue posible cargar las compañías", "error");
        }
    });
}

Archivo de conexión PHP:
<?php
class conexion {
private $instancia;
private $tipo = NULL;
function __construct($host, $database_name, $username, $password, $port) {
    $this->tipo = "sqlserver";
    $connection_string = "DRIVER={SQL Server};SERVER=$host;DATABASE=$database_name;port=$port";
    $conn = odbc_connect($connection_string, $username, $password);
    $this->instancia = $conn;
}
function get_conexion() {
    return $this->instancia;
}
function cerrar() {
    odbc_close($this->instancia);
}

}
Controllador:
<?php
require_once '../model/compania.php';
include_once '../connection/data_connection.php';
define("DATABASE", "UNIVERSAL");
$funcion = new funcion(HOSTNAME,DATABASE,USERNAME,PASSWORD,PORT);
switch($_POST['opcion']){
   case "listar" : echo ( $funcion->listar()); break;
}

$funcion->cerrar();
Modelo:
<?php
require_once '../connection/connection.php';

class funcion extends conexion {

function __construct($host, $database_name, $username, $password, $port) {
    parent::__construct($host, $database_name, $username, $password, $port);
}

function listar() {
    $sql = "select id, nombre_comercial from compania where activo=1 order by orden asc";
    $result = odbc_exec(parent::get_conexion(), $sql);
    $data = array();
    $i = 0;
    while (odbc_fetch_row($result)) {
        $j = 1;
        $data [$i]['id'] = utf8_encode(odbc_result($result, $j));
        $j++;
        $data [$i]['nombre_comercial'] = utf8_encode(odbc_result($result, $j));
        $j++;
        $i++;
    }
    return json_encode($data);
}


text:
Q: Assign JSON Response to Model SwiftUI I have successfully parsed JSON by creating a Model. But now I want a View Model which talks to View and the View updates whenever the Model Updates. But I m having hard time initialising the model.
My simplified model looks like this.
PeopleListM.swift
import SwiftUI
import Alamofire

struct PeopleListM: Decodable {
var all: [Person]

enum CodingKeys: String, CodingKey {
    case all = "people"
}

struct Person: Decodable {

    let name: String
    let email: String
    let favorite: Bool
    let lastSent: String?

    enum CodingKeys: String, CodingKey {
        case name
        case email = "email_id"
        case favorite
        case lastSent = "last_sent"
    }
}

init() {
    let headers: HTTPHeaders = ["disableauth" : "true", "Content-Type": "application/json"]
      AF.request("MY URL", parameters: nil, headers: headers)
        .validate()
        .responseDecodable(of: PeopleListM.self) { (response) in
            guard let result = response.value else { return }
            self.all = result.all
        }
}

This code gives me error Escaping closure captures mutating 'self' parameter
I tried changing line self.all = result.all with self = result, same error.
My further plan is create a class which conforms to ObservableObject
PeopleListVM.swift
import SwiftUI

class PeopleListVM: ObservableObject {

 let people = PeopleListVM.createModel()

 static func createModel() {
    PeopleListM()
 }
}

A: final class PeopleListVM: ObservableObject {

    @Published var people = PeopleListVM.createModel()

    static func createModel() {
        PeopleListM()
    }

    func request() {
        // networking here...
        // update people in callback
        // ... self.people = newPeople
    }
}

struct Model: View {
    @ObservableObject var vm = PeopleListVM()
    // ...
}

You generally won't put networking code in struct, because networking always comes with state changes, when value type is meant to be immutable.


text:
Q: Storing list of instances (of self) in class level attribute? I have a class in which I would like to store a static reference list of objects of the same class. For example:
class Apple:

    NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

This results in a NameError: name 'Apple' is not defined error.
Why doesn't this work?
I've changed the code to the following, which seems to work on the console:
class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

Is there a better way to do this?
Will this work inside and outside the module, and is this dependent on the way I import the module?

A: use a classmethod to append apples to your class list.
class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    @classmethod
    def add_nice_apple(cls, name, colour):
        cls.NICE_APPLES.append(cls(name, colour))

Apple.add_nice_apple('Elstar','Green')
Apple.add_nice_apple('Braeburn','Red')

A: Declare NICE_APPLES as an empty list in the Apple class, and then inside __init__(), when you're done assigning all the local variables, append self to the list.
class Apple(object):

    NICE_APPLES = []

    def __init__(self, name, color, keep=False):
        self.name = name
        self.color = color

        if keep:
            Apple.NICE_APPLES.append(self)

A: You can create new class instance from class method, like this, I think this is a clean way yo do it, and also if you want to store the recent created obj besides a list of hardcords:
class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    @classmethod
    def init_with_nice_apples(self, name, colour):
        Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red')] #hardcore list
        self.__init__(self,name, colour)
        Apple.NICE_APPLES.append(self)
        return self

ap = Apple.init_with_nice_apples("Delicius", "Red")


text:
Q: Batch File - Does Directory Exist - If so, delete Having an issue with if-else statements/error handling. Been trying to get this to work, cannot seem to do it.  What I'm looking to do is have user input client id, then delete the directory associated with said client if it exists.
Code:
@echo off
set /p id=Enter ID:
rd /s /q "\\Images\Public on Images\DMS Scanned Clients\%id%"
echo \\Images\Public on Images\DMS Scanned Clients\%id%
pause

So user would input 956862 for example.  Then if directory at \Images\Public on Images\DMS Scanned Clients\956862 exists, it would be removed, otherwise, message would display stating it does not exist.
Thanks

A: @Echo off
pushd %1 >nul 2>&1
If errorlevel 0 if not errorlevel 1 Echo %~nx1 is a folder
If errorlevel 1 Echo %~nx1 is not a folder
Popd

If /i "%cmdcmdline:~0,6%"=="cmd /c" pause

However in programming we do then test, not test then do. Testing requires a lot of system resources. Therefore to test then do requires two expensive disk accesses. Doing and testing the result (ie is the returned number 0) is only one disk access and a quick test of a number.
rd /s c:\somefolder && Echo Folder deleted || Echo Folder didn't exist

&& and || mean do if errorlevel is zero or not zero. It's easier than If errorlevel 0 if not errorlevel 1 echo errorlevel is 0 on multiple lines. See my post here Is typing %^ into cmd.exe a Windows easter egg?


text:
Q: CUDA Seg Fault for Int Device to Host Copy Why is the following simple program (24 lines) lead to segmentation fault at shrinked_size_host int variable:
#include <stdio.h>
#include <cuda_runtime.h>
#include <curand_kernel.h>

__global__ void cuda_set(int* device_var){
   *device_var = 12;
   printf("Set device variable to: %d\n", *device_var);
}

int main() {
    printf("Hello world CPU\n");

    int* shrinked_size_device;
    cudaMalloc((void**)&shrinked_size_device, sizeof(int));
    cudaDeviceSynchronize();

    cudaMemset(shrinked_size_device, 0, sizeof(int));
    cudaDeviceSynchronize();

    cuda_set<<<1,1>>>(shrinked_size_device);
    cudaDeviceSynchronize();

    int* shrinked_size_host = 0;
    cudaMemcpy(shrinked_size_host, shrinked_size_device, sizeof(int), cudaMemcpyDeviceToHost);
    cudaDeviceSynchronize();

    printf("shrinked_size_host=%d\n", *shrinked_size_host);
    return 0;
}

That's the output produced from the program:

*

*Hello world CPU

*Set device variable to: 12

*Segmentation fault (core dumped)
Not sure why there is a segmentation fault.

A: I figured out the answer to this question.
Memory for the shrinked_size_host should be allocated. So, either do:

*

*Heap allocation: malloc or new int to allocate an integer of size 1. Remember to delete the allocated memory at the end.

*Stack allocation: Use int shrinked_size_host[1];


text:
Q: How to apply .astype() method to a dataframe in Python? I want to convert multiple columns in a dataframe (pandas) to the type "category" using the method .astype. Here is my code:
df['Field_1'].astype('category').cat.codes

works however
categories = df.select_types('objects')
categories['Field_1'].cat.codes

doesn't.
Would someone please tell my why?
In general, the question is how to apply a method (.astype) to a dataframe? I know how to apply a method to a column in a dataframe, however, applying it to a dataframe hasnt been successful, even with for loop since the for loop returns a series and the method .cat.codes is not appliable for the series.

A: I think you need processing each column separately in DataFrame.apply and lambda function, your code failed, because Series.cat.codes is not implemented for DataFrame:
df = pd.DataFrame({
        'A':list('acbdac'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':list('dddbbb')
})

cols = df.select_dtypes('object').columns
df[cols] = df[cols].apply(lambda x: x.astype('category').cat.codes)
print (df)
   A  B  C  D
0  0  4  7  1
1  2  5  8  1
2  1  4  9  1
3  3  5  4  0
4  0  5  2  0
5  2  4  3  0

Similar idea, not sure if same output if convert all columns to categorical in first step by DataFrame.astype:
cols = df.select_dtypes('object').columns
df[cols] = df[cols].astype('category').apply(lambda x: x.cat.codes)
print (df)
   A  B  C  D
0  0  4  7  1
1  2  5  8  1
2  1  4  9  1
3  3  5  4  0
4  0  5  2  0
5  2  4  3  0


text:
Q: Xcode 9 Version editor - Sticky scrolling When I try to scroll in Xcode 9's Version editor with touchpad gestures, it "sticks" to the current change in the file. This GIF illustrates the problem:

When I drag the scrollbar, it scrolls fine that way.
Is there a method to fix this behavior?


text:
Q: centos 6.4 php-fpm install I've bought a VPS from a hosting provider and I want to set it up.
The server is a CentOS-6.4 and the provider installed WHM on it, so it has apache installed as well.
I have 3 IPs available and I managed to install nginx and make it listen on one of the IPs, while apache still responds to the first IP and WHM/CPanel works fine.
My issue is with getting nginx to function properly. It works fine serving HTML content, but for PHP it needs php-fpm or similar to work.
I've read countless blog posts about how to get this to work and they all say: "add the epel.repo and remi.repo, set priorities and yum install php-fpm and whatever extension you might need.
The problem is when I try to yum install, I get:
No package php-fpm available.
No package php-cli available.
No package php-mysql available.
No package php-gd available.
No package php-imap available.
No package php-ldap available.
No package php-odbc available.
No package php-pear available.
No package php-xml available.
No package php-xmlrpc available.
No package php-magickwand available.
No package php-magpierss available.
No package php-mbstring available.
No package php-mcrypt available.
No package php-mssql available.
No package php-shout available.
No package php-snmp available.
No package php-soap available.
No package php-tidy available.
Error: Nothing to do

Any clues as to why it's not working?

A: I think your problem would be solved using the command:
yum --enablerepo=remi install php-fpm

to install php-fpm, if you've added the repo previously.


text:
Q: On the big $O$ notation asymptotics If $f:\mathbb{C}\to \mathbb{C}$ is a function and $$-\Im(f(x+iy))=\mathcal{O}(y)$$ where $\mathcal{O}$ is the big O notation,
then prove that $$\Im(f(x+iy))=\mathcal{O}(y) \ \ \ \ \text{as} \ \ \ \ y\to \infty$$
I tried: Since $$-\Im(f(x+iy))=\mathcal{O}(y)
 \ \ \ \ \text{as} \ \ \ \ y\to \infty   $$ so there exists $M,y_0$ such that $$|\Im(f(x+iy))|\leq M y $$ whenever $y\geq y_0$.
So can we say from the above that $$\Im(f(x+iy))=\mathcal{O}(y)  \ \ \ \ \text{as} \ \ \ \ y\to \infty  $$
Do we require the limit definition of big O?


text:
Q: Forecasting currencies with ARIMA (error occurred: 'ts' object must have one or more observations) Hi I tried to plot future values with ARIMA but this error happened: 'ts' object must have one or more observations.
Import dataset:
library(priceR)
a <- historical_exchange_rates("THB", to = "USD",start_date = "2010-01-01", end_date = "2021-12-31")
Making a timeseries dataset:
library(forecast)
a.dfts <- ts(a$one_THB_equivalent_to_x_USD, frequency=12, start=c(2010,01,01), end=c(2021,12,31))
Apply ARIMA model:
library(TSA)
loga <- diff(log(a.dfts))
finala.arma <- arima(loga, order = c(0,0,2))
Forecasting future values:
forca.ARIMA <- forecast(finala.arma, h=24, level=c(80,95))
Then this is where I got an error.
Error in ts(x) : 'ts' object must have one or more observations


text:
Q: dbm package: file is not a database on open with SQLITE viewer I made a database with the Python package dbm but I cannot seem to find any way to open it. The file is recognizable for reading and writing but when I try to open it visually using SQLITE viewer, it gives back: "An error occurred: file is not a database".
Here is how I open and write one thing but I cannot view it with a VS code extension:
with dbm.open('cache', 'c') as db:
    db['www.python.org'] = 'Python Website'

A: The dbm package is NOT SQLite. The SQLite package is called "sqlite3"


text:
Q: Clearing the bash "source buffer" When running a bash script like source script or . script from the command line, then all the lines in the script are added to bash's "source buffer" and then the current command shell just continues. Stopping execution is impossible (apart from aborting the shell), using ctrl-C only interrupts the current command, but then the next command is executed.
Where is this buffer, and would it be possible to clear it??
Example script:
echo A
sleep 10
echo B
sleep 10
echo C
sleep 10
echo D

After having done "source script", is there any way to stop it executing any further after it has been 'submitted'?

A: There is - to the best of my knowledge - no such thing as a source buffer in bash, so there is nothing to erase. The source command just executes the commands found in its arguments in the current environment (i.e. not in a child process).
There is nothing in the handling of source which is in particular related to the handling of signals. Maybe your shell script  is setup to ignore Control-C? I suggest that you run your script with -x in order to find the culprit.


text:
Q: How can I open a image from an ImageField before validating and saving a form? I want to get the value of a CharField based on the value of an ImageField. My form and view are defined as:
#Form
class GpsImForm(forms.Form):
    image = forms.ImageField(required=True)
    gps_data = forms.CharField(required=True)

#View
def gpsim_gen_view(request):
    if request.method == 'POST':
        form = GpsImForm(request.POST, request.FILES)
        if 'image' in request.FILES:
            im = request.FILES['image']
            i = Image.open(im)
            ... # functions to extract exif data from i
            request.POST.update({ 'gps_data': ...}) # set gps_data based on exif data from i
        if form.is_valid():
            obj = form.save()
            return ... #returns the gpsim
    else:
        form = GpsImForm()
    return direct_to_template(request, 'gpsim_generate.html', {'form': form,})

The gps_data is updated, but, as soon as I use Image.open(), I get the following error message:

Upload a valid image. The file you uploaded was either not an image or a corrupted image.

If I comment the lines concerning i and modify the gps_data to whatever, the form (with the image) is saved without any error...
# i = Image.open(im)
# ...
# functions to extract exif data from i
request.POST.update({ 'gps_data': 'some text'}) # set gps_data to 'test'

A: first of all, make sure that your form has the enctype tag
<form enctype="multipart/form-data" ... >

Try to write the img (all the chunks) on disk:
import Image
from random import choice
from django.conf import settings

random_file_name = getattr(settings, 'FILE_UPLOAD_TEMP_DIR', '/tmp')
random_file_name +=  '/' + ''.join([choice('abcdefg') for i in range(12)]) + '.jpg'

destination = open(random_file_name, 'wb+')
for chunk in request.FILES['image'].chunks():
    destination.write(chunk)
destination.close()

Then, you can open it from disk:
image = Image.open(random_file_name)
if image.mode != "RGB":
    image = image.convert("RGB")

...

This URL may help you:
https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

A: I finally found a cleaner solution:
I removed the "required=True" from my models and defined a clean() method which does the job in my form models:
#Form
class GpsImForm(forms.Form):
    image = forms.ImageField(required=True)
    gps_data = forms.CharField()

    def clean(self):
        super(forms.Form, self)).clean()
        if not self.cleaned_data['gps_data']:  # the user can provide the gps_data manually
            if self.cleaned_data['image']:     # if he provided no gps_data but an image
                i = Image.open(self.cleaned_data['image'])
                ... # functions to extract exif data from i
            else:
                msg = _("You have to provide an image or a gps_data.")
                self._errors['gps_data'] = self.error_class([msg])
        return self.cleaned_data

#View
def gpsim_gen_view(request):
    if request.method == 'POST':
        form = GpsImForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save()
            return ... #returns the gpsim
    else:
        form = GpsImForm()
    return direct_to_template(request, 'gpsim_generate.html', {'form': form,})


text:
Q: Deleted a folder, get ModuleNotFoundError: No module named "api" I am using Django and trying to use Django Rest Framework as well.
Since I had never used Django Rest Framework, I did a kind of tutorial by following an article. To do this, I created a new app by entering python manage.py startapp app.
After I finished the tutorial, I deleted this app in order to work on my project.
However, when I try to make the server run I got this error.
(venv) (base) MacBook-Air-4:extra_exchange user$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/base.py", line 368, in execute
    self.check()
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check
    databases=databases,
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check
    for pattern in self.url_patterns:
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Users/user/opt/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/user/Desktop/my_project/extra_exchange/extra_exchange/urls.py", line 21, in <module>
    path("api/", include("api.urls"))
  File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/Users/user/opt/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'api'

On the very last line, it says No module named 'api'.
But as I said, I have already deleted this. I looked for solutions but all solutions tell about already installed files, not deleted files.
I would like you to teach me how to figure it out.
Before I deleted this api file, the structure of files is like this.
project
|
|- app
| |
| |- migrations
| |      ...
| |- and everything
|
|- api(deleted folder)
| |
| |- migrations
| |      ...
| |- and everything
|
|-my_project
| |
| |- setting.py
| |      ...
| |- and everything
|
|-venv
|-manage.py

A: Actually, I forgot to remove some urls from urls.py, that's why I got the error.
Thank you for watching it. I figured it out.

A: I just spent almost an hour trying to figure out something similar myself.
I deleted all references to my app from my project but kept getting this error.
I searched the entire project in my IDE (VS Code) for references to the app, but didn't find any. (even reinstalled Django but no luck).
Finally I decided to do a grep within the project folder. Sure enough I found a reference. What happened was that I edited the file, but didn't save it.
Hopefully someone will benefit from my experience.


text:
Q: Роутинг не работает, как хотелось бы, как сделать по уму? Я начинающий,у меня написаны роуты, но всё работает не так как хотелось бы.
точнее если я пишу роут в таком роде
return array('add-product'=>'products/add','products' => 'products/index');

редирект работает,но если я оставляю пуcтую строку,как ниже,то он тоже работает,но если я ввожу в URI что-то,что абсолютно не совпадает с ключём из массива,редирект не работает и он начинает обрабатывать эту муть.
Вот .htaccess
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.+)$ index.php [QSA,L]

Задача такова,чтобы при переходе по хост имени вызывался экшн и все остальные запросы делали редирект на основную страницу,за исключением запросов совпадающих с роутами.
Есть конфиг с роутами возвращающий массив роутов
return array('add-product'=>'products/add','' => 'products/index');

И есть вот такой метод,который проверяет не пустой ли URI и возвращает его ,чтобы дальше использовать в следующем методе
public function getURI(){
        if(!empty($_SERVER['REQUEST_URI'])){
            return trim($_SERVER['REQUEST_URI'],'/');
        }
    }

Потом это всё разбивается вычисляются контроллеры и экшены, после чего они вызываются.
public function connectFile($controllerName){

        $fileOfController = ROOT.'/controllers/'.$controllerName.'.php';
        if(file_exists($fileOfController)){
            include_once $fileOfController;
        }
    }
    public function createAndCallInstanceWithoutParams($controllerName,$actionName){
        $instanceOfController = new $controllerName;
        $instanceOfController ->$actionName();
        if($instanceOfController != null){
            return true;
        }
    }
    public function createAndCallInstanceWithParams($controllerName,$actionName,$parametrs){
        $instanceOfController = new $controllerName;
        call_user_func_array(array($instanceOfController,$actionName),$parametrs);
        if($instanceOfController != null){
            return true;
        }
    }

    public function run(){

        $uri = $this->getURI();

        foreach ($this->routes as $uriPattern => $path){

            if(preg_match("~$uriPattern~", $uri)){

                $internalRoute = preg_replace("~$uriPattern~", $path, $uri);

                $segments = explode('/', $internalRoute);

                $controllerName = ucfirst(array_shift($segments).'Controller');
                $actionName = 'action'. ucfirst(array_shift($segments));
                $parametrs = $segments;

                $fileConnection = $this ->connectFile($controllerName);

                $instanceStatus = 0;

                if(empty($parametrs)){
                    $this->createAndCallInstanceWithoutParams($controllerName, $actionName);
                    $instanceStatus++;
                }else{
                    $this->createAndCallInstanceWithParams($controllerName, $actionName, $parametrs);
                    $instanceStatus++;
                }
                if($instanceStatus == 1){
                    break;
                }
            }

        }

    }

Заранее благодарен за изъявленный интерес.


text:
Q: Wrong PID for busybox init process I have set up a small embedded linux that uses busybox. I am facing a problem of which I'm not sure if its caused by busybox or the kernel.
The problem is, that the init process does not have process ID 1. Heres the output of ps:
1 root       0:26 [swapper/0]
2 root       0:00 [kthreadd]
3 root       0:00 [ksoftirqd/0]
4 root       0:00 [kworker/0:0]
5 root       0:00 [kworker/0:0H]
6 root       0:00 [kworker/u4:0]
7 root       0:00 [rcu_preempt]
8 root       0:00 [rcu_sched]
...
549 root       0:00 {linuxrc} init
...

I guess the other processes before init are all kernel processes. The reason why this is a problem is that orphaned processes are given the parent process ID 1, which should be the init process, but now this swapper process is receiving them all.
I noticed that something is going wrong when I observed a lot of zombie processes.
So somehow either init must be forced to PID 1, or orphaned processes must be assigned to the correct init PID.
Does anyone have an idea how to do that?
Thanks a lot!

Update: Some more information on my setup
The target is an ARM board with a Xilinx Zynq chip. I was using the Xilinx linux Kernel, and compiled busybox myself (v1.20.2).
The command line is:
ramdisk_size=65536 console=ttyPS0,115200 earlyprintk
Here are the bootlogs up to the moment that the init script is started:
Uncompressing Linux... done, booting the kernel.
[    0.000000] Booting Linux on physical CPU 0x0
[    0.000000] Linux version 3.13.0-xilinx (cone@cone-ubuntu) (gcc version 4.8.1 (Sourcery CodeBench Lite 2013.11-53) ) #5 SMP PREEMPT Sun J4
[    0.000000] CPU: ARMv7 Processor [413fc090] revision 0 (ARMv7), cr=18c5387d
[    0.000000] CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache
[    0.000000] Machine model: Xilinx Zynq
[    0.000000] bootconsole [earlycon0] enabled
[    0.000000] Memory policy: Data cache writealloc
[    0.000000] PERCPU: Embedded 8 pages/cpu @c101e000 s10176 r8192 d14400 u32768
[    0.000000] Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 130048
[    0.000000] Kernel command line: ramdisk_size=65536 console=ttyPS0,115200 earlyprintk
[    0.000000] PID hash table entries: 2048 (order: 1, 8192 bytes)
[    0.000000] Dentry cache hash table entries: 65536 (order: 6, 262144 bytes)
[    0.000000] Inode-cache hash table entries: 32768 (order: 5, 131072 bytes)
[    0.000000] Memory: 501272K/524288K available (4781K kernel code, 307K rwdata, 1692K rodata, 197K init, 5345K bss, 23016K reserved, 0K hi)
[    0.000000] Virtual kernel memory layout:
[    0.000000]     vector  : 0xffff0000 - 0xffff1000   (   4 kB)
[    0.000000]     fixmap  : 0xfff00000 - 0xfffe0000   ( 896 kB)
[    0.000000]     vmalloc : 0xe0800000 - 0xff000000   ( 488 MB)
[    0.000000]     lowmem  : 0xc0000000 - 0xe0000000   ( 512 MB)
[    0.000000]     pkmap   : 0xbfe00000 - 0xc0000000   (   2 MB)
[    0.000000]     modules : 0xbf000000 - 0xbfe00000   (  14 MB)
[    0.000000]       .text : 0xc0008000 - 0xc065a600   (6474 kB)
[    0.000000]       .init : 0xc065b000 - 0xc068c7c0   ( 198 kB)
[    0.000000]       .data : 0xc068e000 - 0xc06dac78   ( 308 kB)
[    0.000000]        .bss : 0xc06dac84 - 0xc0c13230   (5346 kB)
[    0.000000] Preemptible hierarchical RCU implementation.
[    0.000000]  RCU lockdep checking is enabled.
[    0.000000]  Dump stacks of tasks blocking RCU-preempt GP.
[    0.000000]  RCU restricting CPUs from NR_CPUS=4 to nr_cpu_ids=2.
[    0.000000] NR_IRQS:16 nr_irqs:16 16
[    0.000000] ps7-slcr mapped to e0802000
[    0.000000] zynq_clock_init: clkc starts at e0802100
[    0.000000] Zynq clock init
[    0.000000] sched_clock: 32 bits at 325MHz, resolution 3ns, wraps every 13215283196ns
[    0.000000] ps7-ttc #0 at e0804000, irq=43
[    0.000000] Console: colour dummy device 80x30
[    0.000000] Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar
[    0.000000] ... MAX_LOCKDEP_SUBCLASSES:  8
[    0.000000] ... MAX_LOCK_DEPTH:          48
[    0.000000] ... MAX_LOCKDEP_KEYS:        8191
[    0.000000] ... CLASSHASH_SIZE:          4096
[    0.000000] ... MAX_LOCKDEP_ENTRIES:     16384
[    0.000000] ... MAX_LOCKDEP_CHAINS:      32768
[    0.000000] ... CHAINHASH_SIZE:          16384
[    0.000000]  memory used by lock dependency info: 3695 kB
[    0.000000]  per task-struct memory footprint: 1152 bytes
[   13.207599] Calibrating delay loop... 1292.69 BogoMIPS (lpj=6463488)
[   13.207606] pid_max: default: 32768 minimum: 301
[   13.207607] Mount-cache hash table entries: 512
[   13.207609] CPU: Testing write buffer coherency: ok
[   13.207610] CPU0: thread -1, cpu 0, socket 0, mpidr 80000000
[   13.207611] Setting up static identity map for 0x489b98 - 0x489bf0
[   13.207612] L310 cache controller enabled
[   13.207613] l2x0: 8 ways, CACHE_ID 0x410000c8, AUX_CTRL 0x72760000, Cache size: 512 kB
[   13.207627] CPU1: Booted secondary processor
[   13.207641] CPU1: thread -1, cpu 1, socket 0, mpidr 80000001
[   13.207642] Brought up 2 CPUs
[   13.207644] SMP: Total of 2 processors activated.
[   13.207644] CPU: All CPU(s) started in SVC mode.
[   13.207646] devtmpfs: initialized
[   13.207647] VFP support v0.3: implementor 41 architecture 3 part 30 variant 9 rev 4
[   13.207650] regulator-dummy: no parameters
[   13.207651] NET: Registered protocol family 16
[   13.207651] DMA: preallocated 256 KiB pool for atomic coherent allocations
[   13.207654] cpuidle: using governor ladder
[   13.207654] cpuidle: using governor menu
[   13.207658] syscon f8000000.ps7-slcr: regmap [mem 0xf8000000-0xf8000fff] registered
[   13.207660] hw-breakpoint: found 5 (+1 reserved) breakpoint and 1 watchpoint registers.
[   13.207662] hw-breakpoint: maximum watchpoint size is 4 bytes.
[   13.207663] zynq-ocm f800c000.ps7-ocmc: ZYNQ OCM pool: 256 KiB @ 0xe0880000
[   13.207672] bio: create slab <bio-0> at 0
[   13.207674] vgaarb: loaded
[   13.207674] SCSI subsystem initialized
[   13.207675] usbcore: registered new interface driver usbfs
[   13.207676] usbcore: registered new interface driver hub
[   13.207677] usbcore: registered new device driver usb
[   13.207678] media: Linux media interface: v0.10
[   13.207679] Linux video capture interface: v2.00
[   13.207680] pps_core: LinuxPPS API ver. 1 registered
[   13.207681] pps_core: Software ver. 5.3.6 - Copyright 2005-2007 Rodolfo Giometti <giometti@linux.it>
[   13.207682] PTP clock support registered
[   13.207683] EDAC MC: Ver: 3.0.0
[   13.207685] DMA-API: preallocated 4096 debug entries
[   13.207686] DMA-API: debugging enabled by kernel config
[   13.207687] Switched to clocksource arm_global_timer
[   13.207696] NET: Registered protocol family 2
[   13.207697] TCP established hash table entries: 4096 (order: 2, 16384 bytes)
[   13.207698] TCP bind hash table entries: 4096 (order: 5, 147456 bytes)
[   13.207699] TCP: Hash tables configured (established 4096 bind 4096)
[   13.207700] TCP: reno registered
[   13.207701] UDP hash table entries: 256 (order: 2, 20480 bytes)
[   13.207702] UDP-Lite hash table entries: 256 (order: 2, 20480 bytes)
[   13.207703] NET: Registered protocol family 1
[   13.207704] RPC: Registered named UNIX socket transport module.
[   13.207705] RPC: Registered udp transport module.
[   13.207706] RPC: Registered tcp transport module.
[   13.207707] RPC: Registered tcp NFSv4.1 backchannel transport module.
[   13.207708] Trying to unpack rootfs image as initramfs...
[   13.207709] rootfs image is not initramfs (no cpio magic); looks like an initrd
[   13.207717] Freeing initrd memory: 6004K (df551000 - dfb2e000)
[   13.207718] hw perfevents: enabled with ARMv7 Cortex-A9 PMU driver, 7 counters available
[   13.207722] jffs2: version 2.2. (NAND) (SUMMARY)  © 2001-2006 Red Hat, Inc.
[   13.207723] msgmni has been set to 990
[   13.207724] io scheduler noop registered
[   13.207724] io scheduler deadline registered
[   13.207725] io scheduler cfq registered (default)
[   13.207728] dma-pl330 f8003000.ps7-dma: unable to set the seg size
[   13.207729] dma-pl330 f8003000.ps7-dma: Loaded driver for PL330 DMAC-2364208
[   13.207731] dma-pl330 f8003000.ps7-dma:      DBUFF-128x8bytes Num_Chans-8 Num_Peri-4 Num_Events-16
[   13.207733] e0001000.serial: ttyPS0 at MMIO 0xe0001000 (irq = 82, base_baud = 3125000) is a xuartps
[   13.207734] console [ttyPS0] enabled
[   13.207734] console [ttyPS0] enabled
[   13.207735] bootconsole [earlycon0] disabled
[   13.207735] bootconsole [earlycon0] disabled
[   13.207737] xdevcfg f8007000.ps7-dev-cfg: ioremap 0xf8007000 to e0866000
[   13.207743] brd: module loaded
[   13.207746] loop: module loaded
[   13.207748] zynq-qspi e000d000.ps7-qspi: master is unqueued, this is deprecated
[   13.207749] zynq-qspi e000d000.ps7-qspi: at 0xE000D000 mapped to 0xE0868000, irq=51
[   13.207752] e1000e: Intel(R) PRO/1000 Network Driver - 2.3.2-k
[   13.207753] e1000e: Copyright(c) 1999 - 2013 Intel Corporation.
[   13.207754] libphy: XEMACPS mii bus: probed
[   13.207755] xemacps e000b000.ps7-ethernet: pdev->id -1, baseaddr 0xe000b000, irq 54
[   13.207757] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver
[   13.207758] ehci-pci: EHCI PCI platform driver
[   13.207759] ULPI transceiver vendor/product ID 0x0424/0x0007
[   13.207760] Found SMSC USB3320 ULPI transceiver.
[   13.207761] ULPI integrity check: passed.
[   13.207761] zynq-ehci zynq-ehci.0: Xilinx Zynq USB EHCI Host Controller
[   13.207763] zynq-ehci zynq-ehci.0: new USB bus registered, assigned bus number 1
[   13.207769] zynq-ehci zynq-ehci.0: irq 53, io mem 0x00000000
[   13.207772] zynq-ehci zynq-ehci.0: USB 2.0 started, EHCI 1.00
[   13.207773] usb usb1: New USB device found, idVendor=1d6b, idProduct=0002
[   13.207774] usb usb1: New USB device strings: Mfr=3, Product=2, SerialNumber=1
[   13.207775] usb usb1: Product: Xilinx Zynq USB EHCI Host Controller
[   13.207776] usb usb1: Manufacturer: Linux 3.13.0-xilinx ehci_hcd
[   13.207777] usb usb1: SerialNumber: zynq-ehci.0
[   13.207779] hub 1-0:1.0: USB hub found
[   13.207779] hub 1-0:1.0: 1 port detected
[   13.207781] usbcore: registered new interface driver usb-storage
[   13.207782] mousedev: PS/2 mouse device common for all mice
[   13.207783] i2c /dev entries driver
[   13.207784] cdns-i2c e0004000.ps7-i2c: 400 kHz mmio e0004000 irq 57
[   13.207787] xadcps f8007100.ps7-xadc: enabled:       yes     reference:      external
[   13.207788] cdns-wdt f8005000.ps7-wdt: Xilinx Watchdog Timer at e0876000 with timeout 10s
[   13.207790] zynq-edac f8006000.ps7-ddrc: ecc not enabled
[   13.207791] Xilinx Zynq CpuIdle Driver started
[   13.207590] sdhci: Secure Digital Host Controller Interface driver
[   13.207591] sdhci: Copyright(c) Pierre Ossman
[   13.207592] sdhci-pltfm: SDHCI platform and OF driver helper
[   13.207593] sdhci-arasan e0100000.ps7-sdio: dummy supplies not allowed
[   13.207594] mmc0: no vqmmc regulator found
[   13.207595] sdhci-arasan e0100000.ps7-sdio: dummy supplies not allowed
[   13.207596] mmc0: no vmmc regulator found
[   13.207603] mmc0: SDHCI controller on e0100000.ps7-sdio [e0100000.ps7-sdio] using ADMA
[   13.207608] usbcore: registered new interface driver usbhid
[   13.207608] usbhid: USB HID core driver
[   13.207609] TCP: cubic registered
[   13.207610] NET: Registered protocol family 17
[   13.207611] Registering SWP/SWPB emulation handler
[   13.207612] drivers/rtc/hctosys.c: unable to open rtc device (rtc0)
[   13.207614] mmc0: new high speed SDHC card at address 59b4
[   13.207615] mmcblk0: mmc0:59b4 USD   14.7 GiB
[   13.207617]  mmcblk0: p1 p2
[   13.207618] RAMDISK: gzip image found at block 0
[   13.207691] usb 1-1: new high-speed USB device number 2 using zynq-ehci
[   13.207707] VFS: Mounted root (ext2 filesystem) on device 1:0.
Starting rcS...

@sawdust: I don't have a /init file. I think /linuxrc is the first thing that is executed, and that is just a symlink to busybox.

A: I think I solved the problem. Apparently, adding root=/dev/ram to the boot parameters does the trick. I saw that being recommended somewhere online, but I can't find the link anymore. I'm not entirely sure why this is necessary, but it works :-)


text:
Q: Does a Nonhomogeneous linear differential equation imply itself that it is not linear? I am troubled by the fact that we call a nonhomogeneous differential equation of the form :
$a_0(x)y+a_1(x)y'+a_2(x)y''+...+a_n(x)y^{(n)}=b(x)$, where $b(x)$ is nonzero. Linear.
From what I know, being homogeneous or having the homogeneity property for differential equations is to satisfy the rule : $Lay(x)=aLy(x)$, therefore if the differential equation is not homogeneous, then it cannot satisfy the homogeneity property: $Lay(x)=aLy(x)$.
I also know though that for a differential equation to be linear, it must both satisfy the additive property and homogeneity property, but since the nonhomogeneous differential equation above doesn't satisfy the homogeneous property, then it must be nonlinear right ?

A: We call the non-homogeneous DE you wrote out linear because the operator that acts on $y$ is linear:
$$L=a_0(x)+a_1(x)D+a_2(x)D^2+\cdots+a_n(x)D^n,$$
where $D=d/dx$ is the derivative operator. That is, you can write the DE as $Ly=b(x).$ $L$ is linear in the true sense. It's no different from what we call a linear operator in linear algebra if we're solving the matrix equation $Ax=b.$ It's still a linear equation, despite being non-homogeneous, because the operator $A$ is linear.
We do have a word, by the way, for an equation like $y=mx+b,$ which is the word affine.


text:
Q: C# Winform : Control locked but locked propety is set to false I have a really strange situation in my winform application.
I'm trying to change the design of a certain form but controls are locked so I can't do anything.
If I right click on it, the lock button is not pressed. If I check properties of the control, anything is grayed out but the "locked" property is set to false.

The document outline (main form is not locked) :

The project is 10 years old and was first made with .NET 2 (now it's in 3.5).
There is a lot of form that I could change, but not this one.
Thx for your help
PS : I don't really want to copy/paste in a new form (the project is a total mess).

A: It's almost certain that the form you are trying to edit is in fact derived from another form - have a look at its base type, and it should be obvious. Whatever controls are on the parent will be locked in the children - all the children share the same controls, so you don't want to move them by accident. If you do want to move them in all children, just open the parent form in the designer.


text:
Q: List of DisposableLazy`2 does not have 'Add' method when called using dynamic variable Problem
I am facing a problem using dynamically created list of items when Add method is called on dynamicvariable. Consider following code.
IEnumerable<dynamic> plugins = (IEnumerable<dynamic>)field.GetValue(instance);
if (plugins == null)
  continue;

dynamic filteredPlugins = null;
foreach (var plugin in plugins)
{
  if (filteredPlugins == null)
  filteredPlugins = Activator
    .CreateInstance(typeof(List<>)
    .MakeGenericType(plugin.GetType()));

if (/* this condition does not matter*/)
  //filteredPlugins.Add(plugin);
  filteredPlugins.GetType().GetMethod("Add")
    .Invoke(filteredPlugins, new object[] { plugin });
}

And now, the commented line filteredPlugins.Add(plugin) will throw System.Reflection.TargetInvocationException with the message 'object' does not contain a definition for 'Add' when plugin is of type
System.ComponentModel.Composition.ExportServices.DisposableLazy<IPlugin,IMetadata>

but it works completely perfect when pluginis of type
System.Lazy<IPlugin, IMetadata>

When the reflection is used to call Add method on the instance filteredPlugins instance as is done on the next line - everything works fine for any type.
My question is WHY is not Add method found in case of DisposableLazy type.
Background
This code is part of the method that I use in OnImportsSatisfied() method. I am using two kinds of import - which differs only in RequiredCreationPolicy - on has CreationPolicy.NonShared and the other default value of CreationPolicy.Any.
[ImportMany(RequiredCreationPolicy = CreationPolicy.NonShared)]
private IEnumerable<Lazy<IPlugin, IMetadata>> plugins = null;

For CreationPolicy.NonShared fields the underlaying type in the plugins is DisposableLazy and for CreationPolicy.Any the underlaying type in the plugins is Lazy.
Edit: As asked in the answer - I am using dynamic variable because IPlugin interface can change everytime this method is called and they do not have to have anything in common.
Edit2: I just found similar question C# dynamic type gotcha, so this can be probably closed as duplicite.

A: Because System.ComponentModel.Composition.ExportServices.DisposableLazy is a private class, the runtime binder is having trouble believing you have permission to use type, where reflection doesn't care.
Which begs the question why are you using dynamics at all in this case.  Since DisposableLazy<IPlugin,IMetadata> public interface is it's subclass Lazy<IPlugin, IMetadata> & IDisposable, shouldn't you just be using a List<Lazy<IPlugin, IMetadata>> for either case?
var plugins = (IEnumerable<Lazy<IPlugin, IMetadata>>)field.GetValue(instance);
if (plugins == null)
  continue;

var filteredPlugins = new List<Lazy<IPlugin, IMetadata>>();
foreach (var plugin in plugins)
{
  if (/* this condition does not matter*/)
     filteredPlugins.Add(plugin);
  }
}


text:
Q: SQL query issue on thrift server client I have performed join on 2 tables memberstable (service_id,created_date) and member_servicestable (id and user_id) the join was made on registered id and id since they are the same. I want to get the total number of user ids for service id using a join. I created a view called users and executed this query. I got what I wanted.
SELECT service_id ,COUNT(*) user_id
FROM users
WHERE created_date >= '2020-01-01 00:00:00.000' and created_date <= '2020-01-31 23:59:59.999'
GROUP BY service_id Having COUNT(*) > 1

But I need to get the same result using joins, I'm getting some errors such as grouping expressions sequence is empty, not an aggregate function.
Code to create view users:
CREATE VIEW users AS
SELECT member_servicestable.user_id
       , memberstable.created_date
       , memberstable.service_id
       , member_servicestable.id
FROM memberstable
     , member_servicestable
WHERE memberstable.service_id = member_servicestable.id;


text:
Q: Own asin() function (with Taylor series) not accurate I need to write my own asin() function without math.h library with the use of Taylor series. It works fine for numbers between <-0.98;0.98> but when I am close to limits it stops with 1604 iterations and therefore is inaccurate.
I don't know how to make it more accurete. Any suggestions are very appreciated!
The code is following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define EPS 0.000000000001

double my_arcsin(double x)
{
    long double a, an, b, bn;
    a = an = 1.0;
    b = bn = 2.0;
    long double n = 3.0;
    double xn;
    double xs = x;
    double xp = x;

    int iterace = 0;

    xn = xs + (a/b) * (my_pow(xp,n) / n);

    while (my_abs(xn - xs) >= EPS)
    {
        n += 2.0;
        an += 2.0;
        bn += 2.0;
        a = a * an;
        b = b * bn;

        xs = xn;
        xn = xs + (a/b) * (my_pow(xp,n) / n);
        iterace++;
    }

    //printf("%d\n", iterace);

    return xn;
}

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

    double x = 0.0;

    if (argc > 2)
        x = strtod(argv[2], NULL);
    if (strcmp(argv[1], "--asin") == 0)
    {
           if (x < -1 || x > 1)
               printf("nan\n");
           else
           {
               printf("%.10e\n", my_arcsin(x));
               //printf("%.10e\n", asin(x));
           }

        return 0;
    }
}

And also a short list of my values and expected ones:
My values              Expected values        my_asin(x)
5.2359877560e-01       5.2359877560e-01       0.5
1.5567132089e+00       1.5707963268e+00       1      //problem
1.4292568534e+00       1.4292568535e+00       0.99   //problem
1.1197695150e+00       1.1197695150e+00       0.9
1.2532358975e+00       1.2532358975e+00       0.95

A: Even though the convergence radius of the series expansion you are using is 1, therefore the series will eventually converge for -1 < x < 1, convergence is indeed painfully slow close to the limits of this interval. The solution is to somehow avoid these parts of the interval.
I suggest that you

*

*use your original algorithm for |x| <= 1/sqrt(2),

*use the identity arcsin(x) = pi/2 - arcsin(sqrt(1-x^2)) for 1/sqrt(2) < x <= 1.0,

*use the identity arcsin(x) = -pi/2 + arcsin(sqrt(1-x^2)) for -1.0 <= x < -1/sqrt(2).

This way you can transform your input x into [-1/sqrt(2),1/sqrt(2)], where convergence is relatively fast.

A: PLEASE NOTICE: In this case I strongly recommend @Bence's method, since you can't expect a slowly convergent method with low data accuracy to obtain arbitrary precision.
However I'm willing to show you how to improve the result using your current algorithm.
The main problem is that a and b grows too fast and soon become inf (after merely about 150 iterations). Another similar problem is my_pow(xp,n) grows fast when n grows, however this doesn't matter much in this very case since we could assume the input data goes inside the range of [-1, 1].
So I've just changed the method you deal with a/b by introducing ab_ratio, see my edited code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define EPS 0.000000000001

#include <math.h>
#define my_pow powl
#define my_abs fabsl

double my_arcsin(double x)
{
    #if 0
    long double a, an, b, bn;
    a = an = 1.0;
    b = bn = 2.0;
    #endif
    unsigned long _n = 0;
    long double ab_ratio = 0.5;
    long double n = 3.0;
    long double xn;
    long double xs = x;
    long double xp = x;

    int iterace = 0;

    xn = xs + ab_ratio * (my_pow(xp,n) / n);
    long double step = EPS;

    #if 0
    while (my_abs(step) >= EPS)
    #else
    while (1) /* manually stop it */
    #endif
    {
        n += 2.0;
        #if 0
        an += 2.0;
        bn += 2.0;
        a = a * an;
        b = b * bn;
        #endif
        _n += 1;
        ab_ratio *= (1.0 + 2.0 * _n) / (2.0 + 2.0 * _n);

        xs = xn;
        step = ab_ratio * (my_pow(xp,n) / n);
        xn = xs + step;
        iterace++;
        if (_n % 10000000 == 0)
            printf("%lu %.10g %g %g %g %g\n", _n, (double)xn, (double)ab_ratio, (double)step, (double)xn, (double)my_pow(xp, n));
    }

    //printf("%d\n", iterace);

    return xn;
}

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

    double x = 0.0;

    if (argc > 2)
        x = strtod(argv[2], NULL);
    if (strcmp(argv[1], "--asin") == 0)
    {
           if (x < -1 || x > 1)
               printf("nan\n");
           else
           {
               printf("%.10e\n", my_arcsin(x));
               //printf("%.10e\n", asin(x));
           }

        return 0;
    }
}

For 0.99 (and even 0.9999999) it soon gives correct results with more than 10 significant digits. However it gets slow when getting near to 1.
Actually the process has been running for nearly 12 minutes on my laptop calculating --asin 1, and the current result is 1.570786871 after 3560000000 iterations.
UPDATED: It's been 1h51min now and the result 1.570792915 and iteration count is 27340000000.


text:
Q: How to use ContextReplacementPlugin on a require wrapped in a loop I'm trying to use the ContextReplacementPlugin to resolve dynamic requires occurring in this for loop: https://github.com/mongodb/js-bson/blob/master/lib/bson/index.js#L7-L24
Here's the code:
[ './binary_parser'
  , './binary'
  , './code'
  , './map'
  , './db_ref'
  , './double'
  , './max_key'
  , './min_key'
  , './objectid'
  , './regexp'
  , './symbol'
  , './timestamp'
  , './long'].forEach(function (path) {
    var module = require(path);
    for (var i in module) {
        exports[i] = module[i];
    }
});

I'm having trouble constructing a source regex to match this. The path being matched against the source seems to be just ".". Moreover, the context plugin seems to be called only once when there are actually 13 files being required in this loop. Can the ContextReplacementPlugin be used to resolve this issue or should I try something else?


text:
Q: R shiny app: How to address specific shinyBS buttons across several tabs? I have started writing a shiny app.
What I want to achieve is loading a text file with a string in one line - like this:
$ cat testdata.txt
hello world

If the text gets loaded, the vowels are set to value 1 in the data frame and are highlighted with the shinyBS package.
What I want to achieve is to be able to change the values in the data frame by clicking the toggled buttons. The buttons can be toggled, but the changed values are not transferred to the data frame or the plot.
How can this be achieved? I hope the question is clear, if not please ask and I will try to rephrase the question and make it clearer.
Here is the code for ui.R and server.R.
ui.R
library(shiny)

shinyUI(pageWithSidebar(
  headerPanel("Test buttons"),
  sidebarPanel(
    fileInput('file1', 'Choose text file',
              accept=c('text',
                       'text/plain',
                       '.txt')),
    tags$hr()
    ),
  mainPanel(
    tabsetPanel(
      tabPanel("Home"),
      tabPanel("Loaded Text",
               br(),
               tableOutput("showOverview")),
      tabPanel("Text fields",
               br(),
               uiOutput("createButtons")),
      tabPanel("Plots",
               br(),
               plotOutput("showDistribution"))
    )
  )
))

server.R
library(shiny)
library(shinyBS)

shinyServer(function(input, output) {
  fileReadText <- reactive({
    inFile <- input$file1
    if (is.null(inFile))
      return(NULL)
    uploadReadText <- read.table(inFile$datapath, sep = "|",
                                 stringsAsFactors = FALSE)
    df <- data.frame(V1 = unlist(strsplit(uploadReadText[1,], "")))
    df$V2 <- as.integer(grepl("[aeiou]", df$V1))
    df$V2 <- ifelse(df$V1 == " ", NA, df$V2)
    names(df) <- c("letter", "value")
    df
  })

  output$showOverview <- renderTable({
    data1 <- fileReadText()
    data1[c(1:10),]
  })

  output$createButtons <- renderUI({
    data1 <- fileReadText()
    listOfButtons = list()
    for (i in 1:length(data1$letter)) {
      buttonValue <- as.logical(data1$value[i])
      buttonDisabled = FALSE
      if (is.na(buttonValue)) {
        buttonValue = 0
        buttonDisabled = TRUE
      }
      listOfButtons <- list(listOfButtons,
                            bsButton(paste("button_", i, sep = ""),
                                     data1$letter[i],
                                     type = "toggle",
                                     value = as.logical(buttonValue),
                                     disabled = buttonDisabled))
    }
    listOfButtons

  })

  output$showDistribution <- renderPlot({
    data1 <- fileReadText()
    plot(data1$value)
  })
})

A: This might not be the best solution but it works! Apart from the reactive expression that was already there I have added an additional reactive value so that the changes in that value gets reflected in the table as well as the plot. The ui.R is same as in your code. Here is the modified server.R
library(shiny)
library(shinyBS)

shinyServer(function(input, output) {
  values <- reactiveValues()

  fileReadText <- reactive({
    inFile <- input$file1
    if (is.null(inFile))
      return(NULL)
    uploadReadText <- read.table(inFile$datapath, sep = "|",
                                 stringsAsFactors = FALSE)
    df <- data.frame(V1 = unlist(strsplit(uploadReadText[1,], "")))
    df$V2 <- as.integer(grepl("[aeiou]", df$V1))
    df$V2 <- ifelse(df$V1 == " ", NA, df$V2)
    names(df) <- c("letter", "value")
    values$df <- df
    df
  })

  output$showOverview <- renderTable({
    fileReadText()
    data1 <-  values$df
    data1
  })

  makeObservers <- reactive({
    data1 <- fileReadText()
    lapply(1:(length(data1$letter)), function (x) {

      observeEvent(input[[paste0("button_", x)]], {
         values$df[x,2] <- as.integer(!values$df[x,2])
      })

    })
  })

  output$createButtons <- renderUI({
    data1 <-  fileReadText()
    listOfButtons <-list()
    for (i in 1:length(data1$letter)) {
      buttonValue <- as.logical(data1$value[i])
      buttonDisabled = FALSE
      if (is.na(buttonValue)) {
        buttonValue = 0
        buttonDisabled = TRUE
      }
      listOfButtons <- list(listOfButtons,
                            bsButton(paste("button_", i, sep = ""),
                                     data1$letter[i],
                                     type = "toggle",
                                     value = as.logical(buttonValue),
                                     disabled = buttonDisabled))
    }

    makeObservers()
    listOfButtons

  })

  output$showDistribution <- renderPlot({
    data1 <- values$df
    plot(data1$value)
  })

})

[EDIT]:
I have modified the code so that toggle refers to 1 and untoggled refers to 0. Here is the modified server code:
library(shiny)
library(shinyBS)

shinyServer(function(input, output) {
  values <- reactiveValues()

  fileReadText <- reactive({
    inFile <- input$file1
    if (is.null(inFile))
      return(NULL)
    uploadReadText <- read.table(inFile$datapath, sep = "|",
                                 stringsAsFactors = FALSE)
    df <- data.frame(V1 = unlist(strsplit(uploadReadText[1,], "")))
    df$V2 <- as.integer(grepl("[aeiou]", df$V1))
    df$V2 <- ifelse(df$V1 == " ", NA, df$V2)
    names(df) <- c("letter", "value")
    values$df <- df1
    df
  })

  output$showOverview <- renderTable({
    fileReadText()
    data1 <-  values$df
    data1
  })

  makeObservers <- reactive({
    data1 <- fileReadText()
    lapply(1:(length(data1$letter)), function (x) {

      observeEvent(input[[paste0("button_", x)]], {
    #I have modified the code here. So that the table shows the value of the button
        if(!is.na(values$df[x,2]))
        values$df[x,2] <- as.integer(input[[paste0("button_", x)]])
      })

    })
  })

  output$createButtons <- renderUI({
    data1 <-  fileReadText()
    listOfButtons <-list()
    for (i in 1:length(data1$letter)) {
      buttonValue <- as.logical(data1$value[i])
      buttonDisabled = FALSE
      if (is.na(buttonValue)) {
        buttonValue = 0
        buttonDisabled = TRUE
      }
      listOfButtons <- list(listOfButtons,
                            bsButton(paste("button_", i, sep = ""),
                                     data1$letter[i],
                                     type = "toggle",
                                     value = as.logical(buttonValue),
                                     disabled = buttonDisabled))
    }

    makeObservers()
    listOfButtons

  })

  output$showDistribution <- renderPlot({
    data1 <- values$df
    plot(data1$value)
  })

})

Hope it helps!


text:
Q: how to check whether file exists before using path in Jasper I have a jrxml which has a node as follows,
<image>
  <reportElement x="181" y="0" width="209" height="74"/>
  <imageExpression class="java.lang.String"><![CDATA["logo.jpg"]]></imageExpression>
</image>

How can I check whether physical file logo.jpg exists or not?
If doesn't exists, how to fall back to a default image "default.jpg"?

A: <variable name="LOGO" class="java.lang.String">
    <variableExpression>
        <![CDATA[(new File("logo.jpg").isFile())? "logo.jpg":"default.jpg"]]>
    </variableExpression>
    <initialValueExpression>
        <![CDATA[(new File("logo.jpg").isFile())? "logo.jpg":"default.jpg"]]>
    </initialValueExpression>
</variable>

<image>
  <reportElement x="181" y="0" width="209" height="74"/>
  <imageExpression class="java.lang.String"><![CDATA[$V{LOGO}]]></imageExpression>
</image>

Got clue from this site

A: You can use exists in the Java code, if that's what you're using to check with. Not quite sure if you're asking for another approach that involves the XML itself.
If file doesn't exist, then you would just map the default image.

A: Send your image path using parameter or field in jasper report. for example I am sending image path using field.Name of field is image imagePath. If you have a image named logo.png , path of image as string other wise set path of default image.
and write this syntax with image.
<image>
    <reportElement uuid="0db5b93f-46e4-4aaa-aac9-5a6d090d7eb6" x="127" y="23" width="206" height="78"/>
    <imageExpression><![CDATA[$F{imagePath}]]></imageExpression>
</image>

Enjoy...


text:
Q: Swift: send POST request with JSONEncoder encoded data does not work I am using the JSONEncoder that has been provided with Swift4.
I have a class called Customer that uses the Codable protocol. Inside of Customer there are four Strings.
class Customer: Codable {

   var title: String
   var firstName: String
   var lastName: String
   var email: String
}

Reading JSON with a GET Request works fine.
URLSession.shared.dataTask(with: url) { (data, response, error) in
    if error != nil {
       print(error!.localizedDescription)
    }
    guard let data = data else { return }

    do {
       let customer = try JSONDecoder().decode(Customer.self, from: data)
       DispatchQueue.main.async {
          print("\(customer.title)")
          print("\(customer.firstName)")
          print("\(customer.lastName)")
          print("\(customer.email)")
       }

    } catch let jsonError {
       print(jsonError)
    }
}.resume()

However when I start to do a POST request I am lost:
First set up the request object:
let urlString = "http://localhost:8000/customer"
guard let url = URL(string: urlString) else { return }

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
let customer = Customer()
customer.title = "Mr"
customer.firstName = "Chuck"
customer.lastName = "Norris"
customer.email = "chuck.norris@awsome.com"

let encodedData = try? JSONEncoder().encode(customer)
print(String(data: encodedData!, encoding: .utf8)!) //<- Looks as intended
// Output is {"firstName":"Chuck","lastName":"Norris","title":"MR","email":"chuck.norris@awesome.com "}

Now send it out
request.httpBody = encodedData //
URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
    if let response = response {
        print(response)
    }
    if let data = data {
        do {
            let json = try JSONSerialization.data(withJSONObject: data, options: [])
            print(json)
        }catch {
            print(error)
        }
    }
})

In return I receive the message "The given data was not valid JSON."
So, my assumption is that I simply can not just put the encoded JSON data into the http body of my request.
Browsing through some articles about URLSession and JSON I found that it seems that I need to serialize my encoded JSON:
var json: Any?
if let data = encodedData {
    json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
}

Now, I don't know how to proceed. First I do not understand why I should serialize my JSON to something that can not simply put into a httpBody.
Because JSONSerialization.jsonObject produces Any? and not Data.
Update
Now, I was able to successfully send my data to my server. I am still trying to understand what was wrong - because I did not changed anything (except for the removal of the JSONSerialization call inside the completion Handler. I will investigate further...
...And .resume had been missing. :-)


text:
Q: How to capture the newly inserted row's ID value from C#? Here's my stored procedure
ALTER PROCEDURE dbo.spInsertNewTask
@ModuleID               int,
@Task                   varchar(50),
@StartDate              date,
@PlannedEndDate         date,
@EstimatedEndDate       date,
@Status                 int,
@Comments               varchar(500),
@Started                bit
AS
INSERT INTO DTasks (ModuleID, Task, StartDate, PlannedEndDate, EstimatedEndDate, Status, Comments, Started, LastUpdated)
VALUES (@ModuleID, @Task, @StartDate, @PlannedEndDate, @EstimatedEndDate, @Status, @Comments, @Started, GETDATE())

RETURN SCOPE_IDENTITY()

When I try to capture the newly created ID, all I'm getting is always 1. How to capture the New row's ID?
newID = cmd.ExecuteNonQuery();

In fact I need this new ID for further processing.
Thanks for helping.

A: Instead of ExecuteNonQuery, which returns the number of effected rows, you should use ExecuteScalar, casting the returned object to the correct type:
newID = (int)cmd.ExecuteScalar();

For the above to work, you also need to change the SQL from returning a return value to select the value:
SELECT SCOPE_IDENTITY()

The code example on the page is pretty much what you are looking to do.

If you want to keep the return type, you will need to add a return type parameter to the command, execute as non-query as you currently do, then read the value of the return parameter, as described in Getting return value from stored procedure in C#.

A: You need to pass [ID] assuming that it is you identity column as output parameter:
In C# you need to add new parameter which is output parameter and at the end of execution to retrieve :
Initialize:
    SqlParameter param = new SqlParameter("@ID", 0);
    param.Direction = ParameterDirection.Output;
    param.DbType = DbType.Int32;

Retrieve after execution:
    int id = Convert.ToInt32(sqlcommand.Parameters["@ID"].Value.ToString());

Stored procedure:
    ALTER PROCEDURE dbo.spInsertNewTask
        @ID                     INT = NULL OUTPUT,
        @ModuleID               int,
        @Task                   varchar(50),
        @StartDate              date,
        @PlannedEndDate         date,
        @EstimatedEndDate       date,
        @Status                 int,
        @Comments               varchar(500),
        @Started                bit
    AS
    BEGIN
        INSERT INTO DTasks (ModuleID, Task, StartDate, PlannedEndDate, EstimatedEndDate, Status, Comments, Started, LastUpdated)
        VALUES (@ModuleID, @Task, @StartDate, @PlannedEndDate, @EstimatedEndDate, @Status, @Comments, @Started, GETDATE())

        SET @ID = SCOPE_IDENTITY()
    END
    GO


text:
Q: error: Not in scope: data constructor `Compare' I want to program the card game "Ramsch". i Get the following Error:
error:
    Not in scope: data constructor `Compare'
    Perhaps you meant variable `compare' (imported from Prelude)
   |
66 | Compare c1 c2
   | ^^^^^^^

instance Ord Card where
Compare c1 c2
      | color c1 == color c2 || rank c1 == Bube && rank c2 /= Bube || rank c1 /= Bube && rank c2 == Bube = compare (rank c1) (rank c2)
      | rank c1 == Bube && rank c2 == Bube = compare (color c1) (color c2)
      | otherwise = GT

Why ist "compare" wrong?

A: You are defining a function, functions start with a lowercase, so compare:
instance Ord Card where
  compare c1 c2
    | color c1 == color c2 || rank c1 == Bube && rank c2 /= Bube || rank c1 /= Bube && rank c2 == Bube = compare (rank c1) (rank c2)
    | rank c1 == Bube && rank c2 == Bube = compare (color c1) (color c2)
    | otherwise = GT

It might however make more sense to implement this as:
instance Ord Card where
  compare (Card { rank=Bube, color=c1 }) (Card { rank=Bube, color=c2 }) = compare c1 c2
  compare c1 c2 | color c1 == color c2 = compare (rank c1) (rank c2)
                | otherwise = GT


text:
Q: Generic method for last record of core data base I've made a generic method which return last record from the core data base but in the return statement : return _lastItem as! [T] says that Thread X: signal SIGABRT. How can i fix this?
func lastRecord<T: NSManagedObject>(_ type : T.Type, sort: NSManagedObject? = nil) -> [T] {
    let _context = DataBaseController.persistentContainer.viewContext
    let _request = T.fetchRequest()
    _request.fetchLimit = 1

    do {
        let _result = try _context.fetch(_request)
        if !_result.isEmpty {
            let _lastItem = _result[0]
            return _lastItem as! [T]
        } else {
             return _result as! [T]
        }
    } catch {
        print("Error : \(error)")
        return []
    }
}

Thanks in advance!!

A: As mentioned in the comments _result[0] is a single object (T) and cast to array ([T]) will crash.
Another issue is that the return type is an array, either you keep the return type
do {
   let _result = try _context.fetch(_request) as! [T]
    if !_result.isEmpty {
        return [_result[0]]
    } else {
         return _result
    }
} catch { ...

or change the return type to an optional (T?)
func lastRecord<T: NSManagedObject>(_ type : T.Type, sort: NSManagedObject? = nil) -> T? { ...

then the code is simply
do {
   let _result = try _context.fetch(_request) as! [T]
   return _result.first
} catch { ...

Side-note: The leading underscore characters of the local variables are quite unusual in Swift.


text:
Q: What is Microsoft.SqlServer.Dac.dll and Purpose? What is Microsoft.SqlServer.Dac.dll?
I am trying to see what it does in Microsoft Msdn technical documentation. Don't think Microsoft has  page for this. Just curious what this is used for? Is it only applied to deploy sql databases dacpac through Powershell?
I am researching for the actual SQL Server installation artifacts, not .Net namespace in comments.
C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin


text:
Q: Find this $a,b,c$ such that $\sqrt{9-8\sin 50^{\circ}}=a+b\sin c^{\circ}$ It is known that$$\sqrt{9-8\sin 50^{\circ}}=a+b\sin c^{\circ}$$
for exactly one set of positive integers $(a,b,c)$ where $0<c<90$
find the value
$$\dfrac{b+c}{a}$$
my idea,$ \sin 50^\circ >\sin 45^\circ >\frac{_5}{^8} $
so$\sqrt{9-8\sin 50^{\circ}}<2$,then $a=1$
then $$\dfrac{b^2}{16}(1-\cos{(2c)})+\dfrac{b}{4}\sin{c}=1-\sin{50^{0}}$$
so $b=4$
then we have $\sin{c}-\cos{(2c)}=-\sin{50^{0}}$
then my question: How can prove this $c$ must equality 10?
Thank you everyone: yesterday,when I go to bed, I have consider this:let $f(c)=\sin{c}-\cos{(2c)}$.then we have $f(10)=\sin{10}-\cos{20}=\cos{80}-\cos{20}=2\sin{\dfrac{80-20}{2}}\sin{\dfrac{80+20}{2}}=\sin{50}$, by other hand, we have $f'(c)=\cos{c}+2\sin{2c}>0,0<c<\dfrac{\pi}{2}$,so if we $f(c)=f(10)$,we must $c=10$

A: We have the following (working in degrees):
$$\cos 20 - \cos 80 = \cos(50-30) - \cos(50+30) = 2 \sin 50 \sin 30 = \sin 50$$
Thus we have that
$$1 - 2\sin^2 10 - \sin 10 = \sin 50$$
(using $\cos 20 = 1 - 2 \sin^2 10$ and $\cos 80 = \sin (90 - 80) = \sin 10$)
And so
$$9 - 8 \sin 50 = 9 - 8(1 - 2\sin^2 10 - \sin 10) = 1 + 8\sin 10 + 16\sin^2 10 = (1 + 4 \sin 10)^2$$
Thus $a=1, b=4, c=10$.

A: $$\sin c-\cos(2c)$$
$$\implies \cos(90-c)-\cos(2c)$$
$$\implies -2\sin\Bigg(\dfrac{90+c}2\Bigg) \sin \Bigg(\dfrac{90-3c}2\Bigg)=-\sin(50^{\circ})$$
$$2\sin\theta \sin\phi=\sin 50^{\circ}$$
So, one of the solution comes when one of $\sin \theta^{\circ}$ or $\sin\phi$
is equal to $1/2$ and other is $\sin 50^{\circ}$
So, $$1)\dfrac{90+c}2=50 ;\sin\Bigg(\dfrac{90-3c}2\Bigg)=1/2$$
Or $$2)\dfrac{90-3c}2=50 ; \sin\Bigg(\dfrac{90+c}2\Bigg)=1/2$$
Case $2$ does not hold true , So, from $1$st case $c=10^{\circ}$
And as the solution is unique, it's the one we need.

A: Well the most forward way I think of is using the fact that $cos(2c)=1-2sin^2(c)$. This gives you some equation like:
$2X^2+X-(1+sin(50°))=0$ where $X=sin(c)$
Once you have $sin(c)$ you can get $c$ quite easily given your condition over $c$.


text:
Q: ¿Como puedo obtener el texto de las columnas de un DataView en C#? Quiero usar la información de unas columnas para introducirla en otra columna.
Los campos me aparecen vacíos porque siempre se queda en la primera fila y quiero que vaya cambiando a la siguiente en cada vuelta del foreach, el evento ocurre cuando le doy al botón de enerar_configurable_variation que es el que me insertará esa información en otra columna
       {
           try
           {
               string configurable_variations = "";

              foreach (DataGridViewRow dgvrow in dataGridView2.Rows)
               {
                   MessageBox.Show(dataGridView2.CurrentRow.Cells["temperatura_color"].Value.ToString(), "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                   configurable_variations += "sku=" + dgvrow.Cells["sku"].Value.ToString(); //sku

                   if (!String.IsNullOrWhiteSpace(dataGridView2.CurrentRow.Cells["conector"].Value.ToString()))
                   {
                       configurable_variations += ",conector=" + dgvrow.Cells["conector"].Value.ToString(); //P1
                   }

                   if (!String.IsNullOrWhiteSpace(dataGridView2.CurrentRow.Cells["temperatura_color"].Value.ToString()))
                   {
                       configurable_variations += ",temperatura_color=" + dgvrow.Cells["temperatura_color"].Value.ToString(); //temperatura_color
                   }

                   if (!String.IsNullOrWhiteSpace(dataGridView2.CurrentRow.Cells["angulo"].Value.ToString()))
                   {
                       configurable_variations += ",angulo=" + dgvrow.Cells["angulo"].Value.ToString(); //angulo
                   }

                   if (!String.IsNullOrWhiteSpace(dataGridView2.CurrentRow.Cells["acabado"].Value.ToString()))
                   {
                       configurable_variations += ",acabado=" + dgvrow.Cells["acabado"].Value.ToString(); //acabado
                   }

                   dgvrow.DefaultCellStyle.BackColor = Color.Khaki;
                   configurable_variations += "|";

                   if (dataGridView2.CurrentRow.Cells["product_type"].Value.ToString() == "configurable")
                   {
                       dataGridView2.CurrentRow.Cells["configurable_variations"].Value = configurable_variations;
                   }
               }

               configurable_variations = configurable_variations.Remove(configurable_variations.Length - 1, 1);
               richTextBox1.Text = configurable_variations;
           }

         catch (Exception ex)
           {
               MessageBox.Show(ex.Message);
               MessageBox.Show("Producto no encontrado", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
           }

       }```

[![introducir la descripción de la imagen aquí][1]][1]

 [1]: https://i.stack.imgur.com/YzS0y.png

A: Si quieres obtener la información de una columna en un Datagridview debes usar un foreach El código seria así:
string[] informacion = new string[Datagridview.Rows.Count];
int r = 0;
  foreach (DataGridViewRow row in Datagridview.Rows)
  {
    RUTAS[r] = row.Cells[0].Value != null ?
    row.Cells[0].Value.ToString() : string.Empty;
    r++;
}

Para introducir la información en otra columna solo usa un for usando el tamaño de tu Datagridview y Ncolumna sera la columna que se editara en la programacion se empieza usando el 0 siendo por ejemplo el 2 la columna 3 el 5 en columna 6, ten encuenta eso. El codigo seria así:
int N_Filas = Convert.ToInt32(Datagridview.RowCount.ToString()) - 1;
int NColumna = 2;
for(int i = 0 ; i< N_Filas ; i++)
{
string data = informacion[i]
Datagridview[NColumna, i].Value = ""+data;
}


text:
Q: Picasso loads pictures to the wrong imageview in a list adapter I'm loading an image from a server to a list view item using picasso like this:
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View participantView;
    if(convertView == null) {
        participantView = inflater.inflate(R.layout.participant_item, parent, false);
    } else {
        participantView = convertView;
    }

    TextView textView = (TextView) participantView.findViewById(R.id.participantName);
    textView.setText(getItem(position).getName());
    ImageView imageView = (ImageView) participantView.findViewById(R.id.participantImage);
    String profilePic = getItem(position).getProfilePic();

    if(!profilePic.equals("None")) {
        Log.d("tom.debug", "creating picture for user: " + getItem(position).getName());
        Picasso.with(this.context)
            .load(urlToProfilePics + profilePic)
            .placeholder(R.drawable.sample_0)
            .resize(52, 52)
            .into(imageView);
    } else {
        //load the place holder into the image view
        Picasso.with(this.context).load(R.drawable.sample_0);
    }

    if(!getItem(position).isHere()) {
        imageView.setColorFilter(Color.DKGRAY, PorterDuff.Mode.MULTIPLY);
    }

    return participantView;
}

The debug log under the if statement only fires for users that really have a profile picture. (Users that don't have will get a value of None).
However, some of the other list view items (that don't have a profile pic) also get the picture loaded.
Another useful fact (I think): The items that get the bug changes when scrolling up and down the list.
I'm not sure what I'm missing here.

A: Make sure you call the cancelRequest everytime you are about to use Picasso on a getView() from the Adapter..
// 1st: reset the imageView
Picasso.with(this.context).cancelRequest(holder.imageView);

// 2nd start a new load for the imageView
Picasso.with(this.context).load(...).into(holder.imageView);

The reason is that the view you are reusing from the convertView parameter belongs to a previous row that was possibly already being loaded by Picasso for another picture.
This is only really necessary when using the convertView, if you have just inflated a new layout, it won't be needed..but you can call always to make your code easier.

A: Please refer the following codes.First is my grid_row.xml file. It is grid items layout file

<ProgressBar
    android:layout_height="70dp"
    android:layout_width="70dp"
    android:id="@+id/myprogress"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/title"       />

<View
    android:layout_width="2dp"
    android:layout_height="2dp"/>

<ImageView
    android:layout_height="165dp"
    android:id="@+id/imageView1"
    android:layout_width="125dp"
    android:scaleType="fitXY"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"/>

<View
    android:layout_width="2dp"
    android:layout_height="2dp"/>

<TextView
    android:text="TextView"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_below="@+id/imageView1"
    android:textStyle="bold"
    android:layout_marginTop="2dp"
    android:layout_centerHorizontal="true"
    android:textSize="20sp"
    android:ellipsize="marquee">
</TextView>

<View
    android:layout_width="2dp"
    android:layout_height="2dp"/>

<TextView
    android:text="TextView"
    android:layout_height="wrap_content"
    android:id="@+id/subTitle"
    android:layout_width="wrap_content"
    android:layout_below="@+id/title"
    android:layout_marginTop="2dp"
    android:layout_centerHorizontal="true"
    android:textSize="18sp"
    android:ellipsize="marquee">
</TextView>

 </RelativeLayout>

Then Please go ahead with the adapter class for reference.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
 import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import    com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by mpatil on 28/05/15.
 */
public class GridViewAdapter extends BaseAdapter
{
private ArrayList<String> listTitle;
private ArrayList<String> listSubTitle;
private ArrayList<String> imgp;

private Context activity;
ViewHolder view;
Configuration_Parameter m_config=Configuration_Parameter.getInstance();

public GridViewAdapter(Context activity,ArrayList<String> listTitle, ArrayList<String> subTitle,ArrayList<String> img)
{
    super();
    this.listTitle = listTitle;
    this.imgp = img;
    this.listSubTitle=subTitle;
    this.activity = activity;

}

@Override
public int getCount()
{
    // TODO Auto-generated method stub
    return listTitle.size();
}

@Override
public String getItem(int position)
{
    // TODO Auto-generated method stub
    return (String) (String) view.imgViewFlag.getTag();
}

@Override
public long getItemId(int position)
{
    // TODO Auto-generated method stub
    return 0;
}

public static class ViewHolder
{
    public ImageView imgViewFlag;
    public TextView txtViewTitle;
    public TextView txtViewSubTitle;
    public ProgressBar pg;

    public ViewHolder(View v)
    {

    }
    public ViewHolder()
    {
    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    // TODO Auto-generated method stub
    View participentView=convertView;

    if(participentView == null || participentView.getTag() == null)
    {
        LayoutInflater inflater = null;
        inflater=(LayoutInflater) parent.getContext().getSystemService(activity.LAYOUT_INFLATER_SERVICE);
        view = new ViewHolder();
        participentView = inflater.inflate(R.layout.grid_layout, null);
        view.txtViewTitle = (TextView) participentView.findViewById(R.id.title);
        view.txtViewSubTitle = (TextView) participentView.findViewById(R.id.subTitle);
        view.pg=(ProgressBar)participentView.findViewById(R.id.myprogress);
        view.imgViewFlag = (ImageView) participentView.findViewById(R.id.imageView1);

        participentView.setTag(view);
    }
    else
    {
        view = (ViewHolder) participentView.getTag();
    }

        //download and display image from url

    view.txtViewTitle.setText(listTitle.get(position));
    view.txtViewSubTitle.setText(listSubTitle.get(position) + " subitem");
    ImageLoader imageLoader = null;
    imageLoader= ImageLoader.getInstance();

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.drawable.paceholder) // resource or drawable
            .showImageOnFail(R.drawable.error_page_logo) // resource or drawable
            .resetViewBeforeLoading(false)  // default
            .delayBeforeLoading(1000)
            .cacheInMemory(true) // default
            .cacheOnDisk(true) // default
        .build();

    m_config.imageLoader.displayImage(imgp.get(position), view.imgViewFlag,options,new SimpleImageLoadingListener()
    {
        @Override
        public void onLoadingStarted(String imageUri, View v)
        {
            Log.i("Inside onLoadingStarted " + position,"Yes");
            view.imgViewFlag.setVisibility(View.INVISIBLE);
            view.pg.setVisibility(View.VISIBLE);
            view.imgViewFlag.setVisibility(View.INVISIBLE);
        }
        @Override
        public void onLoadingFailed(String imageUri, View v, FailReason failReason)
        {
            Log.i("Inside onLoadingFailed " + position,"Yes");
            view.pg.setVisibility(View.GONE);

        }
        @Override
         public void onLoadingComplete(String imageUri, View v, Bitmap    loadedImage)
        {
            Log.i("Ins onLoadingComplete " + position, "Yes");
            view.pg.setVisibility(View.GONE);
            view.imgViewFlag.setVisibility(View.VISIBLE);
            view.imgViewFlag.invalidate();
        }

    });

    return participentView;
 }

 }

I am sure that this will help definitely. Thanks NOSTRA for such a great library. Thumbs Up...!!! Happy Coding... :)

A: In your getView() method change your Picasso code like this:
        try {
                Picasso.with(mActivity).
                        cancelRequest(holder.mImgCity);
                Picasso.with(mActivity).
                        load(getItem(position).getBackgroundImg()).
                        error(R.drawable.image_1).
                        into(holder.mImgCity);
            }
            catch (IllegalArgumentException e)
            {
                e.printStackTrace();
                holder.mImgCity.setImageResource(R.drawable.image_1); //<-- Important line
            }

Updated
Use Viewholder concept in your getView() method. You will get your everything done with this only.

A: I think I've been into the same situation. I suggest to use ViewHolder pattern for your adapter.
It will be something like this.
public View getView(int position, View convertView, ViewGroup parent) {

    final ViewHolder holder;
    View participantView = convertView;
    if (participantView == null || participantView.getTag() == null) {
        LayoutInflater inflater = (LayoutInflater) mContext
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // don't forget to inflate the same layout
        participantView = inflater.inflate(R.layout.participant_item, null);
        holder = getHolder(participantView);
        assert participantView != null;
        participantView.setTag(holder);
    } else {
        holder = (ViewHolder) participantView.getTag();
    }

    holder.textView.setText(getItem(position).getName());
    String profilePic = getItem(position).getProfilePic();

    if(!profilePic.equals("None")) {
        Log.d("tom.debug", "creating picture for user: " + getItem(position).getName());
        Picasso.with(this.context)
        .load(urlToProfilePics + profilePic)
        .placeholder(R.drawable.sample_0)
        .resize(52, 52)
        .into(holder.imageView);
    } else {
        //load the place holder into the image view
        Picasso.with(this.context).load(R.drawable.sample_0);
    }

    if(!getItem(position).isHere()) {
        holder.imageView.setColorFilter(Color.DKGRAY, PorterDuff.Mode.MULTIPLY);
    }

    resetViews(participantView);

    return participantView;
}

void resetViews(View v) {
    ViewHolder mHolder = new ViewHolder(v);
    mHolder.textView.invalidate();
    mHolder.imageView.invalidate();
}

static class ViewHolder {
  TextView textView;
  ImageView imageView;
}