Q: Is that correct work of recycleView android 7.0+? I have list of data, and size of data = 7, but when I try to display all the elements, it displays only 6 and in the debug mode in the method onBindViewHolder the last binds position is 5. I thought that was some bugs with my list, so i added 8th element, but it all the same displays only 6 elements.
On android lower than 7.0 everything works properly
Adapter
 public class BottomNavigationAdapter extends RecyclerView.Adapter<BottomNavigationAdapter.MyViewHolder> {

private ArrayList<BottomNavigationData> bottomNavigationDatas = new ArrayList<>();
private Context mContext;

public BottomNavigationAdapter(ArrayList<BottomNavigationData> bnl, Context context) {
    bottomNavigationDatas = bnl;
    mContext = context;
}

public class MyViewHolder extends RecyclerView.ViewHolder {

    ImageView imageView;
    TextView txtview;

    public MyViewHolder(View view) {
        super(view);
        imageView = (ImageView) view.findViewById(R.id.ivBottomItemIcon);
        txtview = (TextView) view.findViewById(R.id.tvBottomTitle);
    }
}

@Override
public BottomNavigationAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.bottom_navigation_item, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(BottomNavigationAdapter.MyViewHolder holder, int position) {
    BottomNavigationData currentNavigationData = bottomNavigationDatas.get(position);
    String image_url = Constants.SERVER_HOST + "/" + currentNavigationData.image;
    Glide.with(mContext).load(image_url).into(holder.imageView);
    holder.txtview.setText(currentNavigationData.name);
    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }

    });

}

@Override
public int getItemCount() {
    return (bottomNavigationDatas != null) ? bottomNavigationDatas.size() : 0;
}

recycle view initialisation
rvBottomNavigation = (RecyclerView) view.findViewById(R.id.rvBottomNavigation);
        LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        rvBottomNavigation.setLayoutManager(horizontalLayoutManager);

   bottomNavigationAdapter = new BottomNavigationAdapter(bottomNavigationDatas, getActivity().getApplicationContext());
        rvBottomNavigation.setAdapter(bottomNavigationAdapter);
        bottomNavigationAdapter.notifyDataSetChanged();

my output on android 7.0+:

output on lower than 7.0:

So as you can see, i have one more item at the end.
Code is exactly the same. How can i fix it?
EDIT
added full code of adapter
item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_marginTop="7dp"
    android:layout_marginLeft="@dimen/small_margin"
    android:layout_marginRight="@dimen/small_margin"
    >
    <ImageView
        android:id="@+id/ivBottomItemIcon"
        android:layout_gravity="center_horizontal"
        android:layout_width="30dp"
        android:layout_height="30dp" />
    <TextView
        android:id="@+id/tvBottomTitle"
        android:textColor="@android:color/white"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"

        />
</LinearLayout>

my_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activities.GiftsActivity">
    <mfp.avdm.chudobox.custom.HeaderGridView
        android:id="@+id/gvGoods"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/footer"
        android:fitsSystemWindows="true"
        android:horizontalSpacing="3dp"
        android:numColumns="2"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:verticalSpacing="3dp" />

    <LinearLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="@drawable/toolbare">

        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="none">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rvBottomNavigation"
                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </HorizontalScrollView>
    </LinearLayout>
</RelativeLayout>

A: Code seems fine but I am sure this is not the way to do it,

*

*You should null check your arrayList in your activity itself, then proceed to set adapter.

*For adapter,you should provide activityContext rather than applicationContext, adapters often hold listeners to open activities or to show toasts, it that case it should be activityContext not applicationContext

*For your problem, I will suggest setting layout manager after setting adapter. In this way, you won't need to call notifyDatasetChang.
Updated part
In your xml, you are adding RecyclerView inside horizontal scrollview which is the reason its giving trouble. Take your recyclerview outside the horizontal scrollview because you are setting the LinearLayoutManager with horizontal orientation in your code anyways. Then set both height and width of the recyclerview to match_parent. Also, if you don't want to add anything else in the footer view, you can remove the linearLayout and set your recyclerview as footer with width=match_parent and height=60dp.
Don't forget to delete horizontalscrollview code.


Q: Disposal of Shared members in a ServicedComponent with ActivationOption.Server For several reasons I need to create a COM+ component in .Net Framework 4. The intent is to host the component in its own process (dllhost.exe), hence the usage of ActivationOption.Server.
My component code needs to persist data between object activations, which is maintained by a worker thread. This worker thread and its data are held in static (shared) members of my base class. The shared data is independent of the caller, its security context, transactions, etc. Also, the worker thread performs background processing on the data.
I need to clean up the data and orderly terminate the worker thread when the dllhost process is disposed. Since there are no static (shared) destructors, I don't know how to do it. Is there anything I could implement while inheriting ServicedComponent? Any other ideas? Thank you.
Here's some code to start:
Imports System.EnterpriseServices

<Assembly: ApplicationName("MySender")>
<Assembly: ApplicationActivation(ActivationOption.Server)>

<ClassInterface(ClassInterfaceType.None), ProgId("MySender.Sender")> _
<Transaction(EnterpriseServices.TransactionOption.NotSupported)> _
Public Class Sender

    Inherits ServicedComponent
    Implements SomeLib.IMsgSender

    Shared worker As myWorker
    Shared sync As New Object

    Public Sub MyInstanceMethod(msg as string) Implements SomeLib.IMsgSender.SendMessage

        SyncLock sync
            If worker Is Nothing Then
                worker = New myWorker
                worker.StartThread()
            End If
        End SyncLock

        worker.Process(msg)

    End Sub

    'Something like this does not exist!'
    Shared Sub Dispose()

        SyncLock sync
            If worker IsNot Nothing Then
                worker.StopThread()
            End If
        End SyncLock

    End Sub

End Class

A: The AppDomain.ProcessExit event will fire before unloading the domain. If the code to run doesn't take too long, it could be used like this:
Imports System.EnterpriseServices

<Assembly: ApplicationName("MySender")>
<Assembly: ApplicationActivation(ActivationOption.Server)>

<ClassInterface(ClassInterfaceType.None), ProgId("MySender.Sender")> _
<Transaction(EnterpriseServices.TransactionOption.NotSupported)> _
Public Class Sender

    Shared Sub New

        AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf MyDisposalCode

    End Sub

    '....

    Shared Sub MyDisposalCode(sender as Object, e as EventArgs)

        'My disposal code

    End Sub

End Class

It's important to notice that .Net will enforce a 2 second timeout on this code.


Q: String Is Empty When Read So basically I call a MYSQL query that grabs a secret key that was generated and saved to the database. Then it sets a string called "ServerCryptKey" to the output of the query which should be "yQnK9xDCxaLIGwzpsKEXeJR2Iz5ZoHnWyLHHikkQv5zbC8B5Sf36ZU9HteHSW5Ov".
$SQLGetUsers = $odb -> query("SELECT * FROM settings");
while ($getInfo = $SQLGetUsers -> fetch(PDO::FETCH_ASSOC))
{
    $NewServerHash = $getInfo['newhash'];
}

I can call the string fine and it will read the above ^, but whenever I have it call it from this function it reads nothing and shows it's an empty string...
function encrypt($data)
{
    $secret = $ServerCryptKey;
    //Generate a key from a hash
    $key = md5(utf8_encode($secret), true);

    //Take first 8 bytes of $key and append them to the end of $key.
    $key .= substr($key, 0, 8);

    //Pad for PKCS7
    $blockSize = mcrypt_get_block_size('tripledes', 'ecb');
    $len = strlen($data);
    $pad = $blockSize - ($len % $blockSize);
    $data .= str_repeat(chr($pad), $pad);

    //Encrypt data
    $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');

    return base64_encode($encData);
}

function decrypt($data)
{
    $secret = $ServerCryptKey;
    //Generate a key from a hash
    $key = md5(utf8_encode($secret), true);

    //Take first 8 bytes of $key and append them to the end of $key.
    $key .= substr($key, 0, 8);

    $data = base64_decode($data);

    $data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');

    $block = mcrypt_get_block_size('tripledes', 'ecb');
    $len = strlen($data);
    $pad = ord($data[$len-1]);

    return substr($data, 0, strlen($data) - $pad);
}

If anyone can help me figure out why this doesn't grab the string, please let me know, thanks!


Q: Angular bootstrap button click function I am using a simple form of my template. In form there is already a validation is added i just need to check when user click on button after all required field how is it possible ?

Your Information

Please provide the correct information we will contact you with your information.

                <form id="contactForm">

                                <input type="text" name="name" id="name" class="form-control" required placeholder="Enter your name">

                                <input type="email" name="email" id="email" class="form-control" required placeholder="Enter your email">

                                <input type="text" name="phone_number" id="phone_number" required class="form-control" placeholder="Enter your number (Whats app)">

                                <input type="text" name="msg_subject" id="msg_subject" class="form-control" required placeholder="Enter your skype name">

                            <button type="submit" class="btn btn-primary">Send Message</button>

                </form>

This is my code I need to simply check when user clicks on Send Message But after all fields are filled as in form. Validation is working fine but the problem is how can I check the button?
I have created a simple function like this
submit(){
  console.log('submit');
}

I if add (click)="submit()" on the button so every time the user clicks it's calling the function. I want when all fields are filled then this function can work.

A: Inner template:
<form #myForm="ngForm">
  <input ngModel name="name" type="text" required />
  <input ngModel name="email" type="email" required />
  <input ngModel name="phone-number" type="text" required />

  <button (click)="onSubmit(myForm)">Submit</button>
</form>

Innner .ts:
onSubmit(form: NgForm) {
  console.log(form.invalid);
}

Be sure that you have imported FormsModule into your module:
import { FormsModule } from '@angular/forms';

@NgModule({
  // ...
  imports: [..., FormsModule, ...],
  // ...
})

A: Important: import { FormsModule } from '@angular/forms'; into your app-module and add it to the imports array.
@NgModule({
  imports: [FormsModule],
})

Create a template variable in form element like myForm given below  and on button tag make use of property binding [disabled]="!myForm.form.valid". Now Submit button will only work when each form element is filled.
Template file:
    <form #myForm="ngForm" method="POST" (ngSubmit)="submitForm(myForm)">

    Name
    <input name="name" type="text" required ngModel/>

    Email
    <input name="email" type="email" required ngModel/>

    Phone no
    <input name="phone" type="number" required ngModel/>

  <button type="submit" [disabled]="!myForm.form.valid">Submit</button>

{{myForm.value | json}}

</form>

You can find my code snippet on StackBlitz


Q: What is the most efficient way I can to get a list of locations sorted by proximity given a location? For example,
Say I have a database of locations (latitude/longtitude), and a point. How can I grab the top 25 nearest locations from the database of locations?
Is there too a library, or a resource I can read up on various geospatial operations like above? Thanks!

A: What you want to do sounds like a nearest neighbour search.
K-d trees are an efficient data structure to achieve this.
The CGAL library has spatial searching functions if you're looking for a library for C++.


Q: Grouping data using a value from a deep subarray How can I assign first level keys using a column value from the third level of a multidimensional array?
My input:
$array = [
    [
        ["ID" => 2, "vendor_id" => "37", "order_id" => 776],
    ],
    [
        ["ID" => 2, "vendor_id" => "37", "order_id" => 786],
    ]
];

My current output is like this:
array(1) {
[787]=>
  array(2) {
    [0]=>
    array(40) {
      ["ID"]=>
      string(1) "1"
      ["vendor_id"]=>
      string(2) "37"
      ["order_id"]=>
      string(3) "776"
    }
    [1]=>
    array(40) {
      ["ID"]=>
      string(1) "2"
      ["vendor_id"]=>
      string(2) "37"
      ["order_id"]=>
      string(3) "787"
    }
  }
}

I want to group the value of order_id separately as a key - the end result would look like this:
array(1) {
  [776]=>
  array(2) {
    [0]=>
    array(40) {
      ["ID"]=>
      string(1) "2"
      ["vendor_id"]=>
      string(2) "37"
      ["order_id"]=>
      string(3) "776"
    }
  }
  [787]=>
  array(2) {
    [0]=>
    array(40) {
      ["ID"]=>
      string(1) "2"
      ["vendor_id"]=>
      string(2) "37"
      ["order_id"]=>
      string(3) "787"
    }
  }
}

A: Get the current item or use reset and extract the entire columns indexing by order_id:
$result = array_column(current($array), null, 'order_id');

If there could be multiple arrays, then just loop and append:
$result = [];
foreach($array as $v) {
    $result += array_column($v, null, 'order_id');
}

A: you can use that function
//$array is your input array
//$mergedArray is the result wanted
$mergedArray = array_reduce($array, function($acc, $val) {
    foreach ($val as $order) {
        $acc[$order['order_id']] = $order;
    }
    return $acc;
}, []);

you can try it on http://sandbox.onlinephpfunctions.com/
<?php
$array = [
    787 => [
        0 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 776],
        1 => [ "ID" => 2, "vendor_id" => "37", "order_id" => 787],
        2 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 790],
    ],
    734 => [
        0 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 722],
        1 => [ "ID" => 2, "vendor_id" => "37", "order_id" => 735],
        2 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 734],
    ],

];

$t = array_reduce($array, function($acc, $val) {
    foreach ($val as $order) {
        $acc[$order['order_id']] = $order;
    }

    return $acc;
}, []);

var_dump($t);

A: The other answers do not maintain the multi-level structure described as your desired output.  The order_id values must be used as first level keys, and the second level keys must be incremented/indexed as they are encountered.  This will allow for multiple entries which share the same first level key.
foreach() inside of a foreach(): (Demo)
$result = [];
foreach ($array as $group) {
    foreach ($group as $row) {
        $result[$row['order_id']][] = $row;
    }
}
var_export($result);

array_reduce() with foreach(): (Demo)
var_export(
    array_reduce(
        $array,
        function ($carry, $group) {
            foreach ($group as $row) {
                $carry[$row['order_id']][] = $row;
            }
            return $carry;
        }
    )
);


Q: Sharepoint - Load a form's view based on user I am using a data connection list to load desired views in an InfoPath form on SharePoint.  I have a permission list with 2 columns: usernames and control group.  My form on the main list loads a specific view based on what the username and group are of the permission list.  You have to filter out the group based on the form's username() function to match the username column and set that as a condition to (on form load) change it to a specific view.
All this works, but the problem comes in when you have a user with multiple control groups.  The filter only returns the first instance it finds.  I can't think of a way to fix this.  Maybe load the other list as a repeating table into the form, but then how would I reference that table in the conditions of a form load rule? Or is there a way to get a field filter to look past the first item it finds?
Update: I forgot to mention that I have to use a field to hold your filtered username:id:group aka group[title=username()] and then use that in the form load conditions.  I think this is where the problem is, as this filter is what doesn't store all instances of the users id from the control list, but only the first.
SharePoint 2010 with forms created in InfoPath 2010

A: Are you querying the data in from info path or using visual studio, if you are querying in info path check the condition as Display name matches the username() and the query the data


Q: How can I remove space between children in the row? enter image description here
I would like to remove space between icon and text. How can I remove space between children in the row?/////////
/////////////////////////////////////////////////////////////////////////////////////////
Widget topSection() {
  return Row(
    mainAxisAlignment: MainAxisAlignment.end,
    children: [
      Padding(
          padding: EdgeInsets.only(left: 20.0, top: 180),
          child: MaterialButton(
            onPressed: () {},
            color: Colors.black,
            textColor: Colors.white,
            child: Icon(
              Icons.done,
              size: 24,
            ),
            shape: CircleBorder(),
          )),
      Expanded(
          child: Padding(
        padding: EdgeInsets.only(top: 180),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(left: 4),
              child: Text("Wellness Coaching",
                  style: TextStyle(
                      fontSize: 18,
                      fontFamily: "LatoR",
                      fontWeight: FontWeight.w900)),
            ),
            Padding(
              padding: EdgeInsets.only(left: 4),
              child: Text("Connect to your data",
                  style: TextStyle(fontSize: 18, fontFamily: "LatoR")),
            )
          ],
        ),
      )),
    ],
  );
}

A: mainAxisAlignment: MainAxisAlignment.end,

Try deleting this line.


Q: How to use pillow module in pyscript to open screenshot using an html onclick button? <button id="button" type = "button" class="btn btn-primary" pys-onClick="run_python">
 NEXT </button>
<py-script>

from PIL import Image
 op = Element("output")
 def run_python(*args,**kwargs):
 image = Image.open("home/saikumar/Desktop/screenshot/selenium1.jpg"/)
 image.show()

</py-script>

I am trying to open the screenshot image which is present in my local directory using the PIL module by clicking button but I am unable open and getting error like "file not found" and I have to open the screenshot by clicking NEXT button.
Error case:
Uncaught PythonError: Traceback (most recent call last):
File "<exec>", line 4, in run_python
File "/lib/python3.10/site-packages/PIL/Image.py", line 3068, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 44] No such file or directory: 'home/saikumar/Desktop/screenshot/selenium1.jpg'

at new_error (pyodide.asm.js:14:238191)
at pyodide.asm.wasm:0xedbcb
at pyodide.asm.wasm:0xedccc
at Module._pythonexc2js (pyodide.asm.js:14:932707)
at Module.callPyObjectKwargs (pyproxy.gen.ts:374:12)
at Module.callPyObject (pyproxy.gen.ts:384:17)
at PyProxyClass.apply (pyproxy.gen.ts:1145:19)
at Object.apply (pyproxy.gen.ts:1022:18)
new_error @ pyodide.asm.js:14
$wrap_exception @ pyodide.asm.wasm:0xedbcb
$pythonexc2js @ pyodide.asm.wasm:0xedccc
Module._pythonexc2js @ pyodide.asm.js:14
Module.callPyObjectKwargs @ pyproxy.gen.ts:374
Module.callPyObject @ pyproxy.gen.ts:384
apply @ pyproxy.gen.ts:1145
apply @ pyproxy.gen.ts:1022


Q: KeyEvent.KEYCODE_VOLUME_UP(DOWN) registering double hits I have a simple app where I do the following:
public void onClick(View v){

    switch(v.getId()) {
        case R.id.buttonup:
            onButtonUp();
            break;

        case R.id.buttondown:
            onButtonDown();
            break;
    }

}

public boolean dispatchKeyEvent(KeyEvent event){
        int keyCode = event.getKeyCode();
        switch (keyCode) {

        case KeyEvent.KEYCODE_VOLUME_UP:
             onButtonUp();
             return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            onButtonDown();
            return true;

        default:
            return super.dispatchKeyEvent(event);

        }

    }

void onButtonUp(){
    increment_some_static_class_variable;
}

void onButtonUp(){
    decrement_some_static_class_variable;
}

The thing is, whenever I press volume buttons, the onButtonUp and onButtondown functions are called twice. This does not happen when I press on screen buttons (handled in onClick(View)). I didn't find anybody having this issue so I am asking the folks here. I am new to Android and this is my first Application. Using Log, I found that both calls to onButtonUp and onButtonDown are coming from dispatchKeyEvent function. What could be wrong here? I hope I explained the problem well. Suggestions/Solutions are most welcome.

A: KeyEvent can represent multiple actions, specifically both ACTION_DOWN and ACTION_UP. Since you aren't checking the action in your dispatchKeyEvent callback you are calling your button click methods for both DOWN and UP events on the volume buttons. Try like this:
public boolean dispatchKeyEvent(KeyEvent event){
    int keyCode = event.getKeyCode();
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch (keyCode) {

            case KeyEvent.KEYCODE_VOLUME_UP:
                 onButtonUp();
                 return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                onButtonDown();
                return true;

            default:
                return super.dispatchKeyEvent(event);
        }
    }
}


Q: What are the next step after compiling PYBIND11_MODULE in C++ file I was trying to use PYbind 11 to wrap the following small C++ test programme into a Python module, so I can call the test C++ function from python files.
My problem is : while the C++ file compiled successfully, I have no clue as to what steps to take next to import the newly created module file in python.
I tried to run "from example import add" in a test Python file in Spyder but received error message saying there is no module named example.
I'm using Windows10 (x64bit), Python3.7 and Visual studio 2017 community.
Can some one please help? Thank you very  much!
#include
//#include <Aspose.Cells.h>
#include <pybind11/pybind11.h>

void print(const char*);

int add(int i, int j) {
return i + j;
}

PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring

m.def("add", &add, "A function which adds two numbers");
}

int main()
{
const char *x = "C Plus plus is wonderful.";

char *z;
char b = 'z';
z = &b;

int num = 10;
int* a = 0;

print(x);
}

void print(const char* z)
{

std::cout << "pointer z is" << z << "\n";

std::cin.get();
}

UPDATE: I followed Stuart's suggestion below when building my test c++ programme. I made two attempts: at the first attempt, I changed Target Extension to ".pyd"; whereas at the second attempt, I kept Target Extension as "dll".
In both attempts, I received the same error message from Visual Studio, which seem to suggest that the DLL file being built can not be started (as shown in the screenshot that immediately follows)
Error Messages for Starting DLL Programme
However, the actual building of dll file seemed successful, as I can see one dll file and one Python Extension Module file, with filenames and path listed as follows:
C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug\ConsoleApplication5.dll
and
C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug\ConsoleApplication5
The Visual Studio output message upon building is pasted at the end.
My problem is: I created a Test.py file in the same directory (C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug)
and tried to run it in Spyder after including just one line command "import example ". Sypder returned a error message saying " No MODULE Named Example".
Can anyone please help? Thanks a lot!
1>------ Build started: Project: ConsoleApplication5, Configuration: Debug x64 ------
1>LINK : C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug\ConsoleApplication5.dll not found or not built by the last incremental link; performing full link
1>   Creating library C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug\ConsoleApplication5.lib and object C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug\ConsoleApplication5.exp
1>ConsoleApplication5.vcxproj -> C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug\ConsoleApplication5.dll
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

UPDATE2: I followed every details of Stuart's instructions in his Update2.
I got example.pyd (as shown in the following screenshot)

However, I got error message when running in Spyder, as follows:
(Sorry I only managed to copy the second half of Spyder output message as its very hard to do text selection in Spyder console)
File "C:\Users\rmili\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/rmili/source/repos/ConsoleApplication5/x64/Debug/Test.py", line 9
    d = "C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug"
       ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I changed backward slash "" to  forward slash"/" in the value that's being assigned to "d", and got the following error again:
File "C:\Users\rmili\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/rmili/source/repos/ConsoleApplication5/x64/Debug/Test.py", line 12, in <module>
    import example

ModuleNotFoundError: No module named 'example'

UPDATE3:
As shown in the following screenshot, example module can not be found in Windows command line prompt.
[Unable to find example module in Windowscommand line prompt]3

A: Make sure the compiled output file is named example.pyd (or has a symlink of that name pointing to it), and try running python from the same directory.

Update: How to build a .pyd in Visual Studio
On Windows, compiled Python modules are simply DLL files, but they have a .pyd file extension.  You mentioned that your C++ file compiles successfully.  Did you compile it as an executable (.exe), or as a .dll? You should compile it as a DLL, but change the file extension to .pyd.
The Visual Studio documentation explains how to change your project to create a DLL.  Here's what it says:

*

*Open the project's Property Pages dialog box. For details, see Set C++ compiler and build properties in Visual Studio.

*Click the Configuration Properties folder.

*Click the General property page.

*Modify the Configuration Type property.

Also, on that same settings page, you can find an option to change the Target Extension property.  Change it to .pyd.  (Or simply rename the file yourself after it is built.)

Update 2
I think you need to change three settings:

*

*Target Name

*

*Change to example

*Target Extension

*

*Change to .pyd

*Configuration Type

*

*Change to Dynamic Library (.dll)
Also, I recommend deleting (or commenting out) everything from example.cpp except for the code shown below.  (I don't know if the presence of a main() function may cause problems, so just remove it.)
After that, building your project should produce the following file:
C:\Users\rmili\source\repos\ConsoleApplication5\x64\Debug\example.pyd
Than, from the Spyder console, try this:
import os

d = "C:\\Users\\rmili\\source\\repos\\ConsoleApplication5\\x64\\Debug"
os.chdir(d)

import example
example.add(1,2)

I don't have a Windows machine to test with.  But in case it's useful, here's how I compiled your example on my Mac.  (On Mac and Linux, they use the extension .so instead of .pyd.)
// example.cpp
#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin";

    m.def("add", &add, "A function which adds two numbers");
}

$ # Compile
$ clang++ -I${CONDA_PREFIX}/include -I${CONDA_PREFIX}/include/python3.7m -undefined dynamic_lookup -shared -o example.so example.cpp

$ # Test
$ python -c "import example; print(example.add(10,20))"
30

A: I have found answer to my problem:

*

*Make sure all steps I described previously in my post are done

*this is what I missed -` It is important to make sure the file type of "example" is Python Extension Module, as shown in the following screenshot .
As shown in screenshots of my Updates, initially the Type of my "example.pyd" file was just "File". I managed to convert it to Python Extension Module by adding "cp35-win_amd64." in the file extension, resulting in file name "examplelib.cp35-win_amd64.pyd", and then remove the same texts that were added.


Q: scaling up angular firestore app by associating data to each user I created an app using Angular 7, and crud with firestore. Everything is working fine with one user. Now, I am trying to scale it, and associate data with each logged user. I can't find detailed material on the web.
I have users in collection. I want to create a collection of 'vacations' and nest it under each user, for his collection of vacations. I believe the first step, is to get the current logged user uid, and update whatever function I might have, to edit the collection, then .doc('current user id').
This is code I used to get current user's uid:
this.userID = this.firestore.collection('users').doc(this.auth().user.uid);
errors in pre-compiler:

1- Type 'AngularFirestoreDocument<{}>' is not assignable to type
  'string'
2- Cannot invoke an expression whose type lacks a call signature. Type
  'AuthService' has no compatible call signatures.

This is currently how the data is structured:

This is the auth service:
export class AuthService {

  user$: Observable<User>;

  constructor(
        public afAuth: AngularFireAuth,
        public afs: AngularFirestore,
        public router: Router
  ) {
    // Get the auth state, then fetch the Firestore user document or return null
    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
          // Logged in
        if (user) {
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }

  googleLogin() {
    const provider = new auth.GoogleAuthProvider()
    return this.oAuthLogin(provider);
  }

  public oAuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider)
      .then((credential) => {
        this.updateUserData(credential.user)
      })
  }

  public updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL
    }
    return userRef.set(data, { merge: true })

  }
}

Appreciate your help.

A: Googles official answer can be found here - Get the currently signed-in user - Firebase
Below is a function that returns a promise of type string. The promise resolves with the user's uid which is returned from onAuthStateChangedwhich() along with the rest of the user's firebase auth object(displayName...etc).
getCurrentUser(): Promise<string> {
  var promise = new Promise<string>((resolve, reject) => {
    this.afAuth.auth.onAuthStateChanged(returnedUser => {
      if (returnedUser) {
        resolve(returnedUser.uid);
      } else {
        reject(null);
      }
    });
  })
  return promise
}

You would call it in the constructor or ngOninit:
userDoc: User = null;

constructor() {
  this.getCurrentUser().then((userID: string) => {
    //here you can use the id to get the users firestore doc
    this.afs.collection('users').doc(userID).valueChanges()
    .subscribe(userFirestoreDoc => { // remember to subscribe
      this.userDoc = userFirestoreDoc;
    })
  }).catch(nullID => {
    //when there is not a current user
    this.userDoc = null
  })
}

To add a collection for 'vacations' nested in the users doc you need to add a sub collection to the that users firestore doc. I would advise only doing this once the user gets/adds their first vacation. You can simply set a doc in the subcollection and if the sub collection doesn't already exist firestore will first create it and then add the new doc(vaction) so this is the only code you need to set the new collection and new vaction inside that collectio.
this.afs.collection('users').doc(this.userDoc.uid).collection('vacations).add(vactionObject).then(returnedVaction => {

}).catch(error => {

})

A: users =》last login
This field on the google auth user object is updated on every new login with the time of the last success login


Q: Laravel 5 dynamically run migrations so I have created my own blog package in a structure of Packages/Sitemanager/Blog I have a service provider that looks like the following:
namespace Sitemanager\Blog;

use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

class BlogServiceProvider extends LaravelServiceProvider {

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot() {

        $this->handleConfigs();
        $this->handleMigrations();
        $this->handleViews();
        $this->handleRoutes();
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register() {

        // Bind any implementations.
        $this->app->make('Sitemanager\Blog\Controllers\BlogController');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides() {

        return [];
    }

    private function handleConfigs() {

        $configPath = __DIR__ . '/config/blog.php';

        $this->publishes([$configPath => config_path('blog.php')]);

        $this->mergeConfigFrom($configPath, 'blog');
    }

    private function handleTranslations() {

        $this->loadTranslationsFrom(__DIR__.'/lang', 'blog');
    }

    private function handleViews() {

        $this->loadViewsFrom(__DIR__.'/views', 'blog');

        $this->publishes([__DIR__.'/views' => base_path('resources/views/vendor/blog')]);
    }

    private function handleMigrations() {

        $this->publishes([__DIR__ . '/migrations' => base_path('database/migrations')]);
    }

    private function handleRoutes() {

        include __DIR__.'/routes.php';
    }
}

Now, what i would like to do is run the migrations dynamically if they have never been run before or within an installation process i suppose. I've seen in older documentation you could so something like this:
Artisan::call('migrate', array('--path' => 'app/migrations'));

However, this is invalid in laravel 5, how can I approach this?

A: Artisan::call('migrate', array('--path' => 'app/migrations'));

will work in Laravel 5, but you'll likely need to make a couple tweaks.
First, you need a use Artisan; line at the top of your file (where use Illuminate\Support\ServiceProvider... is), because of Laravel 5's namespacing. (You can alternatively do \Artisan::call - the \ is important).
You likely also need to do this:
Artisan::call('migrate', array('--path' => 'app/migrations', '--force' => true));

The --force is necessary because Laravel will, by default, prompt you for a yes/no in production, as it's a potentially destructive command. Without --force, your code will just sit there spinning its wheels (Laravel's waiting for a response from the CLI, but you're not in the CLI).

I'd encourage you to do this stuff somewhere other than the boot method of a service provider. These can be heavy calls (relying on both filesystem and database calls you don't want to make on every pageview). Consider an explicit installation console command or route instead.

A: After publishing the package:
php artisan vendor:publish --provider="Packages\Namespace\ServiceProvider"
You can execute the migration using:
php artisan migrate
Laravel automatically keeps track of which migrations have been executed and runs new ones accordingly.
If you want to execute the migration from outside of the CLI, for example in a route, you can do so using the Artisan facade:
Artisan::call('migrate')
You can pass optional parameters such as force and path as an array to the second argument in Artisan::call.
Further reading:

*

*https://laravel.com/docs/5.1/artisan

*https://laravel.com/docs/5.2/migrations#running-migrations

A: For the Laravel 7(and probably 6):
use Illuminate\Support\Facades\Artisan;

Artisan::call('migrate');

will greatly work.


Q: logits and labels must be broadcastable, labels and logits dimension mismatch I am new to Tensorflow and making a Multiclass Classifier. My dataset has 6 classes with images 150x150.
I am getting error regarding Mismatch of dimensions of Logits and Labels,

I have seen other such questions on stackoverflow and my problem don't seem to be any of them.

Please anyone tell me what's the error, and also tell while constructing the I need not to tell batch size for output layer ( it's None if you see model.summary,it is automatically known later), so what things could affect it.?
The Error says:
logits and labels must be broadcastable: logits_size=[40,6] labels_size=[10,6]

Model is defined as follows:
batch_size = 10
epochs = 100
IMG_HEIGHT = 150
IMG_WIDTH = 150
IMG_CHANNEL = 3
classes = 6

inputs = Input(shape=(IMG_HEIGHT, IMG_WIDTH ,3))
conv1 = Conv2D(96, 11, strides=(4,4) , padding='valid', activation='relu')(inputs)
pool1 = MaxPooling2D(pool_size=(3, 3), strides=(2,2), padding='valid', data_format=None)(conv1)
a = tf.keras.layers.Lambda(tf.nn.local_response_normalization)
lrn1 = a(pool1)
conv2 = Conv2D(256, 5, padding='same', strides=(1,1) , activation='relu')(lrn1)
pool2 = MaxPooling2D(pool_size=(3, 3), strides=(2,2), padding='valid', data_format=None)(conv2)
b = tf.keras.layers.Lambda(tf.nn.local_response_normalization)
lrn2 = b(pool2)
conv3 = Conv2D(384, 3, padding='same', strides=(1,1), activation='relu')(lrn2)
conv4 = Conv2D(384, 3, padding='same', strides=(1,1), activation='relu')(conv3)
conv5 = Conv2D(256, 3, padding='same', strides=(1,1), activation='relu')(conv4)
conv6 = MaxPooling2D(pool_size=(3, 3), strides=(2,2), padding='valid', data_format=None)(conv5)
flat1 = Flatten()(conv6)
dense1 = Dense(4096, activation='relu')(flat1)
drop1 = Dropout(0.5)(dense1)
dense2 = Dense(4096, activation='relu')(drop1)
drop2 = Dropout(0.5)(dense2)
dense3 = Dense(classes,activation='softmax')(drop2)

model = Model(inputs=inputs, outputs=dense3, name="one")

opt = SGD(lr=0.1, momentum=0.1)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

# Generator Declaration
train_image_generator = ImageDataGenerator(
                                              rescale=1./255,
                                              rotation_range=45,
                                              width_shift_range=.15,
                                              height_shift_range=.15,
                                              horizontal_flip=True,
                                              zoom_range=0.5
                                        ) # Generator for our training data

validation_image_generator = ImageDataGenerator(
                                         rescale=1./255
                                        ) # Generator for our validation data
train_data_gen = train_image_generator.flow_from_directory(
                                                           batch_size=batch_size,
                                                           directory=train_dir,
                                                           shuffle=True,
                                                           class_mode='categorical',
                                                           target_size=(IMG_HEIGHT, IMG_WIDTH)
                                                         )

val_data_gen = validation_image_generator.flow_from_directory(
                                                              batch_size=batch_size,
                                                              directory=val_dir,
                                                              class_mode='categorical',
                                                            )

history = model.fit(
                              train_data_gen,
                              steps_per_epoch=3000//batch_size,
                              epochs=epochs, validation_data=val_data_gen,
                              validation_steps=3000//batch_size
                              )

A: It seems you are using AlexNet, but on samll size images
If you are using AlexNet architecture on smaller images, you need to resize images or you have to do some changes in Pool and Stride hyperparameters, because with current shape something funcky happens in conv5 affecting the architecture.


Q: Add dimension to pandas DataFrame I have a pandas DataFrame that includes a pipe-separated string in one of the fields. I've split this into a list inside an apply and added it to the DataFrame. The number and content of the values in the pipe-separated string vary.
df = DataFrame([{'wibble': 'a', 'pipestring': 'aa|aaa|aaa'},
    {'wibble': 'b', 'pipestring': 'bb|bbbb|bbb|bbbbbb'}])

df['pipelist'] = df['pipestring'].map(lambda x: x.split('|'))

I'm pretty new to pandas so could be completely wrong about this, but I think this would be better represented via a DataFrame with multiple index levels so I can take advantage of panda's indexing and other (fabulous) tools. However I can't figure out how to do this. Any pointers / advice on what I should be doing instead much appreciated.

A: What is your computational goal more specifically?
Here's a way to split your data up and create a combined frame
In [44]: x = df['pipestring'].apply(lambda x: pd.Series(x.split('|')))

In [45]: x
Out[45]:
    0     1    2       3
0  aa   aaa  aaa     NaN
1  bb  bbbb  bbb  bbbbbb

In [46]: df.join(x).set_index(['wibble'])
Out[46]:
                pipestring                 pipelist   0     1    2       3
wibble
a               aa|aaa|aaa           [aa, aaa, aaa]  aa   aaa  aaa     NaN
b       bb|bbbb|bbb|bbbbbb  [bb, bbbb, bbb, bbbbbb]  bb  bbbb  bbb  bbbbbb

A: The quickest way to get started with that is to stack your dataframe:
In [44]: df = df.stack()

In [45]: df.ix[0, 'pipelist']
Out[45]: ['aa', 'aaa', 'aaa']

In [46]: df
Out[46]:
0  pipestring                 aa|aaa|aaa
   wibble                              a
   pipelist               [aa, aaa, aaa]
1  pipestring         bb|bbbb|bbb|bbbbbb
   wibble                              b
   pipelist      [bb, bbbb, bbb, bbbbbb]

Does that get you where you want to be?


Q: MaxJsonLength error in NewtonSoft JsonConvert.SerializeObject I have a ASP.NET project, with some AJAX calling a webmethod, that would return JSON.
If the DataSet has about 100 lines, there is no problem. But with 1000 lines, it launch the error:

Error during serialization or deserialization using JSON JavaScriptSerializer. The size of the string exceeds the value set in the maxJsonLength property

    [WebMethod(EnableSession = true)]
    public static string PublicWebMethod()
    {
            DataSet ds = new DataSet(); // in the reality do a mountrous query

            if (ds.Tables[0].Rows.Count > 0)
            {
                return JsonConvert.SerializeObject(clsUtil.ToArray(ds.Tables[0]));
            }
            else
            {
                return "false";
            }
        }
    }

How can I solve this by setting a configuration in the method?
I don't want to change the web.config

A: I had the similar issue and took a while to figure out the problem and fix.
Please include the following code after
<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000" />
    </webServices>
  </scripting>
</system.web.extensions>


Q: Multiple web docker containers on a host What is the best practice concerning multiple web containers running on a single host.
How would I assign these subdomains
subdomain1.mydomain.com to container1 and
subdomain2.mydomain.com to container2
when both containers run on host1 with ports 50000 and 50001?
How would this configuration work if I wanted to assign paths to both containers e.g.: mydomain.com/pathnameleadingtocontainer1 , mydomain.com/pathnameleadingtocontainer2 again with both containers running on host1 with ports 50000 and 50001?


Q: How to process the files in NodeJS sent from client FormData? I use HTML5 FormData to upload files from the client to Node Server. In the node server, I have included multiparty module to process the uploaded, but not sure of how it works.
server.js:
var parms = urlLib.parse(req.url, true);
var form = new multiparty.Form();
form.parse(req, function (err,fields,files) {
   console.log(fields, files);
});

I want to know how to write the code for processing the uploaded file. I have tried using fs.readFile and fs.createReadStream, but node threw an error "file path must be of type String" but the uploaded files are blob object. So, how do i proceed further?


Q: socket.io client not able to connect and receive messages emit by server I am emitting messages from socket.io server running on port 8001
but my socket.io client not able to connect and receive these messages
my index.html (client):
    <script src="https://cdn.socket.io/socket.io-4.0.0.js"></script>
    <script>
      //var socket = io();
      //var socket = io.connect('http://localhost:8001');
      var socket = io('http://localhost:8001', { transports : ['websocket'] });
      socket.on('connect', function(){
        console.log("connected");
        socket.on("message", data => {
          console.log(data);
        });
      });
    </script>

My nodejs server code:
    const app = require("express")();
    const server = require("http").createServer(app);

    const io = require("socket.io")(server, {
        cors: {
          origin: '*',
        }
      });

    io.on("connection", () => {
        console.log("Connected!");
    });

    var redis = require('redis');
    //var url = "redis://:@localhost:6379";
    //var redis = require('redis-url').connect();
    //var client = redis.createClient(url);
    var client = redis.createClient();
    //var client = redis.createClient();
    client.on("error", function(error) {
      console.error(error);
    });
    client.subscribe('notification');
    client.on('message', function(channel, msg) {
      console.log("Message received: "+msg);
      io.sockets.emit(msg);
    });

    console.log('starting server on 8001...');
    server.listen(8001);

My node js server console logs:
starting server on 8001...
Message received: from laravel

A: io.sockets.send(msg);

this worked for me. also make sure you are using the same version of socket.io on both client and server


Q: OpenVPN Test cases I am looking for the answer: how can I auto disconnect connection of VPN Client after specific idle time or specific connection duration?
There are many clients connected to my OpenVPN server but they forgot to disconnect VPN client or they connect for a long time but do nothing.
I am using OpenVPN Access Server v2.4.12


Q: PHP site/script map with dependencies Just inherited a large PHP 5.3 site and wondered if there were some sort of crawler or site map tool that would identify the files and their dependencies.

A: You can determine PHP version and extension dependencies with PEAR's PHP_CompatInfo package.  As for PEAR packages the app might be using, you can see what's installed using
pear list -a

I don't know of a tool that will tell you which external script dependencies are in use other than grep.


Q: Difference in the Validation and Evaluation Accuracy I am using pre-trained GoogLeNet and then fine tuned it on my dataset for classifying 11 classes. Validation dataset seems to give the "loss3/top1" 86.5%. But when I am evaluating the performance on my evaluation dataset it gives me 77% accuracy. Whatever changes I did it train_val.prototxt, I did the same changes in deploy.prototxt. Is the difference between the validation and evaluation accuracy is normal or I did something wrong?
Any suggestions?

A: In order to you get the fair estimation of your trained model on the validation dataset you need to set the test_itr and test_batch_size in a meaningful manner.
So, test_itr should be set to:
Val_data / test_batch_Size

Where, Val_data is the size of your validation dataset and test_batch_Size is validation batch size value set in batch_size for the Validation phase.


Q: Resolving Promises sequentially angular Actually I need to do execute var1 before var2 in angular
Please let me know how I can achieve this. Thanks for your help
let var1 = Promise.resolve(database.query(sql))
          .then((res) => {
               someVar = res;
               return someVar;
}))

let var2 = Promise.resolve(database.query(sqlanother)){
          .then((resanother) => {
               someanotherVar = resanother;
               return someVaranother;
}))


Q: Why check if value of an array is an array? I came across the following code in the book PHP Solutions, 2nd Edition
<?php
foreach ($_POST as $key => $value) {
    // assign to temporary variable and strip whitespace if not an array
    $temp = is_array($value) ? $value : trim($value);
    // if empty and required, add to $missing array
    if (empty($temp) && in_array($key, $required)) {
        $missing[] = $key;
    } if (in_array($key, $expected)) {
        // otherwise, assign to a variable of the same name as $key
        ${$key} = $temp;
    }
}
?>

My question is in regards to this line:
$temp = is_array($value) ? $value : trim($value);
If $value is the value held in the array (user inputted content from a form), why is it critical to determine whether or not the value is an array?  Is it for security?

A: "why is it critical to determine whether or not the value is an array?"
Because trim expects a string and the function might not work when passing an array. It has nothing to do with security.


Q: Simple regex redirect not working I'm trying to setup a simple regex redirect. I have the following:
^.+?testurl\.com/folder-path/(\w+?$)/secondfolder

Which should then redirect to
http://www.testurl.com/folder-path/$1

This works if I don't add the /secondfolder to the end of the regex, but as soon as I add /secondfolder it doesn't work so I presume my syntax is wrong. Can anybody shed any light on what is wrong about the /secondfolder part of this?
Thanks!

A: $ denotes the end of the string (while ^ marks the start), so you should put it at the end of the string.
^.+?testurl\.com/folder-path/(\w+?)/secondfolder$


Q: Failed to bundle asset error with CDK + Lambda I have this project structure (where control is the name and root of my project):
control
|_ src
  |_ control_loader -> this has a function inside called also control_loader
  |_ utils
     |_ some_helper_function.py
     |_ __init__.py
  |_ __init__.py
|_ lib
   |_ some-cdk-where-i-declare-a-lambda.ts
|_ requirements.txt

Inside some-cdk-where-i-declare-a-lambda.ts I have this (among all the other necessary stuff):
        new Function(this, `${this.appName}${this.stageName}ControlLambdaLoader`, {
            code: Code.fromAsset(path.join(__dirname, '../src'), {
                bundling: {
                    image: Runtime.PYTHON_3_8.bundlingImage,
                    command: [
                        'bash', '-c',
                        'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output',
                    ],
                },
            }),
            runtime: Runtime.PYTHON_3_8,
            handler: 'control_loader.control_loader',
            vpc,
            vpcSubnets: vpc.selectSubnets({
                subnetType: SubnetType.PRIVATE_WITH_NAT,
            }),
        });

However, upon running cdk synth, I get the following:
(venv) PS C:\Users\rodri\Documents\control> cdk synth
npx: installed 15 in 1.145s
Bundling asset controlPipelineStack/controlBetaDeployStage/controlbetaStack/controlbeta/controlbetaControlLambdaLoader/Code/Stage...
Failed to bundle asset controlPipelineStack/controlBetaDeployStage/controlbetaStack/controlbeta/controlbetaControlLambdaLoader/Code/Stage, bundle output is located at C:\Users\rodri\Documents\control\cdk.out\asset.059c3b383943a1fadd3d933b670a7d351991e742d24a9785474b35c846267fde-error: Error: spawnSync docker EN
OENT

This is a very cryptic error. I know the bundling is done by docker to push the dependencies as a zip asset, but, any idea of where is this failing? I also tried to change the location of requirements.txt to inside src and that didn't help. I can deploy everything I remove the Lambda out. What am I doing wrong? Also, how do I make the bundle include some_helper_function.py as well?
Thanks!


Q: Implementing a scheduler for a backup program for a backup program I am doing I have already finished the GUI. Now I want to do the functional requirements. Each backup can have schedules. There are predefined settings like every Sunday or Monday but the user can also specify his own schedules.
As I have never done anything like this, I was wondering what a good approach would be to running a backup every x hours or days. I was thinking about using Threads or writing a service but both fields are totally new to me. What would be the best method here?

A: If threaded development and service development are both totally new then I think you will struggle to implement this in a useful way.  Even so...
Scheduler-type applications are best run as services, because otherwise you need the user to be logged in to be running the application.  Services run independently of the user being logged in.
Because of this, however, services don't have a user interface so your GUI needs to package up the details of schedule into a configuration file somewhere, then signal the service to re-load that configuration file so that the service will then know what to do and when to do it.
The service will normally spawn a worker thread to do pretty much everything, and that worker thread needs to be able to respond to the service being shut down (read up on AutoResetEvent to see how this might be done across threads).  The thread will then wait until either an event or for the appropriate time to arrive and then do whatever it has to do.
None of this is actually complicated, but I suggest you do some digging into multithreaded programming first.

A: I agree with ColinM, Services are best for the Scheduler Type of application.
You have to combine the Services with application to run your code at scheduled intervals.
See the article for more details - http://msdn.microsoft.com/en-us/magazine/cc163821.aspx


Q: Current Status of Sproutcore/Ember/Blossom/Sencha and Mobile devices (or alt frameworks) I've been looking over Sproutcore, Ember and Blossom and other competitive framework efforts (e.g. Sencha) to select for a HTML5 client side application project. The state, information, and documentation from these projects is a bit fragmented and in need of clarity, so I am presenting this to the community.
My project is to be a native-like HTML5 application with desktop level complexity in need of a complete application framework, that will work well on desktops and run with good speed on mobile devices with touch awareness. The widgets should be native-like (not web-like), but customizable so to be unique to the application.
Questions/framework Requirement:

*

*Native vs. Web style Applications. Framework should make it easy to
build native-like user experiences with the ability to make a custom
native feel (not just wholly imitating mac/win/iOS). Some of the text
surrounding Ember indicates it is really meant for web-style apps - which given no
UI layer maybe goes without saying. Frameworks like Sencha, can it easily accommodate custom widgets?

*Mobile Appropreatness. Framework should be appropreate for mobile devices and have facilities for touch input and
gestures.Several notes I've seen in my research indicate that Sproutcore and
Blossom aren't very appropreate for mobile, and that Ember is better
geared towards mobile (size?). It isn't clear whether the
touch/mobile libraries are very developed in Sproutcore/Blossom and if they will be supported it the
current state going forward. (and blossom compile to native is not acceptable). On the otherhand, Frameworks like Sencha, do they have the facility to work well on desktop as well as mobile?

*Framework Completeness. The framework should be a fairly complete application framework, with desktop-like OO expectations and management for automatically and efficiently syncing, managing, and serializing the data model with the server. Not sure if there is much difference between Ember and Sproutcore, how do other efforts like Sencha stack up?

A: Your question covers a lot of ground.  I will pick some quotes and answer them directly.

My project is to be a native-like HTML5 application with desktop level
  complexity in need of a complete application framework

Ember.js specifically bills itself as a "web-style" framework, not a an RIA framework.  That said, you can build anything you want, but you would be trailblazing.
Sproutcore bills itself as an RIA framework.  You have complete control over the DOM, so if you can do it in the browser, you can do it in Sproutcore.
Ext-Js is also a good application framework for desktops (Sencha Touch is for Mobile).  If you like the way its examples look, then its a good choice.  You can of course customize the dom and write your own widgets.
Blossom is basically Sproutcore with a canvas based view layer.  It just went into beta, so you would definitely be trailblazing if you went with it.
So, you can basically use any of the frameworks you mentioned for the RIA part of your enterprise.  I would eliminate Ember.js simply because the framework itself purposes itself for web-style (e.g. twitter) as opposed to RIA (e.g. iCloud) apps, which is not what you want.

The widgets should be native-like (not web-like), but customizable so
  to be unique to the application.

All three of your remaining options can do this.  If you like Senchas widgets, its a good choice.  I don't know if they are native enough for you.  That said, with any of the remaining frameworks you can customize the DOM to your heart's content.
Mobile Appropreatness. Framework should be appropreate for mobile devices

This is a tough one.    Sencha Touch (which is separate but similar to Ext-Js) is very popular and gets the job done.  It is performant too; a non-trivial app ran fine on my original Droid (which surprised me).
Sproutcore is very heavy weight.  It has mobile support (i.e. for touch events) but you need to very careful about the dom you create, so as not to overwhelm the browser.  I wouldn't choose Sproutcore for mobile, although you could if you are very careful.

and blossom compile to native is not acceptable

That does not seem reasonable to me.  To be clear, NONE of these frameworks run natively on mobile devices; they ALL run in the browser.  Blossom comes closes as the canvas API is mapped directly to the native API, giving you a truly native app.  The only way you could get closer would be to use objective-c/java for iOs and Android.
So basically, at this point your left with Sencha(Ext-Js) and Blossom.  Blossom is still in Beta, you would be trailblazing if you tried it.  Sencha is established, has great support (Blossom support is good on irc), and a large developer base.
So Sencha is the choice, unless you really want to be cutting edge, and take a little risk.

A: Troy. Indeed, ember can run with another view layer framework such as jQuery Mobile which can provide a "app-like" look and feel.There is a github project: https://github.com/LuisSala/emberjs-jqm. In my view, if you need very cool animation you can use blossom.If you want to build a app, SC or ember should be OK. I'll choose ember because it 's loosely coupled.


Q: LINQ ignore incorrect type being assigned to property So, I have my own mapper (NOT AutoMapper) which maps models to each other. You give the model you'd like to map to, and with the Map method you push an object in. Beside of this I wrote the Extend method which functions as a override for the Map method to, for example, add properties which are not available in the object being mapped.
Problem:
The problem hereby is that my public Mapper<T> Extend(Func<T, T> func) method doesn't like the different types.

Possible solutions:
There are 2 solutions I'm thinking of:

*

*Ignore the error and map the value within my Extend method. Which isn't possible as far as I know due to the expression being executed immediately.

*Create a LINQ method which maps the value for me. Eg; q => q.Ownership = obj.Ownerships.First().Map().

Question:
How can I resolve this error and achieve what I want?


Q: Wrapper Function for a Recursive Function that takes a "pass by reference" value Here's the question: I'm trying to do,
Node* foo(Node *& ptr, other args) {
  // some work here
}

In the wrapper function, I have to declare a temporary value (which is meaningless):
Node* wrapper( ... ) {
  Node* p = nullptr;
  return foo(p, other args);
}

Is there any way to get rid of the first line in the wrapper function? Thanks!!

A: I guess in foo you assign ptr some value (otherwise the *& has no value). You cannot pass nullptr and you have to declare a pointer like you shown in the wrapper because nullptr is an rvalue. An rvalue is an expression, or an "unnamed object" and you cannot take the address of it. There is more information here Why don't rvalues have an address?.


Q: GCC cosine optimization and sigbus I have a program that writes in some FPGA memory. When the program is compiled with optimizations (either O1, O2 or O3) it crashes with a bus error. However there is no crash when the program is compiled without optimizations.
Here is a minimal example which crashes:
void set_reg(const uint32_t *data)
{
    uint32_t val = data[0];
    dvm.write32(dac_map, 0, static_cast<uint32_t>(8192 * cos(val))); // crash
}

When I add volatile there is no more crash:
void set_reg(const uint32_t *data)
{
    volatile uint32_t val = data[0];
    dvm.write32(dac_map, 0, static_cast<uint32_t>(8192 * cos(val))); // no crash
}

If I remove the call to cos there is no problem.
This seems related to GCC: program doesn't work with compilation option -O3. When I add the flag -ffloat-store the program don't crash.
However, on the actual code which is more complicated, adding the flag -ffloat-store doesn't solve the problem.
I don't understand the kind of optimization GCC does and how this leads to a SIGBUS. If anyone could explain that, it would be useful for debugging.
Thank you.

NB:
1) GCC version is arm-linux-gnueabihf-g++ (Ubuntu/Linaro 5.3.1-14ubuntu2) 5.3.1 20160413
2) The function write32 is defined as
void write32(MemMapID id, uint32_t offset, uint32_t value)
{
    ASSERT_WRITABLE
    *(volatile uintptr_t *) (GetBaseAddr(id) + offset) = value;
}


Q: split textarea value properly jQuery regex I am having problems to properly split textarea value. My current snippet split each line that starts with "-" and displays it as value of span element, but, it wont collect next line value which does not start with "-".
For example if I paste this text into textarea:
- first match
rest of first match
- second match
- third match

Script should output:
- first match rest of first match

- second match

- third match

$(document).ready(function() {
  const regex = /^\s*-\s*/;
  $("#txt").keyup(function() {
    const entered = $('#textarea').val()
    const lines = entered.split(/\n/);

    let spans = "";
    for (const line of lines) {
      if (regex.test(line)) {
        spans += "- " + line.replace(regex, '') + "
";
      }
    }

    $(".results").html(spans);
  });
});
.row {
  background: #f8f9fa;
  margin-top: 20px;
  padding: 10px;
}

.col {
  border: solid 1px #6c757d;
}

      <form>
        <textarea id="textarea" rows="5" cols="60" placeholder="Type something here..."></textarea>
      </form>

So, basically script should split textarea value from line that starts with "-" until next line which starts "-".
Code snippet is also available here: https://jsfiddle.net/zecaffe/f7zv3udh/1/

A: Why not just a split to the \n-?

$(document).ready(function() {

  $("#textarea").keyup(function() {

    const entered = $('#textarea').val()
    const lines = entered.split(/\n-/);

    let spans = "";
    lines.forEach((l,i)=>{
      // remove the first -
      if(i===0 && l[0]==="-") l = l.slice(1)
      spans += "- " + l + "
";
    })

    $(".results").html(spans);
  });
});
.row {
  background: #f8f9fa;
  margin-top: 20px;
  padding: 10px;
}

.col {
  border: solid 1px #6c757d;
}

      <form>
        <textarea id="textarea" rows="5" cols="60" placeholder="Type something here..."></textarea>
      </form>


Q: ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'private_ip' From: Best way to launch aws ec2 instances with ansible
  - name: Add the newly created EC2 instance(s) to the local host group (located inside the directory)
    local_action: lineinfile
                  dest="/etc/ansibles/aws/hosts"
                  regexp={{ item.private_ip }}
                  insertafter="[webserver]" line={{ item.private_ip }}
    with_items: "{{ ec2.instances }}"

creates this error:
fatal: [localhost]: FAILED! => {
    "failed": true,
    "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'private_ip'\n\n
I have defined variable private_ip: under vars , with a value

A: I think that the private_ip property in the code above references to the property of the ec2 variable that's used to catch the returned values from the ec2 module (from the last step), no the one that you defined elsewhere.

  - name: Launch the new EC2 Instance
    local_action: ec2
                  group={{ security_group }}
                  instance_type={{ instance_type}}
                  image={{ image }}
                  wait=true
                  region={{ region }}
                  keypair={{ keypair }}
                  count={{count}}
    register: ec2 (this is where the variable is defined!!!)

Essentially Ansible is complaining that the ec2 variable hasen't got the

attribute 'private_ip'

, so check the preceding code and see how that variable gets defined.
In the example above you're trying to get the private_ip address from aws. Is that really what you want? Most of the time you want the public ip address since that's what you will use to connect to the ec2 machine, provision it, deploy your app etc...


Q: Message/Folder permissions Is there a way to change folder and/or message permissions?
I noticed that folders created on root folder of a user, are not visible - is this a bug or a feature?
Thank you.

A:

I sent a POST request with: URL= outlook.office.com/api/v2.0/me/MailFolders/root/childfolders content inside: { "DisplayName": "ExampleName" } The folder was created successfully, and reachable via API's. However it is not visible in the Outlook WebUI nor in the Outlook application. Is this by design? –

The end-point for the root folder is incorrect, there is no need to use the “root” keyword. And this end-point give the error when I try to create a folder.
Here is an sample to create a folder under the root folder for your reference:
POST: https://outlook.office.com/api/v2.0/me/MailFolders

Header:
authorization: bearer {token}
content-type: application/json

BODY:
{"DisplayName":"FolderName"}

And we will the 201 status code and response like figure below:


Q: calculate values In an order form, each row has 3 fields: quantity, price, total.
How do I create a function that on changing a number the subtotal is calculated and so is the total?
Can anyone suggest a way?

A: You'd need to add a listener to each row so that when the price or quantity are updated, you can get the new quantity and price and update the total column.
In jQuery, something like:
$('.row').on('change', function() {
    var quantity = $('.quantity', this).val(), // get the new quatity
        price = $('.price', this).val(), // get the new price
        total = price*quantity;
    $('.total', this).val(total);  //set the row total

    var totals = $.map($('.row .total'), function(tot) {
        return tot.val(); // get each row total into an array
    }).reduce(function(p,c){return p+c},0); // sum them
    $('#total').val(totals); // set the complete total
});

This assumes that each order form row container has the class row, each quantity has the class quantity, each row total has the class total and the order form total has the id total.


Q: published bot on skype but it's not working I have a bot that I've created by merging LUIS and QnA together in a single project using Microsoft Bot Builder.
I published the bot to an EC2 instance from visual studio and I'm using the Bot Framework Emulator for testing and it works perfectly. (MUST use ngrok for tunneling).
Now I want to deploy the bot on Skype. I logged into the Bot Framework Portal and I registered my bot. Now comes the configuration part.
I'm not quite sure what to set as the HTTP endpoint here.
I found this in the Bot Framework documentation:

Complete the Configuration section of the form.
Provide your bot's HTTPS messaging endpoint. This is the endpoint
  where your bot will receive HTTP POST messages from Bot Connector. If
  you built your bot by using the Bot Builder SDK, the endpoint should
  end with /api/messages.

*

*If you have already deployed your bot to the cloud, specify the endpoint generated from that deployment.

*If you have not yet deployed your bot to the cloud, leave the endpoint blank for now. You will return to the Bot Framework Portal
  later and specify the endpoint after you've deployed your bot.

When I published from Visual Studio, from the Azure App Service Activity windows, I found this line:

Start Web Deploy Publish the Application/package to https://ec2-00-000-000-00.compute-1.amazonaws.com:PORT/msdeploy.axd?site=bots ...

I used that address for the Messaging Endpoint in the configuration and I published my app. However when I'm testing it on Skype, i'm not receiving any messages from the bot.
I don't know what the problem is exactly, does this have something to do with ngrok? Or am I missing a step here, is there something else I should be doing to deploy the bot on Skype? Maybe something to do with the appid/password that I need to use ... i really don't know
Would really appreciate an explanation of how this works exactly. I don't really understand how the whole deployment procedure works exactly, feels like i'm swimming in murky waters.

A: Your endpoint is going to be the root of your deployed web application instance, plus the route that your bot is listening on.
For example, one of my bots is deployed to the free version of Azure Web Sites. The URL for a site such as this is https://APPLICATION_NAME.azurewebsites.net and the route that the bot listens on is the default /api/messages. This makes the endpoint https://APPLICATION_NAME.azurewebsites.net/api/messages.
If you connect directly to your app's endpoint, you should at least get a JSON dump with an error message. To make sure your site is getting deployed, drop an HTML file into the root of EC2 and see if you can access this.


Q: Posting on same form in JSP I want to search for a product...so I have made a form...
but my products are being retreived in the doGet() method
and when I search for a product, the doPost() method is called....
SO what should i Do?

A: It's actually unclear what your problem is. If you want the form submit to be idempotent/bookmarkable, then just remove method="post" from the HTML <form> element if you want the request to be bookmarkable. Don't forget to remove doPost() method from the servlet as well.
Or if you actually want to let the form submit to a different servlet, then just create another servlet, register/map it the same way but on a bit different URL pattern and finally change the action URL of the HTML <form> element.


Q: Custom Gradle Plugin Exec task with extension does not use input properly I am following the Writing Custom Plugins section of the Gradle documentation, specifically the part about Getting input from the build. The following example provided by the documentation works exactly as expected:
apply plugin: GreetingPlugin

greeting.message = 'Hi from Gradle'

class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
        // Add the 'greeting' extension object
        project.extensions.create("greeting", GreetingPluginExtension)
        // Add a task that uses the configuration
        project.task('hello') << {
            println project.greeting.message
        }
    }
}

class GreetingPluginExtension {
    def String message = 'Hello from GreetingPlugin'
}

Output:
> gradle -q hello
Hi from Gradle

I'd like to have the custom plugin execute an external command (using the Exec task), but when changing the task to a type (including types other than Exec such as Copy), the input to the build stops working properly:
// previous and following sections omitted for brevity
project.task('hello', type: Exec) {
    println project.greeting.message
}

Output:
> gradle -q hello
Hello from GreetingPlugin

Does anyone know what the issue could be?

A: It is not related to the type of the task, it's a typical << misunderstanding.
When you write
project.task('hello') << {
    println project.greeting.message
}

and execute gradle hello, the following happens:
configuration phase

*

*apply custom plugin

*create task hello

*set greeting.message = 'Hi from Gradle'

executon phase

*

*run task with empty body

*execute << closure { println project.greeting.message }

in this scenario output is Hi from Gradle
When you write
project.task('hello', type: Exec) {
    println project.greeting.message
}

and execute gradle hello, the following happens
configuration phase

*

*apply custom plugin

*create exec task hello

*execute task init closure println project.greeting.message

*set greeting.message = 'Hi from Gradle' (too late, it was printed in step 3)
the rest of workflow does not matter.

So, small details matter. Here's the explanation of the same topic.

Solution:
void apply(Project project) {
    project.afterEvaluate {
        project.task('hello', type: Exec) {
            println project.greeting.message
        }
    }
}


Q: How to obtain enrollment certificate from CA in PHP I'm writing a service that is supposed to receive DER format PKCS#10 certificate request in Base64 encoding from mobile device and then return certificates obtained  from CA.
I'm trying to use "https://CA-server/certsrv/mscep/mscep.dll?operation=PKIOperation&Message=urlencoded request"
     $ca_link_device="https://..../certsrv/mscep/mscep.dll";
     $URL=$ca_link_device."?operation=PKIOperation&Message=".urlencode($BinarySecurityToken)."=";
     $ch3 = curl_init();
     curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch3, CURLOPT_URL, $URL);
     curl_setopt($ch3, CURLOPT_HEADER, 0);
     $cert = curl_exec($ch3);

but the data that is returned contains empty envelope. I'm most probably doing something really dumb, but unfortunately my knowledge in certificate management is close to zero. I have been trying to google around, but there are so many technical documents around that I don't know from where to start and what is relevant to me and what is not.
All help much appreciated.
Edit: According to one documentation I should wrap my PKCS10 request into PKCS7. According to Microsoft PKCS10 should be fine and PKCS7 is only used for certificate renewal. Who to believe?

A: In the end we just droped the mscep.dll approach and used curl to directly send POST with needed parameters to ...certsrv/certfnsh.asp page. Then we parsed the returned HTML and obtained the link for certificate download.
Not a nice solution, but worked for us.


Q: How to create this in flutter enter image description here
I have tried different ways like transform and rotation but not able do it

A: I think you've been getting some downvotes because you didn't share any of your previous attempts, on which the solution could be built.
I think what you might want to do is use a CustomClipper to create the desired shape. I wrote you a simple one that makes a wedged shape with just 4 points, but you can use Path.arc to make it more like the image you provided:
class WedgeClipper extends CustomClipper<Path> {
  final bool isRight;

  WedgeClipper({this.isRight = false});

  @override
  Path getClip(Size size) {
    Path path = Path();
    // mirror the clip accordingly when it's left or right aligned
    if (isRight) {
      path.addPolygon([
        Offset(0, size.height / 4),
        Offset(size.width, 0),
        Offset(size.width, size.height),
        Offset(0, 3 * size.height / 4)
      ], true);
    } else {
      path.addPolygon([
        Offset(0, 0),
        Offset(size.width, size.height / 4),
        Offset(size.width, 3 * size.height / 4),
        Offset(0, size.height)
      ], true);
    }

    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
    return true;
  }
}

Then to use it in your code, you can do something like:
@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Wedge List View'),
      ),
      body: ListView.builder(
        itemBuilder: (context, index) {
          bool isRightAligned = index % 2 == 0;
          return Padding(
            child: ClipPath(
              child: Material(
                child: SizedBox(
                  height: 80,
                  width: double.maxFinite,
                  child: Row(
                    mainAxisAlignment: isRightAligned ? MainAxisAlignment.end : MainAxisAlignment.start,
                    children: isRightAligned ? [
                    Text('Tile to the right side'),
                    SizedBox(width: 10),
                    Image.network('https://upload.wikimedia.org/wikipedia/commons/b/b1/VAN_CAT.png'),
                  ] : [
                    Image.network('https://upload.wikimedia.org/wikipedia/commons/b/b1/VAN_CAT.png'),
                    SizedBox(width: 10),
                    Text('Tile to the left side'),
                  ],),
                ),
                color: Color(0xffdddddd),
              ),
              clipper: WedgeClipper(
                  isRight: isRightAligned), // alternating left/right clips
            ),
            padding: EdgeInsets.symmetric(horizontal: 8.0),
          );
        },
      ),
    );
  }

It basically draws a rectangle, clips it with the CustomClipper and renders what's left.
The result looks like this:


Q: Inserting image to database I am trying to fetch image from the database, insertion of images are successful but are not displaying when I fetch it.
Here's my code for uploading image
include("p1-connect.php");

if(isset($_POST['upload'])){

$file = $_FILES['picture'];

$fileName = $_FILES['picture']['name'];
$fileTmpName = $_FILES['picture']['tmp_name'];
$fileSize = $_FILES['picture']['size'];
 $fileError = $_FILES['picture']['error'];
 $fileType = $_FILES['picture']['type'];

 $fileExt = explode('.', $fileName);
 $fileActualExt = strtolower(end($fileExt));

$allowed = array('jpg','jpeg','png'); //allowed file types

 if(in_array($fileActualExt,$allowed))
{
    if($fileError === 0){
        if($fileSize < 1000000){

            $fileNameNew = uniqid('',true).".".$fileActualExt;
            $fileDestination = 'uploads/'.$fileNameNew;

            $query = "INSERT INTO image(image,image_name) VALUES('$fileName','$fileTmpName')";

            mysqli_query($connect,$query);
            $images = addslashes(file_get_contents($_FILES['picture']['tmp_name']));

            move_uploaded_file($fileTmpName, $fileDestination);

        }else{
            echo "Your file is too big";
        }

    } else{
        echo "An error uploading your files";
    }

} else{
    echo "You cannot upload files of this type";
}}

For fetching the image

 <form method="post" action="" enctype='multipart/form-data'>
 <input type='file' name='picture' />
 <input type='submit' value='Upload Image' name='upload'>
    <?php

        $sql = "SELECT * FROM image";

        $result =mysqli_query($connection,$sql);

        while($row = mysqli_fetch_array($result)){

            $imagee = $row['image'];}
    ?>

   <img src="<?php echo $imagee; ?>" width="175" height="200"/>

</form>

Only broken image icons are showing
My 'image' table includes:
id - int
image - blob
image_name - varchar
Thank you in advance


Q: Fixed container positioned on top of the body's scroll We are experencing Fixed container positioned on top of the body's scroll ( even with: box-sizing: border-box;), with those styles:
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
z-index: 100;
width: 100%;
height: 71px;
background-color: #115191;
box-shadow: 0 0px 20px 0 rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 0 0px 20px 0 rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 0px 20px 0 rgba(0, 0, 0, 0.1);
font-family: 'Lato', sans-serif;
position: fixed;
top: 0;
box-sizing: border-box;

but if I set the width, like this:
width: calc(100% - 17px )
then is what we expect ( at least in chrome, other browsers/versions must have a different scroll width)

The styles of html tag:
height: 100%;
overflow-y: auto;

body:
padding: 0;
margin: 0;
background-color: #f7f7f7;
min-height: 100%;

any idea wha'ts causing this and how to prevent it?
thanks

A: We need to see all your code, but you probably have margin:0 at the html/body. Without it, it works

html,
body {
  height: 100%;
  overflow-y: auto;
}

.fixed {
  position: fixed;
  height: 70px;
  background-color: blue;
  top: 0;
  width: 100%
}

.content{
  height: 2000px
}

When I add the margin I got the same problem you experience

html,
body {
  height: 100%;
  overflow-y: auto;
  margin: 0;
}

.fixed {
  position: fixed;
  height: 70px;
  background-color: blue;
  top: 0;
  width: 100%
}

.content{
  height: 2000px
}

A: You can remove scroll from html, body elements and add it to content wrapper. In this example it is main element.
Html example

  Header

Remove dafault page scroll
body, html {
  height: 100%;
  overflow: hidden;
}

Add scroll and height for content wrapper
main {
  margin-top: 40px;
  height: calc(100% - 40px);
  overflow: auto;
}

40px here is the height of the fixed header.
header {
  ...
  height: 40px;
  ...
}

body, html {
  height: 100%;
  overflow: hidden;

  /*Some reset styles*/
  margin: 0;
  font-family: sans-serif;
}

header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;

  display: flex;
  align-items: center;

  height: 40px;
  background-color: gainsboro;
}

main {
  margin-top: 40px;
  height: calc(100% - 40px);
  overflow: auto;
}

header, main {
  padding-left: 15px;
  padding-right: 15px;
}
Header

Title

Title 2

Title 3

The Lost World is a novel released in 1912 by Sir Arthur Conan Doyle concerning an expedition to a plateau in the Amazon basin of South America where prehistoric animals (dinosaurs and other extinct creatures) still survive. It was originally published serially in the popular Strand Magazine and illustrated by New-Zealand-born artist Harry Rountree during the months of April–November 1912. The character of Professor Challenger was in thrusting book. The novel also describes a war between indigenous people and a vicious tribe of ape-like creatures.

The Lost World is a novel released in 1912 by Sir Arthur Conan Doyle concerning an expedition to a plateau in the Amazon basin of South America where prehistoric animals (dinosaurs and other extinct creatures) still survive. It was originally published serially in the popular Strand Magazine and illustrated by New-Zealand-born artist Harry Rountree during the months of April–November 1912. The character of Professor Challenger was in thrusting book. The novel also describes a war between indigenous people and a vicious tribe of ape-like creatures.