问:
How to access the database in Helper Functions in CI4
CI4: I have created database object in Controller, i want to execute helper function which has some queries,

Question: How to access the database in Helper Functions in CI4?

答:
You can access the builder from the model.</p>

```<code>$model = new SomeModel();
$builder = $model->builder();
$builder->db  //returns the db conn used in model
</code>```

Body:
You can access the builder from the model.

$model = new SomeModel();
$builder = $model->builder();
$builder->db  //returns the db conn used in model


来源: stackexchange

问:
How do I create a serializer that reuses a unique key of my model?
I'm using Python 3.7, Django 2.2, the Django rest framework, and pytest.  I have the following model, in which I want to re-use an existing model if it exists by its unique key ...

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False, unique=True)

    objects = CoopTypeManager()
```

<p>Then I have created the below serializer to generate this model from REST data</p>

```class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.get_or_create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance
```

<p>However, when I run the below test in which I intentionally use a name that is taken</p>

```@pytest.mark.django_db
def test_coop_type_create_with_existing(self):
    """ Test coop type serizlizer model if there is already a coop type by that name """
    coop_type = CoopTypeFactory()
    serializer_data = {
        "name": coop_type.name,
    }

    serializer = CoopTypeSerializer(data=serializer_data)
    serializer.is_valid()
    print(serializer.errors)
    assert serializer.is_valid(), serializer.errors
    result = serializer.save()
    assert result.name == name
```

<p>I get the below error</p>

```python manage.py test --settings=directory.test_settings
...        ----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_serializers.py", line 46, in test_coop_type_create_with_existing
    assert serializer.is_valid(), serializer.errors
AssertionError: {'name': [ErrorDetail(string='coop type with this name already exists.', code='unique')]}
```

<p>How do I construct my serializer so that I can create my model if its unique key doesn't exist, or re-use it if it does?</p>

<p><b>Edit:</b> Here's the GitHub link ...</p>

```https://github.com/chicommons/maps/tree/master/web
```

答:
DRF validates the uniqueness of each field if is declared with unique=True in the model, so you have to change the model as following if you want to keep your unique contraint for the name field:

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    objects = CoopTypeManager()

    class Meta:
        # Creates a new unique constraint with the `name` field
        constraints = [models.UniqueConstraint(fields=['name'], name='coop_type_unq')]
```

<p>Also, you have to change your serializer, if you're using a ViewSet with the default behavior, you only need to add a custom validation in the serializer.</p>

<pre class="lang-py prettyprint-override"><code>from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from .models import CoopType

class CoopTypeSerializer(serializers.ModelSerializer):
    default_error_messages = {'name_exists': 'The name already exists'}

    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def validate(self, attrs):
        validated_attrs = super().validate(attrs)
        errors = {}

        # check if the new `name` doesn't exist for other db record, this is only for updates
        if (
            self.instance  # the instance to be updated
            and 'name' in validated_attrs  # if name is in the attributes
            and self.instance.name != validated_attrs['name']  # if the name is updated
        ):
            if (
                CoopType.objects.filter(name=validated_attrs['name'])
                .exclude(id=self.instance.id)
                .exists()
            ):
                errors['name'] = self.error_messages['name_exists']

        if errors:
            raise ValidationError(errors)

        return validated_attrs

    def create(self, validated_data):
        # get_or_create returns a tuple with (instance, boolean). The boolean is True if a new instance was created and False otherwise
        return CoopType.objects.get_or_create(**validated_data)[0]
</code>```

The update method was removed because is not needed.

Finally, the tests:

class FactoryTest(TestCase):

    def test_coop_type_create_with_existing(self):
        """ Test coop type serializer model if there is already a coop type by that name """
        coop_type = CoopTypeFactory()
        serializer_data = {
            "name": coop_type.name,
        }

        # Creation
        serializer = CoopTypeSerializer(data=serializer_data)
        serializer.is_valid()
        self.assertTrue(serializer.is_valid(), serializer.errors)
        result = serializer.save()
        assert result.name == serializer_data['name']

        # update with no changes
        serializer = CoopTypeSerializer(coop_type, data=serializer_data)
        serializer.is_valid()
        serializer.save()
        self.assertTrue(serializer.is_valid(), serializer.errors)

        # update with the name changed
        serializer = CoopTypeSerializer(coop_type, data={'name': 'testname'})
        serializer.is_valid()
        serializer.save()
        self.assertTrue(serializer.is_valid(), serializer.errors)
        coop_type.refresh_from_db()
        self.assertEqual(coop_type.name, 'testname')
```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Python 3.7, Django 2.2, the Django rest framework, and pytest.  I have the following model, in which I want to re-use an existing model if it exists by its unique key ...

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False, unique=True)

    objects = CoopTypeManager()

Then I have created the below serializer to generate this model from REST data

class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.get_or_create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance

However, when I run the below test in which I intentionally use a name that is taken

@pytest.mark.django_db
def test_coop_type_create_with_existing(self):
    """ Test coop type serizlizer model if there is already a coop type by that name """
    coop_type = CoopTypeFactory()
    serializer_data = {
        "name": coop_type.name,
    }

    serializer = CoopTypeSerializer(data=serializer_data)
    serializer.is_valid()
    print(serializer.errors)
    assert serializer.is_valid(), serializer.errors
    result = serializer.save()
    assert result.name == name

I get the below error

python manage.py test --settings=directory.test_settings
...        ----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_serializers.py", line 46, in test_coop_type_create_with_existing
    assert serializer.is_valid(), serializer.errors
AssertionError: {'name': [ErrorDetail(string='coop type with this name already exists.', code='unique')]}

How do I construct my serializer so that I can create my model if its unique key doesn't exist, or re-use it if it does?

Edit: Here's the GitHub link ...

https://github.com/chicommons/maps/tree/master/web

Body:
DRF validates the uniqueness of each field if is declared with unique=True in the model, so you have to change the model as following if you want to keep your unique contraint for the name field:

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    objects = CoopTypeManager()

    class Meta:
        # Creates a new unique constraint with the `name` field
        constraints = [models.UniqueConstraint(fields=['name'], name='coop_type_unq')]

Also, you have to change your serializer, if you're using a ViewSet with the default behavior, you only need to add a custom validation in the serializer.

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from .models import CoopType

class CoopTypeSerializer(serializers.ModelSerializer):
    default_error_messages = {'name_exists': 'The name already exists'}

    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def validate(self, attrs):
        validated_attrs = super().validate(attrs)
        errors = {}

        # check if the new `name` doesn't exist for other db record, this is only for updates
        if (
            self.instance  # the instance to be updated
            and 'name' in validated_attrs  # if name is in the attributes
            and self.instance.name != validated_attrs['name']  # if the name is updated
        ):
            if (
                CoopType.objects.filter(name=validated_attrs['name'])
                .exclude(id=self.instance.id)
                .exists()
            ):
                errors['name'] = self.error_messages['name_exists']

        if errors:
            raise ValidationError(errors)

        return validated_attrs

    def create(self, validated_data):
        # get_or_create returns a tuple with (instance, boolean). The boolean is True if a new instance was created and False otherwise
        return CoopType.objects.get_or_create(**validated_data)[0]

The update method was removed because is not needed.

Finally, the tests:

class FactoryTest(TestCase):

    def test_coop_type_create_with_existing(self):
        """ Test coop type serializer model if there is already a coop type by that name """
        coop_type = CoopTypeFactory()
        serializer_data = {
            "name": coop_type.name,
        }

        # Creation
        serializer = CoopTypeSerializer(data=serializer_data)
        serializer.is_valid()
        self.assertTrue(serializer.is_valid(), serializer.errors)
        result = serializer.save()
        assert result.name == serializer_data['name']

        # update with no changes
        serializer = CoopTypeSerializer(coop_type, data=serializer_data)
        serializer.is_valid()
        serializer.save()
        self.assertTrue(serializer.is_valid(), serializer.errors)

        # update with the name changed
        serializer = CoopTypeSerializer(coop_type, data={'name': 'testname'})
        serializer.is_valid()
        serializer.save()
        self.assertTrue(serializer.is_valid(), serializer.errors)
        coop_type.refresh_from_db()
        self.assertEqual(coop_type.name, 'testname')


问:
android gravity right cursor shows left of the input text EditText
I am using Kotlin. I have used gravity right so that input number start from right. But EditText cursor keep stay always left of the input text in EditText. I want to keep gravity right & text right to left.Here is the image

Here is my EditText xml code..

```<code><EditText
        android:id="@+id/et_amount"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="numberDecimal"
        android:ellipsize="end"
        android:gravity="right|center_horizontal|center_vertical"
        android:textStyle="bold"
        android:maxLength="6" >
        <requestFocus />
    </EditText>
</code>```

Please help me so that input text start from left to right & cursor show always right.

答:
try this:

```<code>EditText text = new EditText(context);
    text.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String  text1 = text.getText().toString();
            text.setText(text1);
            text.setSelection(text1.length());
        }
    });
</code>```

it will be work;

hope to help you

Body:
I am using Kotlin. I have used gravity right so that input number start from right. But EditText cursor keep stay always left of the input text in EditText. I want to keep gravity right & text right to left.Here is the image

Here is my EditText xml code..

<EditText
        android:id="@+id/et_amount"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="numberDecimal"
        android:ellipsize="end"
        android:gravity="right|center_horizontal|center_vertical"
        android:textStyle="bold"
        android:maxLength="6" >
        <requestFocus />
    </EditText>

Please help me so that input text start from left to right & cursor show always right.

Body:
try this:

EditText text = new EditText(context);
    text.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String  text1 = text.getText().toString();
            text.setText(text1);
            text.setSelection(text1.length());
        }
    });

it will be work;

hope to help you


问:
adding values and merging json objects based on key in d3js
I have a variable that looks something like this when I do console.log(variable1).

```<code>
    0: {node01: "site05", amount: 1010}
    1: {node01: "site02", amount: 1200}
    2: {node01: "site08", amount: 880}
    3: {node01: "site04", amount: 870}
    4: {node01: "site01", amount: 650}
    5: {node01: "site06", amount: 1370}
    6: {node01: "site07", amount: 100}
    7: {node01: "site09", amount: 210}
    8: {node01: "site10", amount: 340}

</code>```

Another variable which looks like this in console.log(variable2):

```<code>
    0: {node02: "site08", amount: 100}
    1: {node02: "site02", amount: 200}
    2: {node02: "site03", amount: 1050}
    3: {node02: "site07", amount: 1300}
    4: {node02: "site09", amount: 850}
    5: {node02: "site10", amount: 890}
    6: {node02: "site04", amount: 640}
    7: {node02: "site06", amount: 290}
    8: {node02: "site01", amount: 50}
    9: {node02: "site05", amount: 200}
    10: {node02: "site11", amount: 1060}

</code>```

I want to add the amount of both the variables based on the node value
for example,
"node01": "site05" has amount:1010 and "node02": "site05" has amount:200
the resultant variable should have "node":"site05" amount:1210. Also, "site11" doesn't exist in variable1. so it should just have the value "node":"site11" amount:1060 --> this comes only from variable2

I tried using two nested for loops but it just results in nodes available in one variable.
I am not sure how to map them all.
Also, is there a solution using only d3js without using the for loops native to js? as from my understanding, D3 has some other approach to looping

Thanks in advance

答:
I think you'll probably want to prepare your data and then send the consolidated result to D3. For example:

 const list1 = [
   {node01: "site05", amount: 1010},
   {node01: "site02", amount: 1200},
   {node01: "site08", amount: 880},
   {node01: "site04", amount: 870},
   {node01: "site01", amount: 650},
   {node01: "site06", amount: 1370},
   {node01: "site07", amount: 100},
   {node01: "site09", amount: 210},
   {node01: "site10", amount: 340},
];
const list2 = [
    {node02: "site08", amount: 100},
    {node02: "site02", amount: 200},
    {node02: "site03", amount: 1050},
    {node02: "site07", amount: 1300},
    {node02: "site09", amount: 850},
    {node02: "site10", amount: 890},
    {node02: "site04", amount: 640},
    {node02: "site06", amount: 290},
    {node02: "site01", amount: 50},
    {node02: "site05", amount: 200},
    {node02: "site11", amount: 1060},
];

const combinedList = [
  ...list1,
  ...list2,
];

const output = Object.values(combinedList.reduce((a, c) => {
  const node = Object.values(c).find(v => typeof v === 'string');
  a[node] = a[node] || {node, amount: 0};
  a[node].amount += c.amount;
  return a;
}, {}));

console.log(output);```

Body:
I have a variable that looks something like this when I do console.log(variable1).

    0: {node01: "site05", amount: 1010}
    1: {node01: "site02", amount: 1200}
    2: {node01: "site08", amount: 880}
    3: {node01: "site04", amount: 870}
    4: {node01: "site01", amount: 650}
    5: {node01: "site06", amount: 1370}
    6: {node01: "site07", amount: 100}
    7: {node01: "site09", amount: 210}
    8: {node01: "site10", amount: 340}

Another variable which looks like this in console.log(variable2):

    0: {node02: "site08", amount: 100}
    1: {node02: "site02", amount: 200}
    2: {node02: "site03", amount: 1050}
    3: {node02: "site07", amount: 1300}
    4: {node02: "site09", amount: 850}
    5: {node02: "site10", amount: 890}
    6: {node02: "site04", amount: 640}
    7: {node02: "site06", amount: 290}
    8: {node02: "site01", amount: 50}
    9: {node02: "site05", amount: 200}
    10: {node02: "site11", amount: 1060}

I want to add the amount of both the variables based on the node value
for example,
"node01": "site05" has amount:1010 and "node02": "site05" has amount:200
the resultant variable should have "node":"site05" amount:1210. Also, "site11" doesn't exist in variable1. so it should just have the value "node":"site11" amount:1060 --> this comes only from variable2

I tried using two nested for loops but it just results in nodes available in one variable.
I am not sure how to map them all.
Also, is there a solution using only d3js without using the for loops native to js? as from my understanding, D3 has some other approach to looping

Thanks in advance


问:
Debugging multithreaded applications
I have an application written in C++ and MFC which is multithreaded running on windows. Occasionally I do get some complaints such as deadlocks or an unhandled exception which is caused because of these threads. Normally I use visual studio (if the problem is reproducible) or else use the WinDbg to analyse the dump files generated. Is there any better way of doing this? Can  I use some other tools to do this?</p>

答:
Multithreaded system are complex and location of blockages is not made only with appropriate tools. To find the cause of the deadlock you can put a record of the lock / unlock in a table map. When starting an "action lock" you save in the table, when unlock ocours delete the record from the table. At the end of a cycle you can log the state of the table or expect a particular event to do this.

Build this implementation in a dll, so you can use it in other projects too.

OwnerDisplayName: Naveen

ContentLicense: CC BY-SA 2.5

Title: Debugging multithreaded applications

LastEditorDisplayName: Jason S

OwnerDisplayName: lsalamon


问:
where is data stored?
i am designing a project in .net 4.0 using mvc3. I am using two attribute name and fname(father name).

my controller class:

loginController.cs

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class loginController : Controller
    {
        private logindata db = new logindata();

        //
        // GET: /login/

        public ViewResult Index()
        {
            return View(db.loginobj.ToList());
        }

        //
        // GET: /login/Details/5

        public ViewResult Details(int id)
        {
          //  login login = db.loginobj.Find(id);
            login login = db.loginobj.Find(2) ;
            return View(login);
        }

        //
        // GET: /login/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /login/Create

        [HttpPost]
        public ActionResult Create(login login)
        {
            if (ModelState.IsValid)
            {
                db.loginobj.Add(login);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(login);
        }

        //
        // GET: /login/Edit/5

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
</code>```

model class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
login.cs

namespace MvcMovie.Models
{
    public class login
    {
        public int ID { get; set; }
        public string name{get; set;}
        public string fname { get; set; }
    }
    public class logindata : DbContext
    {
        public DbSet<login> loginobj { get; set; }
    }
}
</code>```

view.cshtml

```<code>@model IEnumerable<MvcMovie.Models.login>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            name
        </th>
        <th>
            fname
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fname)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>
</code>```

I want to ask that where is data stored which is created by me? means how can I see that table of entries which is done by me?

whenever i click of .sdf file then there is a problem occured as shown in following picture, what should i do to solve this problem. should i installed something. i installed visual studio 2010 and sql server 2008.

答: Probably you're using Microsoft SQL CE to store your application data. If this is the case, take a look at the App_Data folder in Solution Explorer. You should see a file with .sdf extension there. Just make sure to select Show All Files icon in Solution Explorer. More details here.

ContentLicense: CC BY-SA 3.0

Title: where is data stored?

Body:
i am designing a project in .net 4.0 using mvc3. I am using two attribute name and fname(father name).

my controller class:

loginController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class loginController : Controller
    {
        private logindata db = new logindata();

        //
        // GET: /login/

        public ViewResult Index()
        {
            return View(db.loginobj.ToList());
        }

        //
        // GET: /login/Details/5

        public ViewResult Details(int id)
        {
          //  login login = db.loginobj.Find(id);
            login login = db.loginobj.Find(2) ;
            return View(login);
        }

        //
        // GET: /login/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /login/Create

        [HttpPost]
        public ActionResult Create(login login)
        {
            if (ModelState.IsValid)
            {
                db.loginobj.Add(login);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(login);
        }

        //
        // GET: /login/Edit/5

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

model class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
login.cs

namespace MvcMovie.Models
{
    public class login
    {
        public int ID { get; set; }
        public string name{get; set;}
        public string fname { get; set; }
    }
    public class logindata : DbContext
    {
        public DbSet<login> loginobj { get; set; }
    }
}

view.cshtml

@model IEnumerable<MvcMovie.Models.login>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            name

            fname

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.name)

            @Html.DisplayFor(modelItem => item.fname)

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

}

I want to ask that where is data stored which is created by me? means how can I see that table of entries which is done by me?

whenever i click of .sdf file then there is a problem occured as shown in following picture, what should i do to solve this problem. should i installed something. i installed visual studio 2010 and sql server 2008.


问:
Why auto running my python script on startup not working?
I want to Add a Python script to windows which runs on every start-up so that the python script will run as the windows boots up creating a hello.txt file every time. What I'm facing is this issue:

When I run this file manually, it works fine by creating the hello.txt file. Then I delete the hello.txt file and restart the PC so as to check if it's workin' properly or not. And then it didn't work i.e it didn't created that file now!

Where I am wrong?

Here's my code:

```<code>import winreg as reg
from winreg import HKEY_CURRENT_USER
import os

def AddToRegistry():

    def my_funct():
        with open(r"C:\Users\username\Desktop\hello.txt", "w+") as test_file:
            test_file.write(r'start here')

    address = my_funct()

    # key we want to change is HKEY_CURRENT_USER
    # key value is Software\Microsoft\Windows\CurrentVersion\Run
    key = HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

    # open the key to make changes to
    openfile = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)

    # modifiy the opened key
    reg.SetValueEx(openfile,"Testingit",0,reg.REG_SZ,address)

if __name__=="__main__":
    AddToRegistry()

</code>```

But when I create the same program with two different files it works:

```<code>import winreg as reg
from winreg import HKEY_CURRENT_USER
import os

def AddToRegistry():

    # name of the python file with extension
    my_funct = r"C:\Users\intel\Desktop\Python programs\testing.py"
    # joins the file name to end of path address
    address = my_funct

    # key we want to change is HKEY_CURRENT_USER
    # key value is Software\Microsoft\Windows\CurrentVersion\Run
    key = HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

    # open the key to make changes to
    openfile = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)

    # modifiy the opened key
    reg.SetValueEx(openfile,"Testing_it",0,reg.REG_SZ,address)

# Driver Code
if __name__=="__main__":
    AddToRegistry()

</code>```

Testing.py

```<code>with open(r"C:\Users\intel\Desktop\hello.txt", "w+") as test_file:
    test_file.write(r'start')

</code>```

答:
I figured it out by my own & now it's solved! Instead of adding testing.py to the winreg I add the file itself i.e. background.py to the registry and now it's working.

I just simply changed the file name and added a function to it. Here's how:

```<code>import winreg as reg
from winreg import HKEY_CURRENT_USER
import os

def AddToRegistry():

    # name of the python file with extension
    my_funct = r"C:\Users\intel\Desktop\Python programs\background.py"

    # joins the file name to end of path address
    address = my_funct

    def the_task():
        with open(r"C:\Users\intel\Desktop\hello.txt", "w+") as test_file:
            test_file.write(r'start')

    the_task()

    # key we want to change is HKEY_CURRENT_USER
    # key value is Software\Microsoft\Windows\CurrentVersion\Run
    key = HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

    # open the key to make changes to
    openfile = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)

    # modifiy the opened key
    reg.SetValueEx(openfile,"Testing_it",0,reg.REG_SZ,address)

    inputs = input(">> ")

# Driver Code
if __name__=="__main__":
    AddToRegistry()

</code>```

Body:
I want to Add a Python script to windows which runs on every start-up so that the python script will run as the windows boots up creating a hello.txt file every time. What I'm facing is this issue:

When I run this file manually, it works fine by creating the hello.txt file. Then I delete the hello.txt file and restart the PC so as to check if it's workin' properly or not. And then it didn't work i.e it didn't created that file now!

Where I am wrong?

Here's my code:

import winreg as reg
from winreg import HKEY_CURRENT_USER
import os

def AddToRegistry():

    def my_funct():
        with open(r"C:\Users\username\Desktop\hello.txt", "w+") as test_file:
            test_file.write(r'start here')

    address = my_funct()

    # key we want to change is HKEY_CURRENT_USER
    # key value is Software\Microsoft\Windows\CurrentVersion\Run
    key = HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

    # open the key to make changes to
    openfile = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)

    # modifiy the opened key
    reg.SetValueEx(openfile,"Testingit",0,reg.REG_SZ,address)

if __name__=="__main__":
    AddToRegistry()

But when I create the same program with two different files it works:

import winreg as reg
from winreg import HKEY_CURRENT_USER
import os

def AddToRegistry():

    # name of the python file with extension
    my_funct = r"C:\Users\intel\Desktop\Python programs\testing.py"
    # joins the file name to end of path address
    address = my_funct

    # key we want to change is HKEY_CURRENT_USER
    # key value is Software\Microsoft\Windows\CurrentVersion\Run
    key = HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

    # open the key to make changes to
    openfile = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)

    # modifiy the opened key
    reg.SetValueEx(openfile,"Testing_it",0,reg.REG_SZ,address)

# Driver Code
if __name__=="__main__":
    AddToRegistry()

Testing.py

with open(r"C:\Users\intel\Desktop\hello.txt", "w+") as test_file:
    test_file.write(r'start')

Body:
I figured it out by my own & now it's solved! Instead of adding testing.py to the winreg I add the file itself i.e. background.py to the registry and now it's working.

I just simply changed the file name and added a function to it. Here's how:

import winreg as reg
from winreg import HKEY_CURRENT_USER
import os

def AddToRegistry():

    # name of the python file with extension
    my_funct = r"C:\Users\intel\Desktop\Python programs\background.py"

    # joins the file name to end of path address
    address = my_funct

    def the_task():
        with open(r"C:\Users\intel\Desktop\hello.txt", "w+") as test_file:
            test_file.write(r'start')

    the_task()

    # key we want to change is HKEY_CURRENT_USER
    # key value is Software\Microsoft\Windows\CurrentVersion\Run
    key = HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

    # open the key to make changes to
    openfile = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)

    # modifiy the opened key
    reg.SetValueEx(openfile,"Testing_it",0,reg.REG_SZ,address)

    inputs = input(">> ")

# Driver Code
if __name__=="__main__":
    AddToRegistry()


问:
How to get the object with the first next date from an array in Nuxt.js / Vue.js?
I want to get the object with the first next date from an array in Nuxt.js.

I'm showing the object manually with the method below in the computed section:

```<code>showObject(){
    const myData = Object.keys(this.fixtures).map(key => this.fixtures[key]);
    return myData.find(x => x.teams.home.uid === this.teamID && x._dt.date === '04/06/2020');
}
</code>```

This means I have to keep changing the date.

I want to check the objects in the array and see which object is the next one to get.

Tried with @nuxtjs/moment but I failed.

How can I solve this?

答:
You need to bring your array into an order which relies on the sequence of the dates. You can do this with a custom sort function. Then, you can just increase the index by one and access the next element in the array.

Here is an example of how to sort the array by date.

const array = [{
  date: new Date(),
  value: 123
}, {
  date: new Date(),
  value: 321
}, {
  date: new Date(),
  value: 'test'
}];

console.log(array.sort((a, b) => {
  return a.date - b.date;
}));```

See also this StackOverflow answer.

Body:
I want to get the object with the first next date from an array in Nuxt.js.

I'm showing the object manually with the method below in the computed section:

showObject(){
    const myData = Object.keys(this.fixtures).map(key => this.fixtures[key]);
    return myData.find(x => x.teams.home.uid === this.teamID && x._dt.date === '04/06/2020');
}

This means I have to keep changing the date.

I want to check the objects in the array and see which object is the next one to get.

Tried with @nuxtjs/moment but I failed.

How can I solve this?

Body:
You need to bring your array into an order which relies on the sequence of the dates. You can do this with a custom sort function. Then, you can just increase the index by one and access the next element in the array.

Here is an example of how to sort the array by date.

const array = [{
  date: new Date(),
  value: 123
}, {
  date: new Date(),
  value: 321
}, {
  date: new Date(),
  value: 'test'
}];

console.log(array.sort((a, b) => {
  return a.date - b.date;
}));

See also this StackOverflow answer.


问:
"No Content-Security-Policy meta tag found." error in my phonegap application
After update Cordova 5.0 in my system, I create new applications. When I tested my application on a device that time I get an error in the console log:

```<code>No Content-Security-Policy meta tag found.
Please add one when using the Cordova-plugin-whitelist plugin.: 23.
</code>```

I add meta in the head section

```<code><meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src: 'self' 'unsafe-inline' 'unsafe-eval'>
</code>```

But again, I got the same error, in the application I use in-app browser plugin and 7 of other website links.

答:
There is an another issue about connection. Some android versions can connect but some cannot. So there is an another solution

in AndroidManifest.xml:

<application ... android:usesCleartextTraffic="true">
        ...
    </application>```

Just add 'android:usesCleartextTraffic="true"'

and problem solved finally.

Body:
After update Cordova 5.0 in my system, I create new applications. When I tested my application on a device that time I get an error in the console log:

No Content-Security-Policy meta tag found.
Please add one when using the Cordova-plugin-whitelist plugin.: 23.

I add meta in the head section

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src: 'self' 'unsafe-inline' 'unsafe-eval'>

But again, I got the same error, in the application I use in-app browser plugin and 7 of other website links.

Body:
There is an another issue about connection. Some android versions can connect but some cannot. So there is an another solution

in AndroidManifest.xml:

<application ... android:usesCleartextTraffic="true">
        ...
    </application>

Just add 'android:usesCleartextTraffic="true"'

and problem solved finally.


问:
Convert nested array of objects to object of key-value pairs using reducer
I have an observable output like below. I want to convert this data to desired format(proivded below). I am partially successful forming key value pairs but couldn't figure out how to send only one field(that is for which selected is true) from the cars array to final output.

***Observable Output****

```<code>[{
  "name":"John",
  "age":30,
  "cars": [
      { "selected":true,  "name":"Ford", "models": "Mustang"},
      { "selected":false, "name":"BMW", "models": "320" },
      { "selected":true, "name":"Fiat", "models":"500" }
  ]
 },
 {
  "name":"alex",
  "age":40,
  "cars": [
      { "selected":true,  "name":"tesla", "models": "x"},
      { "selected":false, "name":"merc", "models": "300" },
      { "selected":true, "name":"honda", "models":"accord" }
   ]
  }
]
</code>```

****Desired Format*****

```<code>{John:[ford, fiat], Alex:[tesla,honda]}
</code>```

***Code used*****

```<code>const results = item.reduce((r,{name,cars}) => (r[name]=cars,r), {})
</code>```

//This gives me complete cars object but i need only name from it(and that too for selected true ones).

Edit 1: Do not want to have empty record in the final object. For eg, if Alex does not have any Cars Selected True then i do not want Alex:[] in the final object.

答:
use forEach and build an object

Update: another solution using reduce

data = [
  {
    name: "John",
    age: 30,
    cars: [
      { selected: true, name: "Ford", models: "Mustang" },
      { selected: false, name: "BMW", models: "320" },
      { selected: true, name: "Fiat", models: "500" },
    ],
  },
  {
    name: "alex",
    age: 40,
    cars: [
      { selected: false, name: "tesla", models: "x" },
      { selected: false, name: "merc", models: "300" },
      { selected: false, name: "honda", models: "accord" },
    ],
  },
];

const output = data.reduce((acc, { name, cars }) => {
  const items = cars.filter(({selected}) => selected).map(({name}) => name);
  if (items.length > 0) {
     acc[name] = items;
  }
  return acc;
}, {});

console.log(output);```

Body:
I have an observable output like below. I want to convert this data to desired format(proivded below). I am partially successful forming key value pairs but couldn't figure out how to send only one field(that is for which selected is true) from the cars array to final output.

***Observable Output****

[{
  "name":"John",
  "age":30,
  "cars": [
      { "selected":true,  "name":"Ford", "models": "Mustang"},
      { "selected":false, "name":"BMW", "models": "320" },
      { "selected":true, "name":"Fiat", "models":"500" }
  ]
 },
 {
  "name":"alex",
  "age":40,
  "cars": [
      { "selected":true,  "name":"tesla", "models": "x"},
      { "selected":false, "name":"merc", "models": "300" },
      { "selected":true, "name":"honda", "models":"accord" }
   ]
  }
]

****Desired Format*****

{John:[ford, fiat], Alex:[tesla,honda]}

***Code used*****

const results = item.reduce((r,{name,cars}) => (r[name]=cars,r), {})

//This gives me complete cars object but i need only name from it(and that too for selected true ones).

Edit 1: Do not want to have empty record in the final object. For eg, if Alex does not have any Cars Selected True then i do not want Alex:[] in the final object.


问:
Python calendar with loops
```<code>days = int(input("Enter number of days: "))
day_of_week = input("The first day of the week: ")

print("{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}".format("S","M","T","W","Th","F","S"))

for d in range(1, days + 1):
  print("{:3}".format(d),end="")
  if (d %  7 == 0):
    print()
</code>```

Here's my output:

I'm confused... What should I add so that the first day of the week is my input's?

答:
Below is one solution that actually uses the start day that you enter. You'll notice a couple of other improvements as well, specifically:

using an array of days for validation (I've made them match my sensibilities of two characters each but they'll work with the same entries you originally had);

using that same array for figuring out where the month should start;

also using it for simplifying the heading output;

validates the number of days to output;

adds a final newline output; and

uses f-strings for formatting (I prefer this because it localises the value to where it should be, rather than way out to the right somewhere in the format() parameter area, where you have to go searching for it).

The code is:

```<code># Valid day list, adjust as necessary.

day_list = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]

# Get days in month, with validation.

days = -1
while days < 1 or days > 31:
    try:
        days = int(input("Enter number of days: "))
        if days < 28 or days > 31:
            days = -1
    except ValueError:
        days = -1

# Get starting day, with validation.

start_day = ""
while start_day not in day_list:
    start_day = input(f"The first day of the week ({', '.join(day_list)}): ")

# Output heading line.

for day in day_list:
    print(f"{day:>3}", end="")
print()

# Pad with spaces in first week if needed.

start_pos = day_list.index(start_day)
for _ in range(start_pos):
    print("   ", end="")

# Output each day, wrapping to new week if needed.

for day in range(1, days + 1):
    if (start_pos != 0 and start_pos %  7 == 0):
        print()
    print(f"{day:3}", end="")
    start_pos += 1

# Output final newline.

print()
</code>```

A couple of sample runs:

```<code>Enter number of days: 27
Enter number of days: 32
Enter number of days: 28
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): blah
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): Mo
 Su Mo Tu We Th Fr Sa
     1  2  3  4  5  6
  7  8  9 10 11 12 13
 14 15 16 17 18 19 20
 21 22 23 24 25 26 27
 28

Enter number of days: 30
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): Su
 Su Mo Tu We Th Fr Sa
  1  2  3  4  5  6  7
  8  9 10 11 12 13 14
 15 16 17 18 19 20 21
 22 23 24 25 26 27 28
 29 30

Enter number of days: 29
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): Sa
 Su Mo Tu We Th Fr Sa
                    1
  2  3  4  5  6  7  8
  9 10 11 12 13 14 15
 16 17 18 19 20 21 22
 23 24 25 26 27 28 29
</code>```

Title: Python calendar with loops

Body:
days = int(input("Enter number of days: "))
day_of_week = input("The first day of the week: ")

print("{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}".format("S","M","T","W","Th","F","S"))

for d in range(1, days + 1):
  print("{:3}".format(d),end="")
  if (d %  7 == 0):
    print()

Here's my output:

I'm confused... What should I add so that the first day of the week is my input's?

Body:
Below is one solution that actually uses the start day that you enter. You'll notice a couple of other improvements as well, specifically:

using an array of days for validation (I've made them match my sensibilities of two characters each but they'll work with the same entries you originally had);

using that same array for figuring out where the month should start;

also using it for simplifying the heading output;

validates the number of days to output;

adds a final newline output; and

uses f-strings for formatting (I prefer this because it localises the value to where it should be, rather than way out to the right somewhere in the format() parameter area, where you have to go searching for it).

The code is:

# Valid day list, adjust as necessary.

day_list = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]

# Get days in month, with validation.

days = -1
while days < 1 or days > 31:
    try:
        days = int(input("Enter number of days: "))
        if days < 28 or days > 31:
            days = -1
    except ValueError:
        days = -1

# Get starting day, with validation.

start_day = ""
while start_day not in day_list:
    start_day = input(f"The first day of the week ({', '.join(day_list)}): ")

# Output heading line.

for day in day_list:
    print(f"{day:>3}", end="")
print()

# Pad with spaces in first week if needed.

start_pos = day_list.index(start_day)
for _ in range(start_pos):
    print("   ", end="")

# Output each day, wrapping to new week if needed.

for day in range(1, days + 1):
    if (start_pos != 0 and start_pos %  7 == 0):
        print()
    print(f"{day:3}", end="")
    start_pos += 1

# Output final newline.

print()

A couple of sample runs:

Enter number of days: 27
Enter number of days: 32
Enter number of days: 28
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): blah
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): Mo
 Su Mo Tu We Th Fr Sa
     1  2  3  4  5  6
  7  8  9 10 11 12 13
 14 15 16 17 18 19 20
 21 22 23 24 25 26 27
 28

Enter number of days: 30
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): Su
 Su Mo Tu We Th Fr Sa
  1  2  3  4  5  6  7
  8  9 10 11 12 13 14
 15 16 17 18 19 20 21
 22 23 24 25 26 27 28
 29 30

Enter number of days: 29
The first day of the week (Su, Mo, Tu, We, Th, Fr, Sa): Sa
 Su Mo Tu We Th Fr Sa
                    1
  2  3  4  5  6  7  8
  9 10 11 12 13 14 15
 16 17 18 19 20 21 22
 23 24 25 26 27 28 29


答:
You can use itertools.groupby (it is part of standard library) - it does pretty much what you did under the hood (grouping together sequences of elements for which the key function gives same output). It can look like the following:

```<code>import itertools

def select_month(item):
    return item[0].split('/')[1]

def get_value(item):
    return item[1]

result = [(month, sum(map(get_value, group)))
            for month, group in itertools.groupby(sorted(sum_weekly), select_month)]
print(result)
</code>```

Title: Group items in a list and calculate sums

Body:
I have a list with weekly figures and need to obtain the grouped totals by month.

The following code does the job, but there should be a more pythonic way of doing it with using the  standard libraries.
The drawback of the code below is that the list needs to be in sorted order.

#Test data (not sorted)
sum_weekly=[('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89),
 ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08', 85),
  ('2020/04/19', 6), ('2020/04/26', 5), ('2020/05/03', 14),
 ('2020/05/10', 5), ('2020/05/17', 20), ('2020/05/24', 28),('2020/03/15', 56), ('2020/03/29', 5), ('2020/04/12', 2),]

month = sum_weekly[0][0].split('/')[1]
count=0
out=[]
for item in sum_weekly:
    m_sel = item[0].split('/')[1]
    if m_sel!=month:
        out.append((month, count))
        count=item[1]
    else:
        count+=item[1]
    month = m_sel
out.append((month, count))

# monthly sums output as ('01', 242), ('02', 360), ('03', 220), ('04', 13), ('05', 67)
print (out)

Body:
You can use itertools.groupby (it is part of standard library) - it does pretty much what you did under the hood (grouping together sequences of elements for which the key function gives same output). It can look like the following:

import itertools

def select_month(item):
    return item[0].split('/')[1]

def get_value(item):
    return item[1]

result = [(month, sum(map(get_value, group)))
            for month, group in itertools.groupby(sorted(sum_weekly), select_month)]
print(result)


问:
What causes the shape error in numpy.dot when a vector is multiplied with a matrix?
```<code>a= [1, 2, 3, 2.5]
b= [[0.2, 0.8, -0.5, 1.0],
    [0.5, -0.91, 0.26, -0.5],
    [-0.26, -0.27, 0.17, 0.87]]

print(np.dot(b,a))
print(np.dot(a,b))
</code>```

Why does the first line print but the second line cause a shape alignment error?

"ValueError: shapes (4,) and (3,4) not aligned: 4 (dim 0) != 3 (dim 0)"

What calculation is numpy trying to do that will cause that error?

Note - I understand matrix multiplication.

Thanks for any help you can give!

Edit - Fixed some variable names

答:
Your example is one case from the np.dot docs:

```<code>dot(a, b, out=None)

Dot product of two arrays. Specifically,

- If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
  the last axis of `a` and `b`.
</code>```

It does not list a case for a 1-D and b N-D.

```<code>In [106]: a= np.array([1, 2, 3, 2.5])
     ...: b= np.array([[0.2, 0.8, -0.5, 1.0],
     ...:     [0.5, -0.91, 0.26, -0.5],
     ...:     [-0.26, -0.27, 0.17, 0.87]])
In [107]: a.shape, b.shape
Out[107]: ((4,), (3, 4))
In [108]: np.dot(b, a)
Out[108]: array([ 2.8  , -1.79 ,  1.885])
</code>```

in einsum notation, note the common j index (last axis of both)

```<code>In [109]: np.einsum('ij,j->i', b, a)
Out[109]: array([ 2.8  , -1.79 ,  1.885])
</code>```

a can be 1d, but it is paired with the 2nd to the last dimension of b, so we have transpose it to match (4,) with (4,3):

```<code>In [113]: np.einsum('i,ij', a, b.T)
Out[113]: array([ 2.8  , -1.79 ,  1.885])
In [114]: np.dot(a,b.T)
Out[114]: array([ 2.8  , -1.79 ,  1.885])
</code>```

@, matmul describes the 1d array case in a differently, but the result is the same:

```<code>- If the first argument is 1-D, it is promoted to a matrix by
  prepending a 1 to its dimensions. After matrix multiplication
  the prepended 1 is removed.
- If the second argument is 1-D, it is promoted to a matrix by
  appending a 1 to its dimensions. After matrix multiplication
  the appended 1 is removed.

In [117]: b@a
Out[117]: array([ 2.8  , -1.79 ,  1.885])
In [118]: a@b.T
Out[118]: array([ 2.8  , -1.79 ,  1.885])
</code>```

Body:
a= [1, 2, 3, 2.5]
b= [[0.2, 0.8, -0.5, 1.0],
    [0.5, -0.91, 0.26, -0.5],
    [-0.26, -0.27, 0.17, 0.87]]

print(np.dot(b,a))
print(np.dot(a,b))

Why does the first line print but the second line cause a shape alignment error?

"ValueError: shapes (4,) and (3,4) not aligned: 4 (dim 0) != 3 (dim 0)"

What calculation is numpy trying to do that will cause that error?

Note - I understand matrix multiplication.

Thanks for any help you can give!

Edit - Fixed some variable names

Body:
Your example is one case from the np.dot docs:

dot(a, b, out=None)

Dot product of two arrays. Specifically,

- If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
  the last axis of `a` and `b`.

It does not list a case for a 1-D and b N-D.

In [106]: a= np.array([1, 2, 3, 2.5])
     ...: b= np.array([[0.2, 0.8, -0.5, 1.0],
     ...:     [0.5, -0.91, 0.26, -0.5],
     ...:     [-0.26, -0.27, 0.17, 0.87]])
In [107]: a.shape, b.shape
Out[107]: ((4,), (3, 4))
In [108]: np.dot(b, a)
Out[108]: array([ 2.8  , -1.79 ,  1.885])

in einsum notation, note the common j index (last axis of both)

In [109]: np.einsum('ij,j->i', b, a)
Out[109]: array([ 2.8  , -1.79 ,  1.885])

a can be 1d, but it is paired with the 2nd to the last dimension of b, so we have transpose it to match (4,) with (4,3):

In [113]: np.einsum('i,ij', a, b.T)
Out[113]: array([ 2.8  , -1.79 ,  1.885])
In [114]: np.dot(a,b.T)
Out[114]: array([ 2.8  , -1.79 ,  1.885])

@, matmul describes the 1d array case in a differently, but the result is the same:

- If the first argument is 1-D, it is promoted to a matrix by
  prepending a 1 to its dimensions. After matrix multiplication
  the prepended 1 is removed.
- If the second argument is 1-D, it is promoted to a matrix by
  appending a 1 to its dimensions. After matrix multiplication
  the appended 1 is removed.

In [117]: b@a
Out[117]: array([ 2.8  , -1.79 ,  1.885])
In [118]: a@b.T
Out[118]: array([ 2.8  , -1.79 ,  1.885])


问:
How to debug an Android APK on a Genymotion emulator from a Linux command line?
I am using a Genymotion (VirtualBox) Android emulator. When I'm trying to attach a JDB to a running Android app from a command line, I get a java.io.IOException: handshake failed - connection prematurally closed delight, namely:

```<code>$ adb jdwp
...
1720
1744
^C
$ adb forward tcp:1234 jdwp:1744
$ adb forward --list
192.168.56.105:5555 tcp:1234 jdwp:1744

$ ss -t -a | grep 1234
LISTEN 0      128        127.0.0.1:1234           0.0.0.0:*

$ ifconfig
...
vboxnet0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.1  netmask 255.255.255.0  broadcast 192.168.56.255
        inet6 fe80::800:27ff:fe00:0  prefixlen 64  scopeid 0x20<link>
        ether 0a:00:27:00:00:00  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 243  bytes 48382 (47.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

$ jdb -attach localhost:1234
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true
java.io.IOException: handshake failed - connection prematurally closed
        at jdk.jdi/com.sun.tools.jdi.SocketTransportService.handshake(SocketTransportService.java:142)
        at jdk.jdi/com.sun.tools.jdi.SocketTransportService.attach(SocketTransportService.java:255)
        at jdk.jdi/com.sun.tools.jdi.GenericAttachingConnector.attach(GenericAttachingConnector.java:119)
        at jdk.jdi/com.sun.tools.jdi.SocketAttachingConnector.attach(SocketAttachingConnector.java:83)
        at jdk.jdi/com.sun.tools.example.debug.tty.VMConnection.attachTarget(VMConnection.java:519)
        at jdk.jdi/com.sun.tools.example.debug.tty.VMConnection.open(VMConnection.java:328)
        at jdk.jdi/com.sun.tools.example.debug.tty.Env.init(Env.java:63)
        at jdk.jdi/com.sun.tools.example.debug.tty.TTY.main(TTY.java:1095)

Fatal error:
Unable to attach to target VM.
</code>```

Using the Android Studio IDE/GUI, however, I am able to attach a debugger with a click of the button. Can't debug with the Android Studio giving my situation.

答: It appears that it's the Android Studio itself causing this problem... Also killing the adb server with the Android Studio running, makes the adb server to automatically restart. The solution here is not to run the Android Studio doing a JDB session from the command line.</p>

Body:
I am using a Genymotion (VirtualBox) Android emulator. When I'm trying to attach a JDB to a running Android app from a command line, I get a java.io.IOException: handshake failed - connection prematurally closed delight, namely:

$ adb jdwp
...
1720
1744
^C
$ adb forward tcp:1234 jdwp:1744
$ adb forward --list
192.168.56.105:5555 tcp:1234 jdwp:1744

$ ss -t -a | grep 1234
LISTEN 0      128        127.0.0.1:1234           0.0.0.0:*

$ ifconfig
...
vboxnet0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.1  netmask 255.255.255.0  broadcast 192.168.56.255
        inet6 fe80::800:27ff:fe00:0  prefixlen 64  scopeid 0x20<link>
        ether 0a:00:27:00:00:00  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 243  bytes 48382 (47.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

$ jdb -attach localhost:1234
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true
java.io.IOException: handshake failed - connection prematurally closed
        at jdk.jdi/com.sun.tools.jdi.SocketTransportService.handshake(SocketTransportService.java:142)
        at jdk.jdi/com.sun.tools.jdi.SocketTransportService.attach(SocketTransportService.java:255)
        at jdk.jdi/com.sun.tools.jdi.GenericAttachingConnector.attach(GenericAttachingConnector.java:119)
        at jdk.jdi/com.sun.tools.jdi.SocketAttachingConnector.attach(SocketAttachingConnector.java:83)
        at jdk.jdi/com.sun.tools.example.debug.tty.VMConnection.attachTarget(VMConnection.java:519)
        at jdk.jdi/com.sun.tools.example.debug.tty.VMConnection.open(VMConnection.java:328)
        at jdk.jdi/com.sun.tools.example.debug.tty.Env.init(Env.java:63)
        at jdk.jdi/com.sun.tools.example.debug.tty.TTY.main(TTY.java:1095)

Fatal error:
Unable to attach to target VM.

Using the Android Studio IDE/GUI, however, I am able to attach a debugger with a click of the button. Can't debug with the Android Studio giving my situation.


问:
how to solve exoplay2 delayed currentposition?
When I stop audio and restart using playWhenReady, there is a little bit delay about the position. For example, The position(when I stop the audio) is 1000. But when I restart changing playWhenReady true, the position is 2000. Because of this, My progressbar is not progressed smoothly. Is there any solution about this?

```<code>                    if (activeHolder!! == holder) {
                        when (player!!.playWhenReady) {
                            true -> {
                                showLog("player!!.duration, playWhenReady true :"+player!!.duration)
                                showLog("player!!.currentPosition, playWhenReady true :"+player!!.currentPosition)

                                player!!.playWhenReady = false
                                handlerChangeProgress.removeCallbacks(updateChangeProgressTask)
                                showAudioStartButton(activeHolder!!)
                                return
                            }
                            false -> {
                                showLog("player!!.duration, playWhenReady false :"+player!!.duration)
                                showLog("player!!.currentPosition, playWhenReady false :"+player!!.currentPosition)

                                player!!.playWhenReady = true
                                handlerChangeProgress.postDelayed(updateChangeProgressTask, delayChangeProgress)
                                showAudioStopButton(activeHolder!!)
                                return
                            }

                        }
                    }

    override fun onChangeProgressBar(progress: Float, currentPosition: Int, totalDuration: Int) {
        if(player!!.playWhenReady) {

            if (activeHolder?.adapterPosition == audioPosition) {
                activeHolder?.let {
                    it.binding.progressBar.max = player!!.duration.toInt()
                    it.binding.progressBar.progress = player!!.currentPosition.toInt()
                    showAudioStopButton(it)
                }
            }
        }
    }

    private val updateChangeProgressTask: Runnable = object : Runnable {
        override fun run() {
            if(player != null && changeProgressPlayerListener != null) {
                val totalDuration: Long = player!!.duration
                val currentPosition: Long = player!!.currentPosition
                val progress = currentPosition.toFloat() / totalDuration.toFloat()
                changeProgressPlayerListener!!.onChangeProgressBar(progress, currentPosition.toInt(), totalDuration.toInt())
            }
            handlerChangeProgress.postDelayed(this, delayChangeProgress)
        }
    }

</code>```

Log

```<code>D/TAG: player!!.duration, playWhenReady false :4166
D/TAG: player!!.currentPosition, playWhenReady false :2459
D/TAG: player!!.duration, playWhenReady true :4166
D/TAG: player!!.currentPosition, playWhenReady true :2640
</code>```

答:
when playWhenReady is true,reset the progress to 0.

is it what you want?

Body:
When I stop audio and restart using playWhenReady, there is a little bit delay about the position. For example, The position(when I stop the audio) is 1000. But when I restart changing playWhenReady true, the position is 2000. Because of this, My progressbar is not progressed smoothly. Is there any solution about this?

                    if (activeHolder!! == holder) {
                        when (player!!.playWhenReady) {
                            true -> {
                                showLog("player!!.duration, playWhenReady true :"+player!!.duration)
                                showLog("player!!.currentPosition, playWhenReady true :"+player!!.currentPosition)

                                player!!.playWhenReady = false
                                handlerChangeProgress.removeCallbacks(updateChangeProgressTask)
                                showAudioStartButton(activeHolder!!)
                                return
                            }
                            false -> {
                                showLog("player!!.duration, playWhenReady false :"+player!!.duration)
                                showLog("player!!.currentPosition, playWhenReady false :"+player!!.currentPosition)

                                player!!.playWhenReady = true
                                handlerChangeProgress.postDelayed(updateChangeProgressTask, delayChangeProgress)
                                showAudioStopButton(activeHolder!!)
                                return
                            }

                        }
                    }

    override fun onChangeProgressBar(progress: Float, currentPosition: Int, totalDuration: Int) {
        if(player!!.playWhenReady) {

            if (activeHolder?.adapterPosition == audioPosition) {
                activeHolder?.let {
                    it.binding.progressBar.max = player!!.duration.toInt()
                    it.binding.progressBar.progress = player!!.currentPosition.toInt()
                    showAudioStopButton(it)
                }
            }
        }
    }

    private val updateChangeProgressTask: Runnable = object : Runnable {
        override fun run() {
            if(player != null && changeProgressPlayerListener != null) {
                val totalDuration: Long = player!!.duration
                val currentPosition: Long = player!!.currentPosition
                val progress = currentPosition.toFloat() / totalDuration.toFloat()
                changeProgressPlayerListener!!.onChangeProgressBar(progress, currentPosition.toInt(), totalDuration.toInt())
            }
            handlerChangeProgress.postDelayed(this, delayChangeProgress)
        }
    }

Log

D/TAG: player!!.duration, playWhenReady false :4166
D/TAG: player!!.currentPosition, playWhenReady false :2459
D/TAG: player!!.duration, playWhenReady true :4166
D/TAG: player!!.currentPosition, playWhenReady true :2640


问:
npm install throws a bunch of errors in react project
I'm currently learning how to work with React and everytime I try to work on a course file and run npm install I get back a million errors and warning. On literally every file I try this on. I've made sure I'm inside the right directory and that there is a json file.

```<code>    gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Darwin 19.4.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/jessiematias/Downloads/hooks-videoplayer-starterfiles-master/react-hooks-videoplayer-START/node_modules/webpack-dev-server/node_modules/fsevents
gyp ERR! node -v v12.17.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
</code>```

I've already tried to reinstall node, update npm to latest version (i'm on 6.14.4) and run npm cache clean but none of those worked. The only  thing that worked once was to run a command that was something along the lines of npm install missing dependencies but that's not it, i can't remember it or find it anywhere online now.

答:
You need to install node-gyp

```<code>npm install -g node-gyp
</code>```

Body:
I'm currently learning how to work with React and everytime I try to work on a course file and run npm install I get back a million errors and warning. On literally every file I try this on. I've made sure I'm inside the right directory and that there is a json file.

    gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Darwin 19.4.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/jessiematias/Downloads/hooks-videoplayer-starterfiles-master/react-hooks-videoplayer-START/node_modules/webpack-dev-server/node_modules/fsevents
gyp ERR! node -v v12.17.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok

I've already tried to reinstall node, update npm to latest version (i'm on 6.14.4) and run npm cache clean but none of those worked. The only  thing that worked once was to run a command that was something along the lines of npm install missing dependencies but that's not it, i can't remember it or find it anywhere online now.

Body:
You need to install node-gyp

npm install -g node-gyp


问:
Same notifications is repeated with user after each exit from application
I use Service in my app to send Notifications to user after the user exits the application; it's work but I have one problem after user exits from app every time he gets last notification received each time he enters and leaves, the same notice is repeated even if there is no new notice. This is problem. Notifications should only be sent from once time to user, and if he exit next time it should not be sent again. Just if he have a new notification with a new ID it must be sent once time to user.

This is class my service

```<code>public class MyService extends Service {

    public MyService() {
    }

    @Override
    public void onCreate(){
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        Toast.makeText(this, "Start myServis", Toast.LENGTH_LONG).show();
    //    run_loop();
        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        Toast.makeText(this, "Stopmyservci", Toast.LENGTH_LONG).show();
       super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

</code>```

I get data by this code ..

```<code> public void run_loop(){
        String url =  "http://00000000/testnet/android_register_login/ShowAllData.php";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("data");
                                JSONObject hit = jsonArray.getJSONObject(0);
                                String id = hit.getString("id");
                                int lastThread = Integer.parseInt(String.valueOf(id));
                                JSONObject jsonObject = null;
                                Toast.makeText(MainActivtiy.this, lastThread + "", Toast.LENGTH_SHORT).show();
                                if (app.getTotal_threads() < lastThread) {
                                    app.setTotal_threads(lastThread);
                                    Notification notification = new NotificationCompat.Builder(MainActivtiy.this)
                                            .setSmallIcon(android.R.drawable.ic_popup_reminder)
                                            .setContentTitle("title")
                                            .setContentText("message")
                                            .setAutoCancel(true)
                                            .setPriority(NotificationCompat.PRIORITY_HIGH)
                                            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                                            .build();

                                    notificationManager.notify(1, notification);

                            }
                            } catch(JSONException e){
                                e.printStackTrace();
                            }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(request);

        Handler handler=new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                run_loop();
            }
        },10000);

    }

</code>```

```<code>public void onBackPressed() {
        Intent sr =new Intent(this, MyService.class);
        startService(sr);
        Toast.makeText(this, "Exit", Toast.LENGTH_SHORT).show();
        finish();
        run_loop();
        super.onBackPressed();
    }

</code>```

I store id here

```<code>public class App extends Application {
    public static final String CHANNEL_1_ID = "channel1";
    public static final String CHANNEL_2_ID = "channel2";
    private int Total_threads;
    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannels();
    }
    public int getTotal_threads() {
        return Total_threads;
    }
    public void setTotal_threads(int Total_threads) {
        this.Total_threads = Total_threads;
    }
    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID, "Channel 2", NotificationManager.IMPORTANCE_LOW
            );
            channel2.setDescription("This is Channel 2");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}
</code>```

and I get it from here

```<code>
    private void JSON() {
        String url = "http://00000000/test/Showall.php";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray jsonArray = response.getJSONArray("data");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);
                                JSONObject jsonObject = null;

                                String id= hit.getString("id");

app.setTotal_threads(Integer.parseInt(String.valueOf(id)));

                            }
</code>```

What can I try next?

答: I think it's because you're using the Handler to call run_loop() inside your run_loop() function. It might be producing a loop that makes you receive multiple notifications. Try moving it outside of the loop and check if it works.

Body:
I use Service in my app to send Notifications to user after the user exits the application; it's work but I have one problem after user exits from app every time he gets last notification received each time he enters and leaves, the same notice is repeated even if there is no new notice. This is problem. Notifications should only be sent from once time to user, and if he exit next time it should not be sent again. Just if he have a new notification with a new ID it must be sent once time to user.

This is class my service

public class MyService extends Service {

    public MyService() {
    }

    @Override
    public void onCreate(){
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        Toast.makeText(this, "Start myServis", Toast.LENGTH_LONG).show();
    //    run_loop();
        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        Toast.makeText(this, "Stopmyservci", Toast.LENGTH_LONG).show();
       super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

I get data by this code ..

 public void run_loop(){
        String url =  "http://00000000/testnet/android_register_login/ShowAllData.php";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("data");
                                JSONObject hit = jsonArray.getJSONObject(0);
                                String id = hit.getString("id");
                                int lastThread = Integer.parseInt(String.valueOf(id));
                                JSONObject jsonObject = null;
                                Toast.makeText(MainActivtiy.this, lastThread + "", Toast.LENGTH_SHORT).show();
                                if (app.getTotal_threads() < lastThread) {
                                    app.setTotal_threads(lastThread);
                                    Notification notification = new NotificationCompat.Builder(MainActivtiy.this)
                                            .setSmallIcon(android.R.drawable.ic_popup_reminder)
                                            .setContentTitle("title")
                                            .setContentText("message")
                                            .setAutoCancel(true)
                                            .setPriority(NotificationCompat.PRIORITY_HIGH)
                                            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                                            .build();

                                    notificationManager.notify(1, notification);

                            }
                            } catch(JSONException e){
                                e.printStackTrace();
                            }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(request);

        Handler handler=new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                run_loop();
            }
        },10000);

    }

public void onBackPressed() {
        Intent sr =new Intent(this, MyService.class);
        startService(sr);
        Toast.makeText(this, "Exit", Toast.LENGTH_SHORT).show();
        finish();
        run_loop();
        super.onBackPressed();
    }

I store id here

public class App extends Application {
    public static final String CHANNEL_1_ID = "channel1";
    public static final String CHANNEL_2_ID = "channel2";
    private int Total_threads;
    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannels();
    }
    public int getTotal_threads() {
        return Total_threads;
    }
    public void setTotal_threads(int Total_threads) {
        this.Total_threads = Total_threads;
    }
    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID, "Channel 2", NotificationManager.IMPORTANCE_LOW
            );
            channel2.setDescription("This is Channel 2");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}

and I get it from here

    private void JSON() {
        String url = "http://00000000/test/Showall.php";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray jsonArray = response.getJSONArray("data");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);
                                JSONObject jsonObject = null;

                                String id= hit.getString("id");

app.setTotal_threads(Integer.parseInt(String.valueOf(id)));

                            }

What can I try next?


问:
Why is the MySQL integer comparison is slower than datetime null comparison?
I'm using MySQL 5.7.

There is a table called transactions with over 3 million records. The table schema is as follows:

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

Other columns pertaining to this table...

The record_status is an integer version of the deleted_at. When a record is deleted, the value is set to 0. An index is also created for this column.

The null based DATETIME query takes 740 ms to execute:

select transactions.id from transactions where transactions.deleted_at is null

The TINYINT based query takes 15.1 s to execute:

select transactions.id from transactions where transactions.record_status = 1

Isn't the check on the TINYINT column (with index) supposed to be faster? Why is this happening?

[EDIT]

Added information about the table's performance

To take the experiment further, all unnecessary columns were removed from the table. Only the following persist.

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

transaction_time (DATETIME)

Query 1: Takes 2.3ms

```<code>select transactions.id from transactions
where transactions.record_status = 1 limit 1000000;
</code>```

Query 2: Takes 2.1ms

```<code>select transactions.id from transactions
where transactions.deleted_at is null limit 1000000;
</code>```

Query 3: Takes 20 seconds

```<code>select transactions.id from transactions
where transactions.record_status = 1
and transaction_time > '2020-04-01' limit 1000;
</code>```

Query 4: Takes 500ms

```<code>select transactions.id from transactions
where transactions.deleted_at is null
and transaction_time > '2020-04-01' limit 1000;
</code>```

Query 5: 394ms

```<code>select transactions.id from transactions
where transaction_time > '2020-04-01' limit 1000000;
</code>```

I'm unable to figure out why Query 3 is taking this long.

答:
```<code>select transactions.id from transactions
where transactions.record_status = 1
and transaction_time > '2020-04-01' limit 1000;
</code>```

cannot be optimized without a composite index like this -- in this order:

```<code>INDEX(record_status, transaction_time)
</code>```

(No, two separate single-column indexes will not work as well.)

Body:
I'm using MySQL 5.7.

There is a table called transactions with over 3 million records. The table schema is as follows:

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

Other columns pertaining to this table...

The record_status is an integer version of the deleted_at. When a record is deleted, the value is set to 0. An index is also created for this column.

The null based DATETIME query takes 740 ms to execute:

select transactions.id from transactions where transactions.deleted_at is null

The TINYINT based query takes 15.1 s to execute:

select transactions.id from transactions where transactions.record_status = 1

Isn't the check on the TINYINT column (with index) supposed to be faster? Why is this happening?

[EDIT]

Added information about the table's performance

To take the experiment further, all unnecessary columns were removed from the table. Only the following persist.

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

transaction_time (DATETIME)

Query 1: Takes 2.3ms

select transactions.id from transactions
where transactions.record_status = 1 limit 1000000;

Query 2: Takes 2.1ms

select transactions.id from transactions
where transactions.deleted_at is null limit 1000000;

Query 3: Takes 20 seconds

select transactions.id from transactions
where transactions.record_status = 1
and transaction_time > '2020-04-01' limit 1000;

Query 4: Takes 500ms

select transactions.id from transactions
where transactions.deleted_at is null
and transaction_time > '2020-04-01' limit 1000;

Query 5: 394ms

select transactions.id from transactions
where transaction_time > '2020-04-01' limit 1000000;

I'm unable to figure out why Query 3 is taking this long.

Body:
select transactions.id from transactions
where transactions.record_status = 1
and transaction_time > '2020-04-01' limit 1000;

cannot be optimized without a composite index like this -- in this order:

INDEX(record_status, transaction_time)

(No, two separate single-column indexes will not work as well.)


答:
Terse, but maybe not that pythonic:</p>

```<code>import calendar, functools, collections

{calendar.month_name[i]: val for i, val in functools.reduce(lambda a, b: a + b, [collections.Counter({datetime.datetime.strptime(time, '%Y/%m/%d').month: val}) for time, val in sum_weekly]).items()}
</code>```

Body:
Terse, but maybe not that pythonic:

import calendar, functools, collections

{calendar.month_name[i]: val for i, val in functools.reduce(lambda a, b: a + b, [collections.Counter({datetime.datetime.strptime(time, '%Y/%m/%d').month: val}) for time, val in sum_weekly]).items()}


问:
In IntelliJ, Maven can't resolve dependencies
Right now, I get errors on the dependencies shown in Maven. </p>

<p>I've tried the things listed here Intellij idea cannot resolve anything in maven such as changing my Maven Home Directory and Selecting Import Maven automatically. I'm not sure what else it could be...
Also, the project was initially done in Eclipse. </p>

答:
You can try to force the downloading of dependencies with this command:

```<code>mvn clean install -U
</code>```

Or you can press Ctrl+Shift+A (win/linux) or Command+shift+A (mac) to find actions, type "reimport" and choose "Reimport All Maven Projects".

From the UI:

Body:
Right now, I get errors on the dependencies shown in Maven.

I've tried the things listed here Intellij idea cannot resolve anything in maven such as changing my Maven Home Directory and Selecting Import Maven automatically. I'm not sure what else it could be...
Also, the project was initially done in Eclipse.

Body:
You can try to force the downloading of dependencies with this command:

mvn clean install -U

Or you can press Ctrl+Shift+A (win/linux) or Command+shift+A (mac) to find actions, type "reimport" and choose "Reimport All Maven Projects".

From the UI:


问:
Is there a way to read a file in C without a bunch of checks for sscanf and fgets?
In a program I'm writing, I'm currently doing the part of parsing an input file. I have to do input validation (to some degree), checking if sscanf parses the right number of variables and fgets isn't null. But as a result, the main outline looks like this:

```<code>int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;
    if (camFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz, dx, dy, dz, dt;
        if (sscanf(line, "%f %f %f %f %f %f %f\n", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        // do stuff with input
    }
    if (lightFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz;
        unsigned char r, g, b;
        if (sscanf(line, "%f %f %f %hhu %hhu %hhu\n", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        if (fgets(line, LINE_LENGTH, fp) == NULL)) return 1;
        int n;
        if (sscanf(line, "%d\n", &n) != 1) return 1;
        // etc...
    }
}
</code>```

and as a result, half the lines are checking input. Is there a good way to avoid this?

答:
Is there a way to read a file in C without a bunch of checks for sscanf and fgets?

Yes. Just read characters one by one with fgetc, then apply usual lexing and parsing techniques.

Read the Dragon book.

Consider using parser generators such as ANTLR, flex+bison, lemon, etc... Then would generate some C code from a higher-level description of the parsed language.

Or else, if your input parsed language is weird enough, use your own meta-programming techniques. Write (perhaps in in some other programming language like Ocaml or Guile or Python) some metaprogram to generate the C code (perhaps some recursive descent parser) you are manually writing from a higher-level description. Then adapt your build automation (e.g. add a few lines to your Makefile) for such cases.

Notice that parsing is a well established technique. You'll find research papers on parsing (and compiler building, and interpreter building) since the 1960s. You'll find tons of open source programs (e.g. on github or gitlab or elsewhere) whose parsing should be inspirational to you: e.g. most C compilers (e.g. tinycc), Unix shells such as bash or zsh or sash, the source code of Python, etc...

Body:
In a program I'm writing, I'm currently doing the part of parsing an input file. I have to do input validation (to some degree), checking if sscanf parses the right number of variables and fgets isn't null. But as a result, the main outline looks like this:

int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;
    if (camFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz, dx, dy, dz, dt;
        if (sscanf(line, "%f %f %f %f %f %f %f\n", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        // do stuff with input
    }
    if (lightFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz;
        unsigned char r, g, b;
        if (sscanf(line, "%f %f %f %hhu %hhu %hhu\n", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        if (fgets(line, LINE_LENGTH, fp) == NULL)) return 1;
        int n;
        if (sscanf(line, "%d\n", &n) != 1) return 1;
        // etc...
    }
}

and as a result, half the lines are checking input. Is there a good way to avoid this?


问:
why does "npm run build" produce error "react-scripts Permission denied"?
I'm on Ubuntu 18.04, logged in as root.  The group:owner of /root/.npm is root:root, recursively, and all permissions are 777, recursively.  If I cd to the React folder:

```<code>cd /var/lib/jenkins/workspace/MedAverter/medaverter-front
</code>```

And set all permissions of that folder to 777, recursively and then run

```<code>npm run build
</code>```

I get error:

[[1;34mINFO[m] Running 'npm run build' in
  /var/lib/jenkins/workspace/MedAverter/medaverter-front
  [[1;34mINFO[m]  [[1;34mINFO[m] > medaverter-front@0.1.0 build
  /var/lib/jenkins/workspace/MedAverter/medaverter-front
  [[1;34mINFO[m] > react-scripts build [[1;34mINFO[m]
  [[1;31mERROR[m] sh: 1: react-scripts: Permission denied
  [[1;31mERROR[m] npm ERR! code ELIFECYCLE [[1;31mERROR[m] npm ERR!
  errno 126 [[1;31mERROR[m] npm ERR! medaverter-front@0.1.0 build:
  react-scripts build [[1;31mERROR[m] npm ERR! Exit status 126
  [[1;31mERROR[m] npm ERR!  [[1;31mERROR[m] npm ERR! Failed at the
  medaverter-front@0.1.0 build script.

I've been googling for a solution for hours with no luck.  It builds fine under Windows 10.
Suggestions?

答:
You may need to run

```<code>$ npm config set user root
</code>```

I ran into that issue once building from a node docker file

Body:
I'm on Ubuntu 18.04, logged in as root.  The group:owner of /root/.npm is root:root, recursively, and all permissions are 777, recursively.  If I cd to the React folder:

cd /var/lib/jenkins/workspace/MedAverter/medaverter-front

And set all permissions of that folder to 777, recursively and then run

npm run build

I get error:

[[1;34mINFO[m] Running 'npm run build' in
  /var/lib/jenkins/workspace/MedAverter/medaverter-front
  [[1;34mINFO[m]  [[1;34mINFO[m] > medaverter-front@0.1.0 build
  /var/lib/jenkins/workspace/MedAverter/medaverter-front
  [[1;34mINFO[m] > react-scripts build [[1;34mINFO[m]
  [[1;31mERROR[m] sh: 1: react-scripts: Permission denied
  [[1;31mERROR[m] npm ERR! code ELIFECYCLE [[1;31mERROR[m] npm ERR!
  errno 126 [[1;31mERROR[m] npm ERR! medaverter-front@0.1.0 build:
  react-scripts build [[1;31mERROR[m] npm ERR! Exit status 126
  [[1;31mERROR[m] npm ERR!  [[1;31mERROR[m] npm ERR! Failed at the
  medaverter-front@0.1.0 build script.

I've been googling for a solution for hours with no luck.  It builds fine under Windows 10.
Suggestions?

Body:
You may need to run

$ npm config set user root

I ran into that issue once building from a node docker file


问:
AWS lambda nodejs showing error while using X-RAY
I have following code:

```<code>var AWSXRay = require('aws-xray-sdk');
    var AWS = AWSXRay.captureAWS(require('aws-sdk'));
    const client = AWSXRay.captureAWSClient(new AWS.DynamoDB.DocumentClient({region : 'eu-west-1'}));
    exports.handler = function(event, context, callback) {

        AWSXRay.captureFunc('annotations', function(subsegment){
        subsegment.addAnnotation('User', **);
        subsegment.addAnnotation('Name', **);
      });

         var params = {
            TableName: "****",
            ** all params **
            };
     client.query(params, function(err, data) {
       if (err) console.log(err, err.stack); // an error occurred
       else{
            callback(null,data);
            }
        });
    }
</code>```

When executing the code above, the following error is thrown:

```<code>Response:
{
  "errorMessage": "service.customizeRequests is not a function",
  "errorType": "TypeError",
  "stackTrace": [
    "Object.<anonymous> (/var/task/index.js:5:24)",
    "Module._compile (module.js:570:32)",
    "Object.Module._extensions..js (module.js:579:10)",
    "Module.load (module.js:487:32)",
    "tryModuleLoad (module.js:446:12)",
    "Function.Module._load (module.js:438:3)",
    "Module.require (module.js:497:17)",
    "require (internal/module.js:20:19)"
  ]
}
</code>```

following are the logs of function:

```<code>Function Logs:
START RequestId: Version: $LATEST
module initialization error: TypeError
    at Object.captureAWSClient (/var/task/node_modules/aws-xray-sdk-core/lib/patchers/aws_p.js:55:11)
    at Object.<anonymous> (/var/task/index.js:5:24)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
END
</code>```

How should I resolve this?

答:
client doesn't have .service public variable. That said, this one is working for me:</p>

```<code>import * as AWS  from 'aws-sdk'
import * as AWSXRay from 'aws-xray-sdk'
import { DocumentClient } from 'aws-sdk/clients/dynamodb'

export class DynDBAccess {
    private readonly docClient: DocumentClient // = new AWS.DynamoDB.DocumentClient(),

    constructor(
        private enableAWSX:boolean,
    ){
        if(this.enableAWSX)
        {
           logger.info('AWSX: enable')
           const ddbClient = AWSXRay.captureAWSClient(new AWS.DynamoDB({
            ////Uncomment below to use serverless-dynamodb-local
            //region: 'localhost',
            //endpoint: 'http://localhost:8001',
            //accessKeyId: 'DEFAULT_ACCESS_KEY',  // needed if you don't have aws credentials at all in env
            //secretAccessKey: 'DEFAULT_SECRET',
           }));
           this.docClient = new AWS.DynamoDB.DocumentClient({
            service: ddbClient
          });

        }
...

</code>```

Body:
I have following code:

var AWSXRay = require('aws-xray-sdk');
    var AWS = AWSXRay.captureAWS(require('aws-sdk'));
    const client = AWSXRay.captureAWSClient(new AWS.DynamoDB.DocumentClient({region : 'eu-west-1'}));
    exports.handler = function(event, context, callback) {

        AWSXRay.captureFunc('annotations', function(subsegment){
        subsegment.addAnnotation('User', **);
        subsegment.addAnnotation('Name', **);
      });

         var params = {
            TableName: "****",
            ** all params **
            };
     client.query(params, function(err, data) {
       if (err) console.log(err, err.stack); // an error occurred
       else{
            callback(null,data);
            }
        });
    }

When executing the code above, the following error is thrown:

Response:
{
  "errorMessage": "service.customizeRequests is not a function",
  "errorType": "TypeError",
  "stackTrace": [
    "Object.<anonymous> (/var/task/index.js:5:24)",
    "Module._compile (module.js:570:32)",
    "Object.Module._extensions..js (module.js:579:10)",
    "Module.load (module.js:487:32)",
    "tryModuleLoad (module.js:446:12)",
    "Function.Module._load (module.js:438:3)",
    "Module.require (module.js:497:17)",
    "require (internal/module.js:20:19)"
  ]
}

following are the logs of function:

Function Logs:
START RequestId: Version: $LATEST
module initialization error: TypeError
    at Object.captureAWSClient (/var/task/node_modules/aws-xray-sdk-core/lib/patchers/aws_p.js:55:11)
    at Object.<anonymous> (/var/task/index.js:5:24)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
END

How should I resolve this?

Body:
client doesn't have .service public variable. That said, this one is working for me:

import * as AWS  from 'aws-sdk'
import * as AWSXRay from 'aws-xray-sdk'
import { DocumentClient } from 'aws-sdk/clients/dynamodb'

export class DynDBAccess {
    private readonly docClient: DocumentClient // = new AWS.DynamoDB.DocumentClient(),

    constructor(
        private enableAWSX:boolean,
    ){
        if(this.enableAWSX)
        {
           logger.info('AWSX: enable')
           const ddbClient = AWSXRay.captureAWSClient(new AWS.DynamoDB({
            ////Uncomment below to use serverless-dynamodb-local
            //region: 'localhost',
            //endpoint: 'http://localhost:8001',
            //accessKeyId: 'DEFAULT_ACCESS_KEY',  // needed if you don't have aws credentials at all in env
            //secretAccessKey: 'DEFAULT_SECRET',
           }));
           this.docClient = new AWS.DynamoDB.DocumentClient({
            service: ddbClient
          });

        }
...


问:
Building a chat app with angular, trying to make it so whenever the @ character is typed a list of the groups users appears above the @ symbol
So say I've got an input as follows:

```<code><input
class="chatInput form-control"
[(ngModel)]="message"
(keydown)="handleSubmit($event)"
/>
</code>```

as well as a list of group members with username attributes.

I want to make it so similar to groupme, every time I type the @ symbol, a list of the groups users pop up above wherever the @ is. I'm able to identify WHEN there is an @ symbold typed with (ngModelChange), however I don't know how to make a pop up at the exact location of the @ symbol. Any ideas?

答:
You can something like:

```<code><input
class="chatInput form-control"
[(ngModel)]="message"
(keydown)="handleSubmit($event)"
/>
<ul class="list-group" ng-model="users" ng-hide="!users">
    <li class="list-group-item" ng-repeat="user in users track by $index">{{user.name}}</li>
</ul>
</code>```

This will show a list of users just below your input, like this:

Hope this will help you.

Body:
So say I've got an input as follows:

<input
class="chatInput form-control"
[(ngModel)]="message"
(keydown)="handleSubmit($event)"
/>

as well as a list of group members with username attributes.

I want to make it so similar to groupme, every time I type the @ symbol, a list of the groups users pop up above wherever the @ is. I'm able to identify WHEN there is an @ symbold typed with (ngModelChange), however I don't know how to make a pop up at the exact location of the @ symbol. Any ideas?

Body:
You can something like:

<input
class="chatInput form-control"
[(ngModel)]="message"
(keydown)="handleSubmit($event)"
/>
<ul class="list-group" ng-model="users" ng-hide="!users">
    <li class="list-group-item" ng-repeat="user in users track by $index">{{user.name}}</li>
</ul>

This will show a list of users just below your input, like this:

Hope this will help you.