答:
Not completely your example (because I can't test), but it gives you an idea of how to pass PHP variables into your javascript function from PHP file.</p>

```<code><!DOCTYPE html>
<html>
<head></head>
<body>

<div id="progress"></div>

<script src="https://cdn.rawgit.com/kimmobrunfeldt/progressbar.js/1.0.1/dist/progressbar.js"></script>

<script>
    function drawMyCircle(state) {
        var bar = new ProgressBar.Circle('#progress', {
            color: '#57bf6d',
            // This has to be the same size as the maximum width to
            // prevent clipping
            strokeWidth: 5,
            trailWidth: 10,
            easing: 'easeInOut',
            duration: 1400,
            text: {
                autoStyleContainer: false

            },
            from: { color: '#333', width: 7 },
            to: { color: '#57bf6d', width: 10 },
            // Set default step function for all animate calls
            step: function(state, circle) {
                circle.path.setAttribute('stroke', state.color);
                circle.path.setAttribute('stroke-width', state.width);

                var value = Math.round(circle.value() * 5);
                if (value === 0) {
                    circle.setText('');
                } else {
                    circle.setText( value +' / 5');
                }

            }
        });
        bar.text.style.fontFamily = '"Montserrat", Helvetica, sans-serif';
        bar.text.style.fontSize = '2rem';

        var newvalue = 2;
        bar.animate( newvalue * 0.2);  // Number from 0.0 to 1.0

        //Alert state for testing
        alert(state);
    }
</script>

<?php

//The state which will be passed to javascript function
$state = 1

?>

<?php if(! empty($state)): ?>
    <!-- Calling javascript function if some PHP conditions are met -->
    <script>drawMyCircle(<?= $state ?>)</script>
<?php endif ?>

</body>
</html>
</code>```

Title: Insert javascript object in php function

Body:
I want to insert some a circle created with javascript in my woocommerce shortcode created in php.
So far i've saved the javascript in assets under js with the file name. So basically i want to show my circle on my wordpress website.

The PHP looks like this:

// Add Shortcode
function get_cart_count() {

    // Code
/**
 * Check if WooCommerce is active
 **/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     global $woocommerce;
         echo '';
    echo cat_cart_count( 22 ). " ud af 5 samples ";
        echo "
Total: ".$woocommerce->cart->get_cart_total();

}
}
add_shortcode( 'cart_count', 'get_cart_count' );

and the javascript for drawing the circle is:

var bar = new ProgressBar.Circle(container, {
  color: '#57bf6d',
  // This has to be the same size as the maximum width to
  // prevent clipping
  strokeWidth: 5,
  trailWidth: 10,
  easing: 'easeInOut',
  duration: 1400,
  text: {
    autoStyleContainer: false

  },
  from: { color: '#333', width: 7 },
  to: { color: '#57bf6d', width: 10 },
  // Set default step function for all animate calls
  step: function(state, circle) {
    circle.path.setAttribute('stroke', state.color);
    circle.path.setAttribute('stroke-width', state.width);

    var value = Math.round(circle.value() * 5);
    if (value === 0) {
      circle.setText('');
    } else {
      circle.setText( value +' / 5');
    }

  }
});
bar.text.style.fontFamily = '"Montserrat", Helvetica, sans-serif';
bar.text.style.fontSize = '2rem';

var newvalue = 2;
bar.animate( newvalue * 0.2);  // Number from 0.0 to 1.0

Body:
Not completely your example (because I can't test), but it gives you an idea of how to pass PHP variables into your javascript function from PHP file.

<!DOCTYPE html>
<html>
<head></head>
<body>

<div id="progress"></div>

<script src="https://cdn.rawgit.com/kimmobrunfeldt/progressbar.js/1.0.1/dist/progressbar.js"></script>

<script>
    function drawMyCircle(state) {
        var bar = new ProgressBar.Circle('#progress', {
            color: '#57bf6d',
            // This has to be the same size as the maximum width to
            // prevent clipping
            strokeWidth: 5,
            trailWidth: 10,
            easing: 'easeInOut',
            duration: 1400,
            text: {
                autoStyleContainer: false

            },
            from: { color: '#333', width: 7 },
            to: { color: '#57bf6d', width: 10 },
            // Set default step function for all animate calls
            step: function(state, circle) {
                circle.path.setAttribute('stroke', state.color);
                circle.path.setAttribute('stroke-width', state.width);

                var value = Math.round(circle.value() * 5);
                if (value === 0) {
                    circle.setText('');
                } else {
                    circle.setText( value +' / 5');
                }

            }
        });
        bar.text.style.fontFamily = '"Montserrat", Helvetica, sans-serif';
        bar.text.style.fontSize = '2rem';

        var newvalue = 2;
        bar.animate( newvalue * 0.2);  // Number from 0.0 to 1.0

        //Alert state for testing
        alert(state);
    }
</script>

<?php

//The state which will be passed to javascript function
$state = 1

?>

<?php if(! empty($state)): ?>
    <!-- Calling javascript function if some PHP conditions are met -->
    <script>drawMyCircle(<?= $state ?>)</script>
<?php endif ?>

</body>
</html>


来源: stackexchange

问:
Redirect all ASP.NET Core logging into a single NLog logger
I have an ASP.NET project that sends its logs to NLog.

However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.

I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.

How can this be accomplished?

This is the code that creates the logger:

```<code>        // create the module name
        var ProcessName = Process.GetCurrentProcess().ProcessName;
        _ModuleName = ProcessName  + " (\"" + Oracle.GuessMyName() + "\")";

        // create the logger configuration
        var Configuration = new LoggingConfiguration();

        // create the file target
        var FileTarget = new FileTarget ("file")
        {
            FileName            = @"x:\Logs\${processname}.log",
            ArchiveFileName     = @"x:\Logs\${processname}.{#}.log",
            Layout              = @"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
            ArchiveEvery        = FileArchivePeriod.Day,
            ArchiveNumbering    = ArchiveNumberingMode.Rolling,
            MaxArchiveFiles     = 7,
            ConcurrentWrites    = true
        };

        Configuration.AddTarget(FileTarget);

        // create the viewer target
        var ViewerTarget = new NLogViewerTarget ("viewer")
        {
            Layout              = @"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
            IncludeSourceInfo   = true,
            IncludeCallSite     = true,
            Address             = @"udp://127.0.0.1:9999"
        };

        Configuration.AddTarget(ViewerTarget);

        // set the rules
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));

        // set the configuration
        LogManager.Configuration = Configuration;

        // create a new logger
        _Logger = LogManager.GetLogger(_ModuleName);
</code>```

and this is also how ASP.net gets attached to nlog:

```<code>        LoggerFactory.AddNLog();
        Application.AddNLogWeb();
</code>```

Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)

so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.

the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.

答:
Alternative you can create a custom target wrapper, that fixes the Logger on LogEventInfo's, so when forwarded to the wrapped target (UDP- / File-target), then it looks like they are all come from the same logger.

Similar to what this guy is trying to do:

https://github.com/NLog/NLog/issues/2352

Again really ugly solution, and should only be used when not able to figure out, how to avoid using the logger-name in the configuration of the wanted Nlog-targets (Ex. configure file-target-filename using something else).

ContentLicense: CC BY-SA 3.0

Body:
I have an ASP.NET project that sends its logs to NLog.

However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.

I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.

How can this be accomplished?

This is the code that creates the logger:

        // create the module name
        var ProcessName = Process.GetCurrentProcess().ProcessName;
        _ModuleName = ProcessName  + " (\"" + Oracle.GuessMyName() + "\")";

        // create the logger configuration
        var Configuration = new LoggingConfiguration();

        // create the file target
        var FileTarget = new FileTarget ("file")
        {
            FileName            = @"x:\Logs\${processname}.log",
            ArchiveFileName     = @"x:\Logs\${processname}.{#}.log",
            Layout              = @"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
            ArchiveEvery        = FileArchivePeriod.Day,
            ArchiveNumbering    = ArchiveNumberingMode.Rolling,
            MaxArchiveFiles     = 7,
            ConcurrentWrites    = true
        };

        Configuration.AddTarget(FileTarget);

        // create the viewer target
        var ViewerTarget = new NLogViewerTarget ("viewer")
        {
            Layout              = @"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
            IncludeSourceInfo   = true,
            IncludeCallSite     = true,
            Address             = @"udp://127.0.0.1:9999"
        };

        Configuration.AddTarget(ViewerTarget);

        // set the rules
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));

        // set the configuration
        LogManager.Configuration = Configuration;

        // create a new logger
        _Logger = LogManager.GetLogger(_ModuleName);

and this is also how ASP.net gets attached to nlog:

        LoggerFactory.AddNLog();
        Application.AddNLogWeb();

Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)

so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.

the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.


问:
Pass str as an int array to a Python C extended function (extended using SWIG)
How can I pass a str value (containing 3000 {'0', '1'} bytes) obtained using python code as an argument to a python c extended function (extended using SWIG) which requires int * (fixed length int array) as an input argument? My code is such:

```<code>int *exposekey(int *bits) {
    int a[1000];
    for (int j=2000; j < 3000; j++) {
        a[j - 2000] = bits[j];
    }
    return a;
}
</code>```

What I've tried was to use ctypes (see below code):

```<code>import ctypes
ldpc = ctypes.cdll.LoadLibrary('./_ldpc.so')
arr = (ctypes.c_int * 3072)(<mentioned below>)
ldpc.exposekey(arr)
</code>```

with 3072 {0, 1} entered in the  position. Python returns syntax error : more than 255  arguments. This still doesn't help me to pass assigned str value instead of the initialized ctypes int array.

Other suggestion included using SWIG typemaps but how would that work for converting a str into int * ? Thanks in advance.

答:
Regarding my comment, here are some more details about returning arrays from functions: [SO]: Returning an array using C. In short, ways (each with its pros and cons) to handle this:

Make the returned variable static

Dynamically allocate it (using malloc (family) or new)

Turn it into an additional argument for the function (and delegate management to the caller)

Getting that piece of C (or C++) code to run within the Python interpreter is possible in 2 ways:

[Python.Docs]: Extending Python with C or C++ - which creates an extension (C written) Python module

That's typically done using [Python.Docs]: Python/C API Reference Manual. Since the boiler plate code is quite large, there are 3rd-party tools (wrappers) which make things easier (offering a simpler interface for generating the module):

[SWIG]: SWIG Users Manual

[ReadTheDocs.Cython]: Welcome to Cython’s Documentation

[ReadTheDocs.PyBind11]: Seamless operability between C++11 and Python (C++)

The other way around, leaving the code in a standard .dll (.so) which can be accessed via [Python.Docs]: ctypes - A foreign function library for Python

Since they both are doing the same thing, mixing them together makes no sense. So, pick the one that best fits your needs (I want to mention that running your code didn't raise the error you got).

I prepared examples for the methods. They work using Python 3.

1. SWIG

swig_demo.h:

#define OUT_BUF_SIZE 1000

char* exposekey(const char *bIn);
```
</li>
<li><p><em>swig_demo.c</em>:</p>
<pre class="lang-c prettyprint-override"><code>#include <malloc.h>
#include <stdio.h>
#include "swig_demo.h"

char* exposekey(const char *bIn)
{
    char *ret = (char*)malloc(sizeof(char) * 20000000);
    if (ret == NULL) {
        return NULL;
    }
    printf("Message from C code...\n");
    for (int j = 0; j < OUT_BUF_SIZE; ++j) {
        ret[j] = bIn[j + 2000];
    }
    return ret;
}
</code>```

swig_demo.i:

%module swig_demo
%{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
#include "swig_demo.h"
%}

%newobject exposekey;
%include "swig_demo.h"
```
</li>
<li><p><em>test_mod.py</em> (shared by <strong>all methods that create an extension module</strong>):</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python

import sys

import data

try:
    from _capi_demo import exposekey as capi_exposekey
except:
    capi_exposekey = None

try:
    from swig_demo import exposekey as swig_exposekey
except:
    swig_exposekey = None

try:
    from _cython_demo import exposekey as cython_exposekey
except:
    cython_exposekey = None

def main(*argv):
    eks = (
        capi_exposekey,
        swig_exposekey,
        cython_exposekey,
    )
    buf = data.gen_buf()
    for ek in eks:
        if ek is None:
            continue
        print("Running function: {:s} from {:s}".format(ek.__name__, ek.__module__))
        out = ek(buf)
        print("C function returned ({:d}): {:}".format(len(out), out))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)
</code>```

data.py (shared by all methods):

def gen_buf(pad=2000, length=1000):
    _buf = b"010011000110101110101110101010010111011101101010101"
    d, m = divmod(length, len(_buf))
    return b"\x00" * pad + _buf * d + _buf[:m]
```
</li>
<li><p><em>Makefile.mak</em> (same):</p>
<pre class="lang-make prettyprint-override"><code>!include <NtWin32.mak>

.PHONY: capi swig cython ctypes

PYTHON_DIR=c:\Install\pc064\Python\Python\03.10
PYTHON_DIR_INC=$(PYTHON_DIR)\include
PYTHON_DIR_LIB=$(PYTHON_DIR)\libs

RM=del /f /q

SRC_DIR=src
CAPI_DEMO=capi_demo
SWIG_DEMO=swig_demo
CYTHON_DEMO=cython_demo
CTYPES_DEMO=ctypes_demo
SWIG_DEMO_WRAP=$(SWIG_DEMO)_wrap
CYTHON_DEMO_SRC=$(CYTHON_DEMO).c

SWIG_DEMO_SRC=$(SRC_DIR)\$(SWIG_DEMO).i
SWIG_DEMO_WRAP_SRC=$(SWIG_DEMO_WRAP).c

CYTHON_DEMO_PYX=$(SRC_DIR)\$(CYTHON_DEMO).pyx
CYTHON_DEMO_SRC=$(CYTHON_DEMO).c

CAPI_DEMO_OBJ=$(CAPI_DEMO).obj

SWIG_DEMO_OBJ=$(SWIG_DEMO).obj
SWIG_DEMO_WRAP_OBJ=$(SWIG_DEMO_WRAP).obj

CAPI_OBJS=$(CAPI_DEMO_OBJ) $(SWIG_DEMO_OBJ)

SWIG_OBJS=$(SWIG_DEMO_OBJ) $(SWIG_DEMO_WRAP_OBJ)

CYTHON_DEMO_OBJ=$(CYTHON_DEMO).obj

CYTHON_OBJS=$(CYTHON_DEMO_OBJ) $(SWIG_DEMO_OBJ)

CTYPES_DEMO_OBJ=$(CTYPES_DEMO).obj

CAPI_TARGET=_$(CAPI_DEMO).pyd
SWIG_TARGET=_$(SWIG_DEMO).pyd
CTYHON_TARGET=_$(CYTHON_DEMO).pyd
CTYPES_TARGET=$(CTYPES_DEMO).dll

#cflags=$(cflags) /UDEBUG /U_DEBUG /DNDEBUG

all:

clean:
    -@$(RM) *.dll *.pyd *.lib *.exp *.pdb *.obj $(SWIG_DEMO).py $(SWIG_DEMO_WRAP_SRC) $(CYTHON_DEMO_SRC)

.c.obj:
    $(cc) $(cdebug) $(cflags) $(cvarsdll) /I"$(SRC_DIR)" /I"$(PYTHON_DIR_INC)" /c /Fo$@ $<

{$(SRC_DIR)}.c.obj:
    $(cc) $(cdebug) $(cflags) $(cvarsdll) /I"$(PYTHON_DIR_INC)" /c /Fo$@ $<

$(SWIG_DEMO_WRAP_SRC): $(SWIG_DEMO_SRC)
    swig -python -py3 -o $@ $?

$(CYTHON_DEMO_SRC): $(CYTHON_DEMO_PYX)
    cython.exe -3 --module-name _$(CYTHON_DEMO) -o $(CYTHON_DEMO_SRC) $?

$(CAPI_TARGET): $(CAPI_OBJS)
    $(link) $(ldebug) $(dlllflags) /LIBPATH:"$(PYTHON_DIR_LIB)" $(conlibsdll) /OUT:$@ $?

$(SWIG_TARGET): $(SWIG_OBJS)
    $(link) $(ldebug) $(dlllflags) /LIBPATH:"$(PYTHON_DIR_LIB)" $(conlibsdll) /OUT:$@ $?

$(CTYHON_TARGET): $(CYTHON_OBJS)
    $(link) $(ldebug) $(dlllflags) /LIBPATH:"$(PYTHON_DIR_LIB)" $(conlibsdll) /OUT:$@ $?

$(CTYPES_TARGET): $(CTYPES_DEMO_OBJ)
    $(link) $(ldebug) $(dlllflags) $(conlibsdll) /OUT:$@ $?

capi: $(CAPI_TARGET)
swig: $(SWIG_TARGET)
cython: $(CTYHON_TARGET)
ctypes: $(CTYPES_TARGET)
</code>```

Notes:

Based on comments, I changed the types in the function from int* to char*, because it's 4 times more compact (although it's still ~700% inefficient since 7 bits of each char are ignored versus only one of them being used; that can be fixed, but requires bitwise processing)

I also modified the index range (without changing functionality), because it makes more sense to work with low index values and add something to them in one place, instead of a high index values and subtract (the same) something in another place

printf it's just dummy, to show that the C code gets executed

When dealing with such arrays, it's recommended to pass their dimensions as well, to avoid out of bounds errors. Also, error handling is an important aspect

I'm allocating the array and return it (the 2nd option from the beginning)

The .i file is a standard SWIG interface file

Defines the module, and its exports (via %include)

One thing that is worth mentioning is the %newobject directive that deallocates the pointer returned by exposekey to avoid memory leaks

The .h file just contains the function declaration, in order to be included by the .i file (it's not mandatory, but things are more elegant this way)

In Python code (data.py), I generate an input buffer 3000 (padded with 2000 NUL bytes at the beginning) bytes long and the output is 1000 (hardcoded values based on your example didn't make them configurable, to keep the code simple)

Check [SO]: Visual Studio NMake build fails with: fatal error U1052: file 'win32.mak' not found (@CristiFati's answer) for details regarding Win builds

Output (on Win. I'll be reusing the console):

```<code>[cfati@CFATI-5510-0:e:\Work\Dev\StackExchange\StackOverflow\q047276327]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> "c:\Install\pc032\Microsoft\VisualStudioCommunity\2019\VC\Auxiliary\Build\vcvarsall.bat" x64 > nul

[prompt]> set _INCLUDE=%INCLUDE%

[prompt]> set INCLUDE=%_INCLUDE%;e:\Work\Dev\GitHub\CristiFati\MSSDKFiles\src\Include

[prompt]> set _PATH=%PATH%

[prompt]> set PATH=%_PATH%;e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts;f:\Install\pc032\SWIG\SWIGWin\4.0.1

[prompt]>
[prompt]> tree /a /f
Folder PATH listing for volume SSD0-WORK
Volume serial number is AE9E-72AC
E:.
|   data.py
|   Makefile.mak
|   test_ctypes.py
|   test_mod.py
|
\---src
        capi_demo.c
        ctypes_demo.c
        cython_demo.pyx
        swig_demo.c
        swig_demo.h
        swig_demo.i

[prompt]>
[prompt]> nmake /f Makefile.mak NODEBUG=1 clean swig

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Could Not Find e:\Work\Dev\StackExchange\StackOverflow\q047276327\*.dll
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo.obj src\swig_demo.c
swig_demo.c
        swig -python -py3 -o swig_demo_wrap.c src\swig_demo.i
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"src" /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo_wrap.obj swig_demo_wrap.c
swig_demo_wrap.c
c:\Install\pc064\Python\Python\03.10\include\cpython/pytime.h(120): warning C4115: 'timeval': named type definition in parentheses
swig_demo_wrap.c(1437): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(1566): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(1578): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(1586): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(2361): warning C4100: 'clientdata': unreferenced formal parameter
swig_demo_wrap.c(2537): warning C4100: 'argnum': unreferenced formal parameter
swig_demo_wrap.c(2837): warning C4100: 'self': unreferenced formal parameter
swig_demo_wrap.c(3157): warning C4100: 'v': unreferenced formal parameter
swig_demo_wrap.c(3448): warning C4100: 'self': unreferenced formal parameter
swig_demo_wrap.c(3467): warning C4100: 'self': unreferenced formal parameter
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll /LIBPATH:"c:\Install\pc064\Python\Python\03.10\libs" kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:_swig_demo.pyd swig_demo.obj swig_demo_wrap.obj
   Creating library _swig_demo.lib and object _swig_demo.exp

[prompt]>
[prompt]> dir /b
data.py
Makefile.mak
src
swig_demo.obj
swig_demo.py
swig_demo_wrap.c
swig_demo_wrap.obj
test_ctypes.py
test_mod.py
_swig_demo.exp
_swig_demo.lib
_swig_demo.pyd

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_mod.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Running function: exposekey from swig_demo
Message from C code...
C function returned (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'

Done.
</code>```

2. Cython

cython_demo.pyx:

from libc.stdlib cimport free

cdef extern from "swig_demo.h":
    char* _exposekey "exposekey"(const char *bIn)

def exposekey(bIn):
    cdef char *b = _exposekey(bIn)
    ret = bytes(b)
    free(b)
    return ret
```
</li>
</ul>
<p><strong>Notes</strong>:</p>
<ul>
<li><p>I added this part as a personal exercise</p>
</li>
<li><p>Requires <em>swig_demo.h</em> and <em>swig_demo.c</em> (the actual function)</p>
</li>
</ul>
<p><strong>Output</strong>:</p>
<blockquote>
```[prompt]> nmake /f Makefile.mak NODEBUG=1 clean cython

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        cython.exe -3 --module-name _cython_demo src\cython_demo.pyx
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Focython_demo.obj src\cython_demo.c
cython_demo.c
c:\Install\pc064\Python\Python\03.10\include\cpython/pytime.h(120): warning C4115: 'timeval': named type definition in parentheses
src\cython_demo.c(1264): warning C4100: '__pyx_self': unreferenced formal parameter
src\cython_demo.c(1564): warning C4100: 'def': unreferenced formal parameter
src\cython_demo.c(2289): warning C4127: conditional expression is constant

:: ------- @TODO - cfati: Truncated output (same warning) -------

src\cython_demo.c(3116): warning C4127: conditional expression is constant
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo.obj src\swig_demo.c
swig_demo.c
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll /LIBPATH:"c:\Install\pc064\Python\Python\03.10\libs" kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:_cython_demo.pyd cython_demo.obj swig_demo.obj
   Creating library _cython_demo.lib and object _cython_demo.exp

[prompt]>
[prompt]> dir /b
cython_demo.c
cython_demo.obj
data.py
Makefile.mak
src
swig_demo.obj
test_ctypes.py
test_mod.py
_cython_demo.exp
_cython_demo.lib
_cython_demo.pyd
__pycache__

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_mod.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Running function: exposekey from _cython_demo
Message from C code...
C function returned (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'

Done.
```
</blockquote>
<br>
<h4>3. Plain <em>Python C API</em></h4>
<ul>
<li><p><em>capi_demo.c</em>:</p>
<pre class="lang-c prettyprint-override"><code>#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "swig_demo.h"

#define MOD_NAME "_capi_demo"

static PyObject* PyExposekey(PyObject *self, PyObject *args)
{
    PyObject *bitsInArg = NULL, *ret = NULL;
    char *bitsOut = NULL;
    if (!PyArg_ParseTuple(args, "S", &bitsInArg))
        return NULL;
    bitsOut = exposekey(PyBytes_AsString(bitsInArg));
    ret = PyBytes_FromStringAndSize(bitsOut, OUT_BUF_SIZE);
    free(bitsOut);
    return ret;
}

static PyMethodDef moduleMethods[] = {
    {"exposekey", (PyCFunction)PyExposekey, METH_VARARGS, NULL},
    {NULL, NULL, 0, NULL},  // Sentinel
};

static struct PyModuleDef moduleDef = {
    PyModuleDef_HEAD_INIT, MOD_NAME, NULL, -1, moduleMethods
};

PyMODINIT_FUNC PyInit__capi_demo(void)
{
    return PyModule_Create(&moduleDef);
}
</code>```

Notes:

Also a personal exercise

This is what SWIG / Cython do, but "manually"

Error handling may be improved

Also requires the actual function

Output:

```<code>[prompt]> nmake /f Makefile.mak NODEBUG=1 clean capi

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Focapi_demo.obj src\capi_demo.c
capi_demo.c
c:\Install\pc064\Python\Python\03.10\include\cpython/pytime.h(120): warning C4115: 'timeval': named type definition in parentheses
src\capi_demo.c(8): warning C4100: 'self': unreferenced formal parameter
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo.obj src\swig_demo.c
swig_demo.c
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll /LIBPATH:"c:\Install\pc064\Python\Python\03.10\libs" kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:_capi_demo.pyd capi_demo.obj swig_demo.obj
   Creating library _capi_demo.lib and object _capi_demo.exp

[prompt]>
[prompt]> dir /b
capi_demo.obj
data.py
Makefile.mak
src
swig_demo.obj
test_ctypes.py
test_mod.py
_capi_demo.exp
_capi_demo.lib
_capi_demo.pyd
__pycache__

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_mod.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Running function: exposekey from _capi_demo
Message from C code...
C function returned (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'

Done.
</code>```

4. CTypes

ctypes_demo.c:

#include <stdio.h>

#if defined(_WIN32)
#  define CTYPES_DEMO_EXPORT_API __declspec(dllexport)
#else
#  define CTYPES_DEMO_EXPORT_API
#endif

#define OUT_BUF_SIZE 1000

int CTYPES_DEMO_EXPORT_API exposekey(const char *bIn, char *bOut)
{
    int ret = 0;
    printf("Message from C code...\n");
    for (int j = 0; j < OUT_BUF_SIZE; ++j) {
        bOut[j] = bIn[j + 2000];
        ++ret;
    }
    return ret;
}
```
</li>
<li><p><em>test_ctypes.py</em>:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python

import ctypes as cts
import sys

from data import gen_buf

OUT_BUF_SIZE = 1000
DLL_NAME = "./ctypes_demo.{:s}".format("dll" if sys.platform[:3].lower() == "win" else "so")

def main(*argv):
    dll = cts.CDLL(DLL_NAME)
    exposekey = dll.exposekey
    exposekey.argtypes = (cts.c_char_p, cts.c_char_p)
    exposekey.restype = cts.c_int

    bin = cts.create_string_buffer(gen_buf())
    bout = cts.create_string_buffer(OUT_BUF_SIZE)
    print("Before ({:d}): {:} ... {:}".format(len(bout), bout.raw[:100], bout.raw[-100:]))
    ret = exposekey(bin, bout)
    print("After ({:d}): {:}".format(len(bout), bout.raw))
    print("Return code: {:d}".format(ret))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)
</code>```

Notes:

This is what you started with

It's one of the ways of doing things using CTypes

I took a and turned into the 2nd argument (bOut). I think this is best because it's caller responsibility to allocate and deallocate the array (the 3rd option from the beginning). The alternative would be to export another function that deallocates whatever exposekey returns

Return value is the number of bits set (obviously, 1000 in this case) but it's just an example

Check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) for a common pitfall when working with CTypes (calling functions)

Output:

```<code>[prompt]> nmake /f Makefile.mak NODEBUG=1 clean ctypes

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foctypes_demo.obj src\ctypes_demo.c
ctypes_demo.c
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:ctypes_demo.dll ctypes_demo.obj
   Creating library ctypes_demo.lib and object ctypes_demo.exp

[prompt]>
[prompt]> dir /b
ctypes_demo.dll
ctypes_demo.exp
ctypes_demo.lib
ctypes_demo.obj
data.py
Makefile.mak
src
test_ctypes.py
test_mod.py
__pycache__

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_ctypes.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Before (1000): b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ... b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Message from C code...
After (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'
Return code: 1000

Done.
</code>```

Body:
How can I pass a str value (containing 3000 {'0', '1'} bytes) obtained using python code as an argument to a python c extended function (extended using SWIG) which requires int * (fixed length int array) as an input argument? My code is such:

int *exposekey(int *bits) {
    int a[1000];
    for (int j=2000; j < 3000; j++) {
        a[j - 2000] = bits[j];
    }
    return a;
}

What I've tried was to use ctypes (see below code):

import ctypes
ldpc = ctypes.cdll.LoadLibrary('./_ldpc.so')
arr = (ctypes.c_int * 3072)(<mentioned below>)
ldpc.exposekey(arr)

with 3072 {0, 1} entered in the  position. Python returns syntax error : more than 255  arguments. This still doesn't help me to pass assigned str value instead of the initialized ctypes int array.

Other suggestion included using SWIG typemaps but how would that work for converting a str into int * ? Thanks in advance.

Body:
Regarding my comment, here are some more details about returning arrays from functions: [SO]: Returning an array using C. In short, ways (each with its pros and cons) to handle this:

Make the returned variable static

Dynamically allocate it (using malloc (family) or new)

Turn it into an additional argument for the function (and delegate management to the caller)

Getting that piece of C (or C++) code to run within the Python interpreter is possible in 2 ways:

[Python.Docs]: Extending Python with C or C++ - which creates an extension (C written) Python module

That's typically done using [Python.Docs]: Python/C API Reference Manual. Since the boiler plate code is quite large, there are 3rd-party tools (wrappers) which make things easier (offering a simpler interface for generating the module):

[SWIG]: SWIG Users Manual

[ReadTheDocs.Cython]: Welcome to Cython’s Documentation

[ReadTheDocs.PyBind11]: Seamless operability between C++11 and Python (C++)

The other way around, leaving the code in a standard .dll (.so) which can be accessed via [Python.Docs]: ctypes - A foreign function library for Python

Since they both are doing the same thing, mixing them together makes no sense. So, pick the one that best fits your needs (I want to mention that running your code didn't raise the error you got).

I prepared examples for the methods. They work using Python 3.

1. SWIG

swig_demo.h:

#define OUT_BUF_SIZE 1000

char* exposekey(const char *bIn);

swig_demo.c:

#include <malloc.h>
#include <stdio.h>
#include "swig_demo.h"

char* exposekey(const char *bIn)
{
    char *ret = (char*)malloc(sizeof(char) * 20000000);
    if (ret == NULL) {
        return NULL;
    }
    printf("Message from C code...\n");
    for (int j = 0; j < OUT_BUF_SIZE; ++j) {
        ret[j] = bIn[j + 2000];
    }
    return ret;
}

swig_demo.i:

%module swig_demo
%{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
#include "swig_demo.h"
%}

%newobject exposekey;
%include "swig_demo.h"

test_mod.py (shared by all methods that create an extension module):

#!/usr/bin/env python

import sys

import data

try:
    from _capi_demo import exposekey as capi_exposekey
except:
    capi_exposekey = None

try:
    from swig_demo import exposekey as swig_exposekey
except:
    swig_exposekey = None

try:
    from _cython_demo import exposekey as cython_exposekey
except:
    cython_exposekey = None

def main(*argv):
    eks = (
        capi_exposekey,
        swig_exposekey,
        cython_exposekey,
    )
    buf = data.gen_buf()
    for ek in eks:
        if ek is None:
            continue
        print("Running function: {:s} from {:s}".format(ek.__name__, ek.__module__))
        out = ek(buf)
        print("C function returned ({:d}): {:}".format(len(out), out))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

data.py (shared by all methods):

def gen_buf(pad=2000, length=1000):
    _buf = b"010011000110101110101110101010010111011101101010101"
    d, m = divmod(length, len(_buf))
    return b"\x00" * pad + _buf * d + _buf[:m]

Makefile.mak (same):

!include <NtWin32.mak>

.PHONY: capi swig cython ctypes

PYTHON_DIR=c:\Install\pc064\Python\Python\03.10
PYTHON_DIR_INC=$(PYTHON_DIR)\include
PYTHON_DIR_LIB=$(PYTHON_DIR)\libs

RM=del /f /q

SRC_DIR=src
CAPI_DEMO=capi_demo
SWIG_DEMO=swig_demo
CYTHON_DEMO=cython_demo
CTYPES_DEMO=ctypes_demo
SWIG_DEMO_WRAP=$(SWIG_DEMO)_wrap
CYTHON_DEMO_SRC=$(CYTHON_DEMO).c

SWIG_DEMO_SRC=$(SRC_DIR)\$(SWIG_DEMO).i
SWIG_DEMO_WRAP_SRC=$(SWIG_DEMO_WRAP).c

CYTHON_DEMO_PYX=$(SRC_DIR)\$(CYTHON_DEMO).pyx
CYTHON_DEMO_SRC=$(CYTHON_DEMO).c

CAPI_DEMO_OBJ=$(CAPI_DEMO).obj

SWIG_DEMO_OBJ=$(SWIG_DEMO).obj
SWIG_DEMO_WRAP_OBJ=$(SWIG_DEMO_WRAP).obj

CAPI_OBJS=$(CAPI_DEMO_OBJ) $(SWIG_DEMO_OBJ)

SWIG_OBJS=$(SWIG_DEMO_OBJ) $(SWIG_DEMO_WRAP_OBJ)

CYTHON_DEMO_OBJ=$(CYTHON_DEMO).obj

CYTHON_OBJS=$(CYTHON_DEMO_OBJ) $(SWIG_DEMO_OBJ)

CTYPES_DEMO_OBJ=$(CTYPES_DEMO).obj

CAPI_TARGET=_$(CAPI_DEMO).pyd
SWIG_TARGET=_$(SWIG_DEMO).pyd
CTYHON_TARGET=_$(CYTHON_DEMO).pyd
CTYPES_TARGET=$(CTYPES_DEMO).dll

#cflags=$(cflags) /UDEBUG /U_DEBUG /DNDEBUG

all:

clean:
    -@$(RM) *.dll *.pyd *.lib *.exp *.pdb *.obj $(SWIG_DEMO).py $(SWIG_DEMO_WRAP_SRC) $(CYTHON_DEMO_SRC)

.c.obj:
    $(cc) $(cdebug) $(cflags) $(cvarsdll) /I"$(SRC_DIR)" /I"$(PYTHON_DIR_INC)" /c /Fo$@ $<

{$(SRC_DIR)}.c.obj:
    $(cc) $(cdebug) $(cflags) $(cvarsdll) /I"$(PYTHON_DIR_INC)" /c /Fo$@ $<

$(SWIG_DEMO_WRAP_SRC): $(SWIG_DEMO_SRC)
    swig -python -py3 -o $@ $?

$(CYTHON_DEMO_SRC): $(CYTHON_DEMO_PYX)
    cython.exe -3 --module-name _$(CYTHON_DEMO) -o $(CYTHON_DEMO_SRC) $?

$(CAPI_TARGET): $(CAPI_OBJS)
    $(link) $(ldebug) $(dlllflags) /LIBPATH:"$(PYTHON_DIR_LIB)" $(conlibsdll) /OUT:$@ $?

$(SWIG_TARGET): $(SWIG_OBJS)
    $(link) $(ldebug) $(dlllflags) /LIBPATH:"$(PYTHON_DIR_LIB)" $(conlibsdll) /OUT:$@ $?

$(CTYHON_TARGET): $(CYTHON_OBJS)
    $(link) $(ldebug) $(dlllflags) /LIBPATH:"$(PYTHON_DIR_LIB)" $(conlibsdll) /OUT:$@ $?

$(CTYPES_TARGET): $(CTYPES_DEMO_OBJ)
    $(link) $(ldebug) $(dlllflags) $(conlibsdll) /OUT:$@ $?

capi: $(CAPI_TARGET)
swig: $(SWIG_TARGET)
cython: $(CTYHON_TARGET)
ctypes: $(CTYPES_TARGET)

Notes:

Based on comments, I changed the types in the function from int* to char*, because it's 4 times more compact (although it's still ~700% inefficient since 7 bits of each char are ignored versus only one of them being used; that can be fixed, but requires bitwise processing)

I also modified the index range (without changing functionality), because it makes more sense to work with low index values and add something to them in one place, instead of a high index values and subtract (the same) something in another place

printf it's just dummy, to show that the C code gets executed

When dealing with such arrays, it's recommended to pass their dimensions as well, to avoid out of bounds errors. Also, error handling is an important aspect

I'm allocating the array and return it (the 2nd option from the beginning)

The .i file is a standard SWIG interface file

Defines the module, and its exports (via %include)

One thing that is worth mentioning is the %newobject directive that deallocates the pointer returned by exposekey to avoid memory leaks

The .h file just contains the function declaration, in order to be included by the .i file (it's not mandatory, but things are more elegant this way)

In Python code (data.py), I generate an input buffer 3000 (padded with 2000 NUL bytes at the beginning) bytes long and the output is 1000 (hardcoded values based on your example didn't make them configurable, to keep the code simple)

Check [SO]: Visual Studio NMake build fails with: fatal error U1052: file 'win32.mak' not found (@CristiFati's answer) for details regarding Win builds

Output (on Win. I'll be reusing the console):

[cfati@CFATI-5510-0:e:\Work\Dev\StackExchange\StackOverflow\q047276327]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> "c:\Install\pc032\Microsoft\VisualStudioCommunity\2019\VC\Auxiliary\Build\vcvarsall.bat" x64 > nul

[prompt]> set _INCLUDE=%INCLUDE%

[prompt]> set INCLUDE=%_INCLUDE%;e:\Work\Dev\GitHub\CristiFati\MSSDKFiles\src\Include

[prompt]> set _PATH=%PATH%

[prompt]> set PATH=%_PATH%;e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts;f:\Install\pc032\SWIG\SWIGWin\4.0.1

[prompt]>
[prompt]> tree /a /f
Folder PATH listing for volume SSD0-WORK
Volume serial number is AE9E-72AC
E:.
|   data.py
|   Makefile.mak
|   test_ctypes.py
|   test_mod.py
|
\---src
        capi_demo.c
        ctypes_demo.c
        cython_demo.pyx
        swig_demo.c
        swig_demo.h
        swig_demo.i

[prompt]>
[prompt]> nmake /f Makefile.mak NODEBUG=1 clean swig

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Could Not Find e:\Work\Dev\StackExchange\StackOverflow\q047276327\*.dll
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo.obj src\swig_demo.c
swig_demo.c
        swig -python -py3 -o swig_demo_wrap.c src\swig_demo.i
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"src" /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo_wrap.obj swig_demo_wrap.c
swig_demo_wrap.c
c:\Install\pc064\Python\Python\03.10\include\cpython/pytime.h(120): warning C4115: 'timeval': named type definition in parentheses
swig_demo_wrap.c(1437): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(1566): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(1578): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(1586): warning C4100: 'args': unreferenced formal parameter
swig_demo_wrap.c(2361): warning C4100: 'clientdata': unreferenced formal parameter
swig_demo_wrap.c(2537): warning C4100: 'argnum': unreferenced formal parameter
swig_demo_wrap.c(2837): warning C4100: 'self': unreferenced formal parameter
swig_demo_wrap.c(3157): warning C4100: 'v': unreferenced formal parameter
swig_demo_wrap.c(3448): warning C4100: 'self': unreferenced formal parameter
swig_demo_wrap.c(3467): warning C4100: 'self': unreferenced formal parameter
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll /LIBPATH:"c:\Install\pc064\Python\Python\03.10\libs" kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:_swig_demo.pyd swig_demo.obj swig_demo_wrap.obj
   Creating library _swig_demo.lib and object _swig_demo.exp

[prompt]>
[prompt]> dir /b
data.py
Makefile.mak
src
swig_demo.obj
swig_demo.py
swig_demo_wrap.c
swig_demo_wrap.obj
test_ctypes.py
test_mod.py
_swig_demo.exp
_swig_demo.lib
_swig_demo.pyd

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_mod.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Running function: exposekey from swig_demo
Message from C code...
C function returned (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'

Done.

2. Cython

cython_demo.pyx:

from libc.stdlib cimport free

cdef extern from "swig_demo.h":
    char* _exposekey "exposekey"(const char *bIn)

def exposekey(bIn):
    cdef char *b = _exposekey(bIn)
    ret = bytes(b)
    free(b)
    return ret

Notes:

I added this part as a personal exercise

Requires swig_demo.h and swig_demo.c (the actual function)

Output:

[prompt]> nmake /f Makefile.mak NODEBUG=1 clean cython

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        cython.exe -3 --module-name _cython_demo src\cython_demo.pyx
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Focython_demo.obj src\cython_demo.c
cython_demo.c
c:\Install\pc064\Python\Python\03.10\include\cpython/pytime.h(120): warning C4115: 'timeval': named type definition in parentheses
src\cython_demo.c(1264): warning C4100: '__pyx_self': unreferenced formal parameter
src\cython_demo.c(1564): warning C4100: 'def': unreferenced formal parameter
src\cython_demo.c(2289): warning C4127: conditional expression is constant

:: ------- @TODO - cfati: Truncated output (same warning) -------

src\cython_demo.c(3116): warning C4127: conditional expression is constant
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo.obj src\swig_demo.c
swig_demo.c
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll /LIBPATH:"c:\Install\pc064\Python\Python\03.10\libs" kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:_cython_demo.pyd cython_demo.obj swig_demo.obj
   Creating library _cython_demo.lib and object _cython_demo.exp

[prompt]>
[prompt]> dir /b
cython_demo.c
cython_demo.obj
data.py
Makefile.mak
src
swig_demo.obj
test_ctypes.py
test_mod.py
_cython_demo.exp
_cython_demo.lib
_cython_demo.pyd
__pycache__

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_mod.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Running function: exposekey from _cython_demo
Message from C code...
C function returned (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'

Done.

3. Plain Python C API

capi_demo.c:

#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "swig_demo.h"

#define MOD_NAME "_capi_demo"

static PyObject* PyExposekey(PyObject *self, PyObject *args)
{
    PyObject *bitsInArg = NULL, *ret = NULL;
    char *bitsOut = NULL;
    if (!PyArg_ParseTuple(args, "S", &bitsInArg))
        return NULL;
    bitsOut = exposekey(PyBytes_AsString(bitsInArg));
    ret = PyBytes_FromStringAndSize(bitsOut, OUT_BUF_SIZE);
    free(bitsOut);
    return ret;
}

static PyMethodDef moduleMethods[] = {
    {"exposekey", (PyCFunction)PyExposekey, METH_VARARGS, NULL},
    {NULL, NULL, 0, NULL},  // Sentinel
};

static struct PyModuleDef moduleDef = {
    PyModuleDef_HEAD_INIT, MOD_NAME, NULL, -1, moduleMethods
};

PyMODINIT_FUNC PyInit__capi_demo(void)
{
    return PyModule_Create(&moduleDef);
}

Notes:

Also a personal exercise

This is what SWIG / Cython do, but "manually"

Error handling may be improved

Also requires the actual function

Output:

[prompt]> nmake /f Makefile.mak NODEBUG=1 clean capi

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Focapi_demo.obj src\capi_demo.c
capi_demo.c
c:\Install\pc064\Python\Python\03.10\include\cpython/pytime.h(120): warning C4115: 'timeval': named type definition in parentheses
src\capi_demo.c(8): warning C4100: 'self': unreferenced formal parameter
        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foswig_demo.obj src\swig_demo.c
swig_demo.c
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll /LIBPATH:"c:\Install\pc064\Python\Python\03.10\libs" kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:_capi_demo.pyd capi_demo.obj swig_demo.obj
   Creating library _capi_demo.lib and object _capi_demo.exp

[prompt]>
[prompt]> dir /b
capi_demo.obj
data.py
Makefile.mak
src
swig_demo.obj
test_ctypes.py
test_mod.py
_capi_demo.exp
_capi_demo.lib
_capi_demo.pyd
__pycache__

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_mod.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Running function: exposekey from _capi_demo
Message from C code...
C function returned (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'

Done.

4. CTypes

ctypes_demo.c:

#include <stdio.h>

#if defined(_WIN32)
#  define CTYPES_DEMO_EXPORT_API __declspec(dllexport)
#else
#  define CTYPES_DEMO_EXPORT_API
#endif

#define OUT_BUF_SIZE 1000

int CTYPES_DEMO_EXPORT_API exposekey(const char *bIn, char *bOut)
{
    int ret = 0;
    printf("Message from C code...\n");
    for (int j = 0; j < OUT_BUF_SIZE; ++j) {
        bOut[j] = bIn[j + 2000];
        ++ret;
    }
    return ret;
}

test_ctypes.py:

#!/usr/bin/env python

import ctypes as cts
import sys

from data import gen_buf

OUT_BUF_SIZE = 1000
DLL_NAME = "./ctypes_demo.{:s}".format("dll" if sys.platform[:3].lower() == "win" else "so")

def main(*argv):
    dll = cts.CDLL(DLL_NAME)
    exposekey = dll.exposekey
    exposekey.argtypes = (cts.c_char_p, cts.c_char_p)
    exposekey.restype = cts.c_int

    bin = cts.create_string_buffer(gen_buf())
    bout = cts.create_string_buffer(OUT_BUF_SIZE)
    print("Before ({:d}): {:} ... {:}".format(len(bout), bout.raw[:100], bout.raw[-100:]))
    ret = exposekey(bin, bout)
    print("After ({:d}): {:}".format(len(bout), bout.raw))
    print("Return code: {:d}".format(ret))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Notes:

This is what you started with

It's one of the ways of doing things using CTypes

I took a and turned into the 2nd argument (bOut). I think this is best because it's caller responsibility to allocate and deallocate the array (the 3rd option from the beginning). The alternative would be to export another function that deallocates whatever exposekey returns

Return value is the number of bits set (obviously, 1000 in this case) but it's just an example

Check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) for a common pitfall when working with CTypes (calling functions)

Output:

[prompt]> nmake /f Makefile.mak NODEBUG=1 clean ctypes

Microsoft (R) Program Maintenance Utility Version 14.29.30148.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        cl -Ox -DNDEBUG -c -DCRTAPI1=_cdecl -DCRTAPI2=_cdecl -nologo -GS -D_AMD64_=1 -DWIN64 -D_WIN64  -DWIN32 -D_WIN32 -W4 -D_WINNT -D_WIN32_WINNT=0x0600 -DNTDDI_VERSION=0x06000000 -D_WIN32_IE=0x0700 -DWINVER=0x0600  -D_MT -D_DLL -MD /I"c:\Install\pc064\Python\Python\03.10\include" /c /Foctypes_demo.obj src\ctypes_demo.c
ctypes_demo.c
        link /RELEASE  /INCREMENTAL:NO /NOLOGO -entry:_DllMainCRTStartup -dll kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib /OUT:ctypes_demo.dll ctypes_demo.obj
   Creating library ctypes_demo.lib and object ctypes_demo.exp

[prompt]>
[prompt]> dir /b
ctypes_demo.dll
ctypes_demo.exp
ctypes_demo.lib
ctypes_demo.obj
data.py
Makefile.mak
src
test_ctypes.py
test_mod.py
__pycache__

[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" test_ctypes.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Before (1000): b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ... b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Message from C code...
After (1000): b'0100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100101110111011010101010100110001101011101011101010100'
Return code: 1000

Done.

ContentLicense: CC BY-SA 4.0


问:
Shapefile into geojson conversion python 3
```<code>output_buffer = []
for features in range(0,layer.GetFeatureCount()):
    feat = layer.GetNextFeature()
    geom = feat.GetGeometryRef()
    result = feat.ExportToJson()
    output_buffer.append(result)
</code>```

When I convert into geojson, I get output, but only one feature is getting formatted as JSON

I got  output like this:

```<code>{"geometry": {"coordinates": [488081.726322771, 2360837.62927308], "type": "Point"}, "type": "Feature", "id": 0, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "BB_D2", "ExtendedEn": null, "SubClasses": null}}{"geometry": {"coordinates": [487523.119248441, 2361228.95273474], "type": "Point"}, "type": "Feature", "id": 1, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "Mil_D2", "ExtendedEn": null, "SubClasses": null}}..................
</code>```

I would like to get output like this:

```<code>{"geometry": {"coordinates": [488081.726322771, 2360837.62927308], "type": "Point"}, "type": "Feature", "id": 0, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "BB_D2", "ExtendedEn": null, "SubClasses": null}}**,**
{"geometry": {"coordinates": [487523.119248441, 2361228.95273474], "type": "Point"}, "type": "Feature", "id": 1, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "Mil_D2", "ExtendedEn": null, "SubClasses": null}}**,**
</code>```

答:
Please check out the following library: https://pypi.python.org/pypi/pyshp/1.1.7

```<code>import shapefile
from json import dumps

# read the shapefile
reader = shapefile.Reader("my.shp")
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
    atr = dict(zip(field_names, sr.record))
    geom = sr.shape.__geo_interface__
    buffer.append(dict(type="Feature", \
    geometry=geom, properties=atr))

    # write the GeoJSON file

geojson = open("pyshp-demo.json", "w")
geojson.write(dumps({"type": "FeatureCollection", "features": buffer}, indent=2) + "\n")
geojson.close()
</code>```

As noted in other answers, you could use geopandas:

```<code>import geopandas

shp_file = geopandas.read_file('myshpfile.shp')
shp_file.to_file('myshpfile.geojson', driver='GeoJSON')
</code>```

Body:
output_buffer = []
for features in range(0,layer.GetFeatureCount()):
    feat = layer.GetNextFeature()
    geom = feat.GetGeometryRef()
    result = feat.ExportToJson()
    output_buffer.append(result)

When I convert into geojson, I get output, but only one feature is getting formatted as JSON

I got  output like this:

{"geometry": {"coordinates": [488081.726322771, 2360837.62927308], "type": "Point"}, "type": "Feature", "id": 0, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "BB_D2", "ExtendedEn": null, "SubClasses": null}}{"geometry": {"coordinates": [487523.119248441, 2361228.95273474], "type": "Point"}, "type": "Feature", "id": 1, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "Mil_D2", "ExtendedEn": null, "SubClasses": null}}..................

I would like to get output like this:

{"geometry": {"coordinates": [488081.726322771, 2360837.62927308], "type": "Point"}, "type": "Feature", "id": 0, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "BB_D2", "ExtendedEn": null, "SubClasses": null}}**,**
{"geometry": {"coordinates": [487523.119248441, 2361228.95273474], "type": "Point"}, "type": "Feature", "id": 1, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "Mil_D2", "ExtendedEn": null, "SubClasses": null}}**,**

Body:
Please check out the following library: https://pypi.python.org/pypi/pyshp/1.1.7

import shapefile
from json import dumps

# read the shapefile
reader = shapefile.Reader("my.shp")
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
    atr = dict(zip(field_names, sr.record))
    geom = sr.shape.__geo_interface__
    buffer.append(dict(type="Feature", \
    geometry=geom, properties=atr))

    # write the GeoJSON file

geojson = open("pyshp-demo.json", "w")
geojson.write(dumps({"type": "FeatureCollection", "features": buffer}, indent=2) + "\n")
geojson.close()

As noted in other answers, you could use geopandas:

import geopandas

shp_file = geopandas.read_file('myshpfile.shp')
shp_file.to_file('myshpfile.geojson', driver='GeoJSON')


问:
Aggregate function AVG and SUM is changing my data type size column in SybaseIQ
I m reciving a error in Sybase Iq because the Aggregation funtion (AVG and SUM) is changing the size of my column, and when I insert the values of my aggregation funtion column in the destination column ,the results are so big for the destination column.

example:

```<code>            Salary
          -----------
            0,4565
            0,4555
            0,4399
             ..
             ..
</code>```

In my procedure i need to write

```<code>        SUM(salary)/AVG(salary)
</code>```

when I write it

```<code>       select  SUM(salary)/AVG(salary) as AVG_Salary
          from mytable
             group by salary
</code>```

I recive that as result

```<code>                AVG_Salary
             ----------------
            0,425000000000000000000000000
            0,455000000000000000000000000
            0,442132124300000000000000000
            1,545646464743879540386969949
              ...
              ...
</code>```

Why is that? and if a try to round it, it doesnt work either,

what can I do?

Thanks for your kinds Answers.

AS suggestion i try to do the

```<code>   cast(AVG_Salary) as decimal (12,9)  --the size of my destination column
</code>```

it doesnt work either.
I recive the error   "Data type conversion is not possible"

答: If you din’t want this, use cast(avg(...) as numeric(9,4))</p>

Body:
I m reciving a error in Sybase Iq because the Aggregation funtion (AVG and SUM) is changing the size of my column, and when I insert the values of my aggregation funtion column in the destination column ,the results are so big for the destination column.

example:

            Salary
          -----------
            0,4565
            0,4555
            0,4399
             ..
             ..

In my procedure i need to write

        SUM(salary)/AVG(salary)

when I write it

       select  SUM(salary)/AVG(salary) as AVG_Salary
          from mytable
             group by salary

I recive that as result

                AVG_Salary
             ----------------
            0,425000000000000000000000000
            0,455000000000000000000000000
            0,442132124300000000000000000
            1,545646464743879540386969949
              ...
              ...

Why is that? and if a try to round it, it doesnt work either,

what can I do?

Thanks for your kinds Answers.

AS suggestion i try to do the

   cast(AVG_Salary) as decimal (12,9)  --the size of my destination column

it doesnt work either.
I recive the error   "Data type conversion is not possible"


问:
How to get updated html after changing page element values using puppeteer?
I'm at a loss.  I'm typing into an input element on the page using this:

```<code>await page.type('#username', 'test');
</code>```

Then I'd like to retrieve the newly updated, which I'm trying using this:

```<code>let html = await page.content();
</code>```

But the username field does not include the word 'test' in it - it is empty.  If I take a screenshot, it has the word 'test' in it.  What am I missing?

答:
Typing in an <input> element updates the value property but leaves the value attribute unchanged. This is why you don't see the text in the rendered HTML.

To get the value property:

```<code>await page.type('#username', 'test');
let value = await page.$('#username').getProperty('value');
</code>```

Body:
I'm at a loss.  I'm typing into an input element on the page using this:

await page.type('#username', 'test');

Then I'd like to retrieve the newly updated, which I'm trying using this:

let html = await page.content();

But the username field does not include the word 'test' in it - it is empty.  If I take a screenshot, it has the word 'test' in it.  What am I missing?

Body:
Typing in an <input> element updates the value property but leaves the value attribute unchanged. This is why you don't see the text in the rendered HTML.

To get the value property:

await page.type('#username', 'test');
let value = await page.$('#username').getProperty('value');


问:
String to list in Python
I'm trying to split a string:

```<code>'QH QD JC KD JS'
</code>```

into a list like:

```<code>['QH', 'QD', 'JC', 'KD', 'JS']
</code>```

How would I go about doing this?

答:
Here the simples</p>

```<code>a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
</code>```

Title: String to list in Python

Body:
I'm trying to split a string:

'QH QD JC KD JS'

into a list like:

['QH', 'QD', 'JC', 'KD', 'JS']

How would I go about doing this?

Body:
Here the simples

a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


问:
Why RecyclerView items disappear with scrolling
I am using a RecyclerView in my app but when I scroll on my RecyclerView my items will disappear! I used this code for a lot of RecyclerView but this time I don't know what is happening.
there is my code for my Activity:

```<code>public class ActivityStartup extends AppCompatActivity {

  Toolbar toolbar;
  DrawerLayout drawerLayout;
  NavigationView navigationView;
  RecyclerView menuListRecycler;
  RecyclerView schedualRecycler;

  private List<ReminderModel> tempSchedualArray = new ArrayList<>();

  /**
   * ATTENTION: This was auto-generated to implement the App Indexing API.
   * See https://g.co/AppIndexing/AndroidStudio for more information.
   */
  private GoogleApiClient client;
  LinearLayoutManager mSchedualLayoutManager = new LinearLayoutManager(ActivityStartup.this);
  private FloatingActionButton mAddReminderButton;
  RecyclerView.Adapter mSchedualAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    toolbar = (Toolbar) findViewById(R.id.toolBar);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.navigationView);
    menuListRecycler = (RecyclerView) findViewById(R.id.menuList);
    schedualRecycler = (RecyclerView) findViewById(R.id.acitvityStartup_recycler_scheduals);

    //Setting Customized toolbar for application
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    LinearLayoutManager mEventsLayoutManager = new LinearLayoutManager(ActivityStartup.this);
    menuListRecycler.setLayoutManager(mEventsLayoutManager);
    RecyclerView.Adapter mEventsAdapter = new MenuAdapter(G.menuItems, ActivityStartup.this);
    menuListRecycler.setAdapter(mEventsAdapter);
    mAddReminderButton = (FloatingActionButton) findViewById(R.id.add_reminder);

    //Setting up recyclerView of events
    populateSchedualArray();

    schedualRecycler.setLayoutManager(mSchedualLayoutManager);
    mSchedualAdapter = new SchedualAdapter(populateSchedualArray(), ActivityStartup.this);
    schedualRecycler.setAdapter(mSchedualAdapter);

    // On clicking the floating action button
    mAddReminderButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(v.getContext(), ReminderAddActivity.class);
        startActivity(intent);
      }
    });

  }

  @Override
  protected void onResume() {
    super.onResume();

    mSchedualAdapter = new SchedualAdapter(populateSchedualArray(), ActivityStartup.this);
    schedualRecycler.setAdapter(mSchedualAdapter);
  }

  private ArrayList<ReminderModel> populateSchedualArray() {

    ArrayList<ReminderModel> schedualArray = new ArrayList<>();

    Database rb = new Database(ActivityStartup.this);
    tempSchedualArray = rb.getAllReminders();

    ArrayList<ReminderModel> monthOne = new ArrayList<>();
    ArrayList<ReminderModel> monthTwo = new ArrayList<>();
    ArrayList<ReminderModel> monthThree = new ArrayList<>();
    ArrayList<ReminderModel> monthFour = new ArrayList<>();
    ArrayList<ReminderModel> monthFive = new ArrayList<>();
    ArrayList<ReminderModel> monthSix = new ArrayList<>();
    ArrayList<ReminderModel> monthSeven = new ArrayList<>();
    ArrayList<ReminderModel> monthEight = new ArrayList<>();
    ArrayList<ReminderModel> monthNine = new ArrayList<>();
    ArrayList<ReminderModel> monthTen = new ArrayList<>();
    ArrayList<ReminderModel> monthEleven = new ArrayList<>();
    ArrayList<ReminderModel> monthTwelve = new ArrayList<>();

    for (ReminderModel rm : tempSchedualArray) {

      String[] split = rm.getDate().split("/");
      switch (split[1]) {
        case "1":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthOne.add(rm);
          break;
        case "2":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthTwo.add(rm);
          break;
        case "3":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthThree.add(rm);
          break;
        case "4":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthFour.add(rm);
          break;
        case "5":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthFive.add(rm);
          break;
        case "6":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthSix.add(rm);
          break;
        case "7":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthSeven.add(rm);
          break;
        case "8":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthEight.add(rm);
          break;
        case "9":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthNine.add(rm);
          break;
        case "10":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthTen.add(rm);
          break;
        case "11":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthEleven.add(rm);
          break;
        case "12":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthTwelve.add(rm);
          break;
      }

    }

    schedualArray.add(new ReminderModel(100000001, "start_spring", "", "", "", "", "", ""));
    schedualArray.addAll(monthOne);
    schedualArray.addAll(monthTwo);
    schedualArray.addAll(monthThree);
    schedualArray.add(new ReminderModel(100000004, "start_summer", "", "", "", "", "", ""));
    schedualArray.addAll(monthFour);
    schedualArray.addAll(monthFive);
    schedualArray.addAll(monthSix);
    schedualArray.add(new ReminderModel(100000007, "start_fall", "", "", "", "", "", ""));
    schedualArray.addAll(monthSeven);
    schedualArray.addAll(monthEight);
    schedualArray.addAll(monthNine);
    schedualArray.add(new ReminderModel(1000000010, "start_winter", "", "", "", "", "", ""));
    schedualArray.addAll(monthTen);
    schedualArray.addAll(monthEleven);
    schedualArray.addAll(monthTwelve);

    return schedualArray;
  }

  private String convertDateToGregorian(String year, String month, String day) {

    CalendarTool calendarTool = new CalendarTool();
    calendarTool.setIranianDate(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));

    return calendarTool.getGregorianYear() + "/" + calendarTool.getGregorianMonth() + "/" + calendarTool.getGregorianDay();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == android.R.id.home) {
      Toast.makeText(this, "دکمه خانه کلیک شد !", Toast.LENGTH_SHORT).show();
    }
    if (id == R.id.action_settings) {
      drawerLayout.openDrawer(Gravity.RIGHT);
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * ATTENTION: This was auto-generated to implement the App Indexing API.
   * See https://g.co/AppIndexing/AndroidStudio for more information.
   */
  public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
      .setName("Main Page") // TODO: Define a title for the content shown.
      // TODO: Make sure this auto-generated URL is correct.
      .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
      .build();
    return new Action.Builder(Action.TYPE_VIEW)
      .setObject(object)
      .setActionStatus(Action.STATUS_TYPE_COMPLETED)
      .build();
  }

  @Override
  public void onStart() {
    super.onStart();
  }

  @Override
  public void onStop() {
    super.onStop();
  }

}
</code>```

and this is my adapter class that i used :

```<code>public class SchedualAdapter extends RecyclerView.Adapter<SchedualAdapter.ViewHolder> {
  private ArrayList<ReminderModel> items;
  private Context mContext;

  public SchedualAdapter(ArrayList<ReminderModel> items, Context mContext) {
    this.items = items;
    this.mContext = mContext;
  }

  public static class ViewHolder extends RecyclerView.ViewHolder {

    TextView txtDateNumber;
    TextView txtDateName;
    TextView txtEventTitle;
    TextView txtMonthName;
    ImageView imgMonth;
    LinearLayout layoutTop;

    public ViewHolder(View v) {
      super(v);

      txtDateNumber = (TextView) v.findViewById(R.id.txt_dateNumber);
      txtDateName = (TextView) v.findViewById(R.id.txt_dateName);
      txtEventTitle = (TextView) v.findViewById(R.id.txt_eventTitle);
      txtMonthName = (TextView) v.findViewById(R.id.txt_monthName);
      imgMonth = (ImageView) v.findViewById(R.id.img_monthPic);
      layoutTop = (LinearLayout) v.findViewById(R.id.layoutTop);
    }
  }

  @Override
  public SchedualAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    // Create a new View
    final View v = LayoutInflater.from(mContext).inflate(R.layout.schedual_recycler_item, parent, false);
    ViewHolder vh = new ViewHolder(v);
    return vh;
  }

  @Override
  public void onBindViewHolder(final ViewHolder holder, final int position) {

    if (items.get(position).getTitle().equals("start_spring")) {

      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.spring);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else if (items.get(position).getTitle().equals("start_summer")) {
      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.summer);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else if (items.get(position).getTitle().equals("start_fall")) {
      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.fall);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else if (items.get(position).getTitle().equals("start_winter")) {
      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.winter);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else {

      holder.imgMonth.setVisibility(View.GONE);

      holder.layoutTop.setVisibility(View.VISIBLE);
      holder.txtEventTitle.setText(items.get(position).getTitle());
      holder.txtDateNumber.setText(items.get(position).getDate());

      CalendarTool c = new CalendarTool();

      if (!items.get(position).getDate().equals("")) {

        String[] split = items.get(position).getDate().split("/");
        c.setIranianDate(Integer.parseInt(split[2]), Integer.parseInt(split[1]), Integer.parseInt(split[0]));
        holder.txtDateName.setText("" + c.getDayOfWeek());
      }

    }

    setAnimation(holder.itemView, position);

  }

  private int lastPosition = -1;

  private void setAnimation(View viewToAnimate, int position) {
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {
      ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
      anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
      viewToAnimate.startAnimation(anim);
      lastPosition = position;
    }
  }

  @Override
  public int getItemCount() {
    return items.size();
  }
}
</code>```

I can't understand how my items will disappear!
I really appreciate it if you can help me.
thank you.

答:
I had the same issue (https://github.com/square/picasso/issues/845) but in github found this and worked for me. Thaks to @raj9686</p>

```<code>rv.getRecycledViewPool().setMaxRecycledViews(0, 0);
</code>```

Body:
I am using a RecyclerView in my app but when I scroll on my RecyclerView my items will disappear! I used this code for a lot of RecyclerView but this time I don't know what is happening.
there is my code for my Activity:

public class ActivityStartup extends AppCompatActivity {

  Toolbar toolbar;
  DrawerLayout drawerLayout;
  NavigationView navigationView;
  RecyclerView menuListRecycler;
  RecyclerView schedualRecycler;

  private List<ReminderModel> tempSchedualArray = new ArrayList<>();

  /**
   * ATTENTION: This was auto-generated to implement the App Indexing API.
   * See https://g.co/AppIndexing/AndroidStudio for more information.
   */
  private GoogleApiClient client;
  LinearLayoutManager mSchedualLayoutManager = new LinearLayoutManager(ActivityStartup.this);
  private FloatingActionButton mAddReminderButton;
  RecyclerView.Adapter mSchedualAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    toolbar = (Toolbar) findViewById(R.id.toolBar);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.navigationView);
    menuListRecycler = (RecyclerView) findViewById(R.id.menuList);
    schedualRecycler = (RecyclerView) findViewById(R.id.acitvityStartup_recycler_scheduals);

    //Setting Customized toolbar for application
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    LinearLayoutManager mEventsLayoutManager = new LinearLayoutManager(ActivityStartup.this);
    menuListRecycler.setLayoutManager(mEventsLayoutManager);
    RecyclerView.Adapter mEventsAdapter = new MenuAdapter(G.menuItems, ActivityStartup.this);
    menuListRecycler.setAdapter(mEventsAdapter);
    mAddReminderButton = (FloatingActionButton) findViewById(R.id.add_reminder);

    //Setting up recyclerView of events
    populateSchedualArray();

    schedualRecycler.setLayoutManager(mSchedualLayoutManager);
    mSchedualAdapter = new SchedualAdapter(populateSchedualArray(), ActivityStartup.this);
    schedualRecycler.setAdapter(mSchedualAdapter);

    // On clicking the floating action button
    mAddReminderButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(v.getContext(), ReminderAddActivity.class);
        startActivity(intent);
      }
    });

  }

  @Override
  protected void onResume() {
    super.onResume();

    mSchedualAdapter = new SchedualAdapter(populateSchedualArray(), ActivityStartup.this);
    schedualRecycler.setAdapter(mSchedualAdapter);
  }

  private ArrayList<ReminderModel> populateSchedualArray() {

    ArrayList<ReminderModel> schedualArray = new ArrayList<>();

    Database rb = new Database(ActivityStartup.this);
    tempSchedualArray = rb.getAllReminders();

    ArrayList<ReminderModel> monthOne = new ArrayList<>();
    ArrayList<ReminderModel> monthTwo = new ArrayList<>();
    ArrayList<ReminderModel> monthThree = new ArrayList<>();
    ArrayList<ReminderModel> monthFour = new ArrayList<>();
    ArrayList<ReminderModel> monthFive = new ArrayList<>();
    ArrayList<ReminderModel> monthSix = new ArrayList<>();
    ArrayList<ReminderModel> monthSeven = new ArrayList<>();
    ArrayList<ReminderModel> monthEight = new ArrayList<>();
    ArrayList<ReminderModel> monthNine = new ArrayList<>();
    ArrayList<ReminderModel> monthTen = new ArrayList<>();
    ArrayList<ReminderModel> monthEleven = new ArrayList<>();
    ArrayList<ReminderModel> monthTwelve = new ArrayList<>();

    for (ReminderModel rm : tempSchedualArray) {

      String[] split = rm.getDate().split("/");
      switch (split[1]) {
        case "1":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthOne.add(rm);
          break;
        case "2":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthTwo.add(rm);
          break;
        case "3":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthThree.add(rm);
          break;
        case "4":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthFour.add(rm);
          break;
        case "5":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthFive.add(rm);
          break;
        case "6":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthSix.add(rm);
          break;
        case "7":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthSeven.add(rm);
          break;
        case "8":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthEight.add(rm);
          break;
        case "9":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthNine.add(rm);
          break;
        case "10":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthTen.add(rm);
          break;
        case "11":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthEleven.add(rm);
          break;
        case "12":
          rm.setDate(convertDateToGregorian(split[2], split[1], split[0]));
          monthTwelve.add(rm);
          break;
      }

    }

    schedualArray.add(new ReminderModel(100000001, "start_spring", "", "", "", "", "", ""));
    schedualArray.addAll(monthOne);
    schedualArray.addAll(monthTwo);
    schedualArray.addAll(monthThree);
    schedualArray.add(new ReminderModel(100000004, "start_summer", "", "", "", "", "", ""));
    schedualArray.addAll(monthFour);
    schedualArray.addAll(monthFive);
    schedualArray.addAll(monthSix);
    schedualArray.add(new ReminderModel(100000007, "start_fall", "", "", "", "", "", ""));
    schedualArray.addAll(monthSeven);
    schedualArray.addAll(monthEight);
    schedualArray.addAll(monthNine);
    schedualArray.add(new ReminderModel(1000000010, "start_winter", "", "", "", "", "", ""));
    schedualArray.addAll(monthTen);
    schedualArray.addAll(monthEleven);
    schedualArray.addAll(monthTwelve);

    return schedualArray;
  }

  private String convertDateToGregorian(String year, String month, String day) {

    CalendarTool calendarTool = new CalendarTool();
    calendarTool.setIranianDate(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));

    return calendarTool.getGregorianYear() + "/" + calendarTool.getGregorianMonth() + "/" + calendarTool.getGregorianDay();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == android.R.id.home) {
      Toast.makeText(this, "دکمه خانه کلیک شد !", Toast.LENGTH_SHORT).show();
    }
    if (id == R.id.action_settings) {
      drawerLayout.openDrawer(Gravity.RIGHT);
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * ATTENTION: This was auto-generated to implement the App Indexing API.
   * See https://g.co/AppIndexing/AndroidStudio for more information.
   */
  public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
      .setName("Main Page") // TODO: Define a title for the content shown.
      // TODO: Make sure this auto-generated URL is correct.
      .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
      .build();
    return new Action.Builder(Action.TYPE_VIEW)
      .setObject(object)
      .setActionStatus(Action.STATUS_TYPE_COMPLETED)
      .build();
  }

  @Override
  public void onStart() {
    super.onStart();
  }

  @Override
  public void onStop() {
    super.onStop();
  }

}

and this is my adapter class that i used :

public class SchedualAdapter extends RecyclerView.Adapter<SchedualAdapter.ViewHolder> {
  private ArrayList<ReminderModel> items;
  private Context mContext;

  public SchedualAdapter(ArrayList<ReminderModel> items, Context mContext) {
    this.items = items;
    this.mContext = mContext;
  }

  public static class ViewHolder extends RecyclerView.ViewHolder {

    TextView txtDateNumber;
    TextView txtDateName;
    TextView txtEventTitle;
    TextView txtMonthName;
    ImageView imgMonth;
    LinearLayout layoutTop;

    public ViewHolder(View v) {
      super(v);

      txtDateNumber = (TextView) v.findViewById(R.id.txt_dateNumber);
      txtDateName = (TextView) v.findViewById(R.id.txt_dateName);
      txtEventTitle = (TextView) v.findViewById(R.id.txt_eventTitle);
      txtMonthName = (TextView) v.findViewById(R.id.txt_monthName);
      imgMonth = (ImageView) v.findViewById(R.id.img_monthPic);
      layoutTop = (LinearLayout) v.findViewById(R.id.layoutTop);
    }
  }

  @Override
  public SchedualAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    // Create a new View
    final View v = LayoutInflater.from(mContext).inflate(R.layout.schedual_recycler_item, parent, false);
    ViewHolder vh = new ViewHolder(v);
    return vh;
  }

  @Override
  public void onBindViewHolder(final ViewHolder holder, final int position) {

    if (items.get(position).getTitle().equals("start_spring")) {

      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.spring);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else if (items.get(position).getTitle().equals("start_summer")) {
      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.summer);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else if (items.get(position).getTitle().equals("start_fall")) {
      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.fall);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else if (items.get(position).getTitle().equals("start_winter")) {
      holder.imgMonth.setVisibility(View.VISIBLE);
      holder.imgMonth.setImageResource(R.drawable.winter);
      holder.txtDateName.setVisibility(View.GONE);
      holder.txtDateNumber.setVisibility(View.GONE);
      holder.txtEventTitle.setVisibility(View.GONE);
    } else {

      holder.imgMonth.setVisibility(View.GONE);

      holder.layoutTop.setVisibility(View.VISIBLE);
      holder.txtEventTitle.setText(items.get(position).getTitle());
      holder.txtDateNumber.setText(items.get(position).getDate());

      CalendarTool c = new CalendarTool();

      if (!items.get(position).getDate().equals("")) {

        String[] split = items.get(position).getDate().split("/");
        c.setIranianDate(Integer.parseInt(split[2]), Integer.parseInt(split[1]), Integer.parseInt(split[0]));
        holder.txtDateName.setText("" + c.getDayOfWeek());
      }

    }

    setAnimation(holder.itemView, position);

  }

  private int lastPosition = -1;

  private void setAnimation(View viewToAnimate, int position) {
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {
      ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
      anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
      viewToAnimate.startAnimation(anim);
      lastPosition = position;
    }
  }

  @Override
  public int getItemCount() {
    return items.size();
  }
}

I can't understand how my items will disappear!
I really appreciate it if you can help me.
thank you.

Body:
I had the same issue (https://github.com/square/picasso/issues/845) but in github found this and worked for me. Thaks to @raj9686

rv.getRecycledViewPool().setMaxRecycledViews(0, 0);