问:
django.db.utils.IntegrityError: (1062, "Duplicate entry for user_id")
I have a certain model:

```<code>class Problem(models.Model):

    title = models.CharField(max_length=80)
    problem_text = models.TextField(max_length=5000)
    pub_date = models.DateTimeField(default=timezone.now)
    votes = models.IntegerField(default=0)
    wiki_answer = models.TextField(max_length=5000, null=False, default='', blank=True)
    topic = models.CharField(max_length=50, blank=False)
    position = models.CharField(max_length=50, null=True, blank=False)
    user = models.OneToOneField(User, null=True, blank=False, unique=False)
</code>```

And after adding more than one post written by one user Django raises an error even though a user is not supposed to be unique. Here is the full stack trace:

```<code>File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
  112.             return self.cursor.execute(query, args)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  226.             self.errorhandler(self, exc, value)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in defaulterrorhandler
  36.         raise errorvalue

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  217.             res = self._query(query)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _query
  378.         rowcount = self._do_query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _do_query
  341.         db.query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in query
  280.             _mysql.connection.query(self, query)

The above exception ((1062, "Duplicate entry '1' for key 'interview_questions_problem_user_id_105dd8d0_uniq'")) was the direct cause of the following exception:

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/Users/artemdremov/Documents/python/interview_project/interview_questions/views.py" in post
  55.             post.save()

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in save
  708.                        force_update=force_update, update_fields=update_fields)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in save_base
  736.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in _save_table
  820.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in _do_insert
  859.                                using=using, raw=raw)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
  122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/query.py" in _insert
  1039.         return query.get_compiler(using=using).execute_sql(return_id)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1060.                 cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/utils.py" in __exit__
  95.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/utils/six.py" in reraise
  685.             raise value.with_traceback(tb)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
  112.             return self.cursor.execute(query, args)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  226.             self.errorhandler(self, exc, value)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in defaulterrorhandler
  36.         raise errorvalue

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  217.             res = self._query(query)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _query
  378.         rowcount = self._do_query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _do_query
  341.         db.query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in query
  280.             _mysql.connection.query(self, query)

Exception Type: IntegrityError at /p/add/
Exception Value: (1062, "Duplicate entry '1' for key 'interview_questions_problem_user_id_105dd8d0_uniq'")
</code>```

Django version 1.9.5.

Here is the view for adding post form:

```<code>class AddView(View):
    template_name = 'interview_questions/add.html'
    form_class = ProblemForm
    success_url = '/'

    # display blank form
    def get(self, request):
        if request.user.is_authenticated():
            form = self.form_class(None)
            return render(request, self.template_name, {'form': form, 'user': request.user})
        else:
            return redirect('interview_questions:index')

    # process data
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid() and request.user.is_authenticated():
            post = form.save(commit=False)
            post.pub_date = timezone.now()
            post.user = request.user
            post.save()
            return redirect('interview_questions:index')

        return render(request, self.template_name, {'form': form, 'user': request.user})
</code>```

答:
If want to handle Duplicate exception in Django read this

How to avoid Duplicate exception

We can also avoid from this kind of exception first check Profile exist or not  then create Profile if not existed.

We can achieve this using get_or_create() method.

Many times we need to make unique fields or unique_together in Model to achieve some business logic.

Example

User and Profile (OneToOne relationship)

One Profile is created for per user.

Handle Duplicate entry exception in Django:

If user already created their profile again want to create then we can easily handle duplicate entry of profile like this.

```<code>from django.db import IntegrityError

try:
   profile = Profile.objects.create(user=someuser,imageUrl= url )
except IntegrityError:
   pass
   #Handle your exception here
</code>```

Body:
I have a certain model:

class Problem(models.Model):

    title = models.CharField(max_length=80)
    problem_text = models.TextField(max_length=5000)
    pub_date = models.DateTimeField(default=timezone.now)
    votes = models.IntegerField(default=0)
    wiki_answer = models.TextField(max_length=5000, null=False, default='', blank=True)
    topic = models.CharField(max_length=50, blank=False)
    position = models.CharField(max_length=50, null=True, blank=False)
    user = models.OneToOneField(User, null=True, blank=False, unique=False)

And after adding more than one post written by one user Django raises an error even though a user is not supposed to be unique. Here is the full stack trace:

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
  112.             return self.cursor.execute(query, args)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  226.             self.errorhandler(self, exc, value)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in defaulterrorhandler
  36.         raise errorvalue

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  217.             res = self._query(query)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _query
  378.         rowcount = self._do_query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _do_query
  341.         db.query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in query
  280.             _mysql.connection.query(self, query)

The above exception ((1062, "Duplicate entry '1' for key 'interview_questions_problem_user_id_105dd8d0_uniq'")) was the direct cause of the following exception:

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/Users/artemdremov/Documents/python/interview_project/interview_questions/views.py" in post
  55.             post.save()

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in save
  708.                        force_update=force_update, update_fields=update_fields)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in save_base
  736.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in _save_table
  820.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/base.py" in _do_insert
  859.                                using=using, raw=raw)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
  122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/query.py" in _insert
  1039.         return query.get_compiler(using=using).execute_sql(return_id)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1060.                 cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/utils.py" in __exit__
  95.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/utils/six.py" in reraise
  685.             raise value.with_traceback(tb)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
  112.             return self.cursor.execute(query, args)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  226.             self.errorhandler(self, exc, value)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in defaulterrorhandler
  36.         raise errorvalue

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in execute
  217.             res = self._query(query)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _query
  378.         rowcount = self._do_query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py" in _do_query
  341.         db.query(q)

File "/Users/artemdremov/Documents/python/interview_project/venv/interview_project/lib/python3.4/site-packages/mysqlclient-1.3.7-py3.4-macosx-10.6-intel.egg/MySQLdb/connections.py" in query
  280.             _mysql.connection.query(self, query)

Exception Type: IntegrityError at /p/add/
Exception Value: (1062, "Duplicate entry '1' for key 'interview_questions_problem_user_id_105dd8d0_uniq'")

Django version 1.9.5.

Here is the view for adding post form:

class AddView(View):
    template_name = 'interview_questions/add.html'
    form_class = ProblemForm
    success_url = '/'

    # display blank form
    def get(self, request):
        if request.user.is_authenticated():
            form = self.form_class(None)
            return render(request, self.template_name, {'form': form, 'user': request.user})
        else:
            return redirect('interview_questions:index')

    # process data
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid() and request.user.is_authenticated():
            post = form.save(commit=False)
            post.pub_date = timezone.now()
            post.user = request.user
            post.save()
            return redirect('interview_questions:index')

        return render(request, self.template_name, {'form': form, 'user': request.user})

Body:
If want to handle Duplicate exception in Django read this

How to avoid Duplicate exception

We can also avoid from this kind of exception first check Profile exist or not  then create Profile if not existed.

We can achieve this using get_or_create() method.

Many times we need to make unique fields or unique_together in Model to achieve some business logic.

Example

User and Profile (OneToOne relationship)

One Profile is created for per user.

Handle Duplicate entry exception in Django:

If user already created their profile again want to create then we can easily handle duplicate entry of profile like this.

from django.db import IntegrityError

try:
   profile = Profile.objects.create(user=someuser,imageUrl= url )
except IntegrityError:
   pass
   #Handle your exception here


来源: stackexchange

问:
Extracting a step from a text file and placing into a list with Python
I am opening a txt and assigning every third word to go into a list called three.

I thought this would step correctly, but I am just getting the entire file as a list.

```<code>three=[]

with open('school_prompt.txt', 'r') as f:
    for line in f.split()[::3]:
        three.append(line)
</code>```

答:
If file is big you can do next (it will read it line by line and append each third word to list):</p>

```<code>idx = 0
three = []

with open('school_prompt.txt', 'r') as file:
    for line in file:
        for word in line.split():
            idx += 1
            if idx % 3 == 0:
                three.append(word)

print(three) # you list of words on 3rd position
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am opening a txt and assigning every third word to go into a list called three.

I thought this would step correctly, but I am just getting the entire file as a list.

three=[]

with open('school_prompt.txt', 'r') as f:
    for line in f.split()[::3]:
        three.append(line)

Body:
If file is big you can do next (it will read it line by line and append each third word to list):

idx = 0
three = []

with open('school_prompt.txt', 'r') as file:
    for line in file:
        for word in line.split():
            idx += 1
            if idx % 3 == 0:
                three.append(word)

print(three) # you list of words on 3rd position


问:
Reorder panels in ridgeline plot
I have a dataframe like this:

```<code>set.seed(3467)

 df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
        beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))
</code>```

I wish to create a ridgeline plot similar to this:

```<code>library(ggplot2)
library(ggridges)

ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))
</code>```

However, I wish to order the y-axis in the order of method= "B", "C", "A" not method= "A", "B", "C"

I have tried the following method, without success, to reorder the density plots:

```<code>library(dplyr)
df %>%
 mutate(method = fct_relevel(method,
                        "B", "C", "A"))%>%
ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))
</code>```

答:
If you change the method column to ordered factor, it should work:</p>

```<code>df$method <- factor(df$method, levels = c("C", "A", "B"), ordered = TRUE)
</code>```

Title: Reorder panels in ridgeline plot

Body:
I have a dataframe like this:

set.seed(3467)

 df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
        beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))

I wish to create a ridgeline plot similar to this:

library(ggplot2)
library(ggridges)

ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))

However, I wish to order the y-axis in the order of method= "B", "C", "A" not method= "A", "B", "C"

I have tried the following method, without success, to reorder the density plots:

library(dplyr)
df %>%
 mutate(method = fct_relevel(method,
                        "B", "C", "A"))%>%
ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))

Body:
If you change the method column to ordered factor, it should work:

df$method <- factor(df$method, levels = c("C", "A", "B"), ordered = TRUE)


问:
Click function on checkbox for toggeling table elements
I have been trying to use this JS for hiding some html table th and td elements.

```<code>$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();
    $('#hide_proces').click(function() {
        if($(this).attr('checked'))
        {
            $('th.proces').show();
            $('td.proces').show();
        }
        else
        {
            $('th.proces').hide();
            $('td.proces').hide();
        }
    });
});
</code>```

When the page is loaded the items are hidden, so that is working.

Now I have this checkbox, and when checked the th and td elements should be made visible again.

```<code><input id="hide_proces" type="checkbox"/>
<th class="proces">Proces</th>
<td class="proces">some content</td>
</code>```

When the checkbox is checked the elements are still not visible, also no errors in the console. Any suggestions?

答:
check the value of the checkbox using this.checked then use show or hide to show column,

see below snippet

$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();

    $("#hide_proces").on("click",function(e){
      this.checked ? ($('th.proces').show(),$('td.proces').show())
                   : ($('th.proces').hide(),$('td.proces').hide());
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

show process :<input id="hide_proces" type="checkbox" />

<br /><br /><br />

<table>
  <tr>
    <th class="proces">proces</th>
    <th>Item</th>
    <th>Amount</th>
  </tr>
  <tr>
    <td class="proces">some text  1!</td>
    <td>Apples</td>
    <td>$15</td>
  </tr>
  <tr>
    <td class="proces">some text 2 !</td>
    <td>Orange</td>
    <td>$9</td>
  </tr>
  <tr>
    <td class="proces">some text 3 !</td>
    <td>Bananas</td>
    <td>$7</td>
  </tr>
</table></code>```

Body:
I have been trying to use this JS for hiding some html table th and td elements.

$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();
    $('#hide_proces').click(function() {
        if($(this).attr('checked'))
        {
            $('th.proces').show();
            $('td.proces').show();
        }
        else
        {
            $('th.proces').hide();
            $('td.proces').hide();
        }
    });
});

When the page is loaded the items are hidden, so that is working.

Now I have this checkbox, and when checked the th and td elements should be made visible again.

<input id="hide_proces" type="checkbox"/>
Proces
some content

When the checkbox is checked the elements are still not visible, also no errors in the console. Any suggestions?

Body:
check the value of the checkbox using this.checked then use show or hide to show column,

see below snippet

$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();

    $("#hide_proces").on("click",function(e){
      this.checked ? ($('th.proces').show(),$('td.proces').show())
                   : ($('th.proces').hide(),$('td.proces').hide());
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

show process :<input id="hide_proces" type="checkbox" />

<br /><br /><br />

<table>
  <tr>
    <th class="proces">proces</th>
    <th>Item</th>
    <th>Amount</th>
  </tr>
  <tr>
    <td class="proces">some text  1!</td>
    <td>Apples</td>
    <td>$15</td>
  </tr>
  <tr>
    <td class="proces">some text 2 !</td>
    <td>Orange</td>
    <td>$9</td>
  </tr>
  <tr>
    <td class="proces">some text 3 !</td>
    <td>Bananas</td>
    <td>$7</td>
  </tr>
</table>


问:
SQL -- create column in SELECT to test equality
In SQL Server, I'm dealing with these columns:

tblSchedule

ID

StaffID

StartTime

EndTime

I want to include a boolean field in my result set that indicates whether StartTime and EndTime are equal.  Something analogous to this:

```<code>SELECT StaffID, StartTime, EndTime, (StartTime = EndTime) AS AreEqual
FROM tblSchedule Where StaffID = xxx
</code>```

But I'm not sure of the actual syntax for an operation like that.

答:
Try using a CASE WHEN in your SELECT statement; something like this:

```<code>SELECT CASE WHEN StartTime = EndTime THEN 1 ELSE 0 END AS AreEqual
FROM MyTable
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In SQL Server, I'm dealing with these columns:

tblSchedule

ID

StaffID

StartTime

EndTime

I want to include a boolean field in my result set that indicates whether StartTime and EndTime are equal.  Something analogous to this:

SELECT StaffID, StartTime, EndTime, (StartTime = EndTime) AS AreEqual
FROM tblSchedule Where StaffID = xxx

But I'm not sure of the actual syntax for an operation like that.

Body:
Try using a CASE WHEN in your SELECT statement; something like this:

SELECT CASE WHEN StartTime = EndTime THEN 1 ELSE 0 END AS AreEqual
FROM MyTable


问:
java.lang.NoSuchMethodError - okhttp3 (Android)
My app keeps crashing. Can't figure out where the issue is.  I'm not even using okttp3 library.
Currently, I'm only using retrofit 1.9 and otto 1.3.8</p>

```<code>java.lang.NoSuchMethodError: No virtual method callEnqueue(Lokhttp3/Call;Lokhttp3/Callback;Z)V in class Lokhttp3/internal/Internal; or its super classes (declaration of 'okhttp3.internal.Internal' appears in /data/app/com.myproj.sample-2/base.apk)
at okhttp3.ws.WebSocketCall.enqueue(WebSocketCall.java:108)
at io.socket.engineio.client.transports.WebSocket.doOpen(WebSocket.java:73)
at io.socket.engineio.client.Transport$1.run(Transport.java:75)
at io.socket.thread.EventThread.exec(EventThread.java:50)
at io.socket.engineio.client.Transport.open(Transport.java:70)
at io.socket.engineio.client.Socket.probe(Socket.java:458)
at io.socket.engineio.client.Socket.onOpen(Socket.java:471)
at io.socket.engineio.client.Socket.onHandshake(Socket.java:512)
at io.socket.engineio.client.Socket.onPacket(Socket.java:485)
at io.socket.engineio.client.Socket.access$900(Socket.java:30)
at io.socket.engineio.client.Socket$5.call(Socket.java:299)
at io.socket.emitter.Emitter.emit(Emitter.java:117)
at io.socket.engineio.client.Transport.onPacket(Transport.java:127)
at io.socket.engineio.client.transports.Polling$2.call(Polling.java:124)
at io.socket.engineio.parser.Parser.decodePayload(Parser.java:251)
at io.socket.engineio.client.transports.Polling._onData(Polling.java:134)
at io.socket.engineio.client.transports.Polling.onData(Polling.java:106)
at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:113)
at io.socket.thread.EventThread$2.run(EventThread.java:75)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
</code>```

答:
Try these dependencies :

```<code> implementation 'com.shopify.mobilebuysdk:buy3:3.2.3'
 implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
 implementation 'com.squareup.okhttp3:okhttp:3.11.0'
</code>```

Hope this may help you.

Body:
My app keeps crashing. Can't figure out where the issue is.  I'm not even using okttp3 library.
Currently, I'm only using retrofit 1.9 and otto 1.3.8

java.lang.NoSuchMethodError: No virtual method callEnqueue(Lokhttp3/Call;Lokhttp3/Callback;Z)V in class Lokhttp3/internal/Internal; or its super classes (declaration of 'okhttp3.internal.Internal' appears in /data/app/com.myproj.sample-2/base.apk)
at okhttp3.ws.WebSocketCall.enqueue(WebSocketCall.java:108)
at io.socket.engineio.client.transports.WebSocket.doOpen(WebSocket.java:73)
at io.socket.engineio.client.Transport$1.run(Transport.java:75)
at io.socket.thread.EventThread.exec(EventThread.java:50)
at io.socket.engineio.client.Transport.open(Transport.java:70)
at io.socket.engineio.client.Socket.probe(Socket.java:458)
at io.socket.engineio.client.Socket.onOpen(Socket.java:471)
at io.socket.engineio.client.Socket.onHandshake(Socket.java:512)
at io.socket.engineio.client.Socket.onPacket(Socket.java:485)
at io.socket.engineio.client.Socket.access$900(Socket.java:30)
at io.socket.engineio.client.Socket$5.call(Socket.java:299)
at io.socket.emitter.Emitter.emit(Emitter.java:117)
at io.socket.engineio.client.Transport.onPacket(Transport.java:127)
at io.socket.engineio.client.transports.Polling$2.call(Polling.java:124)
at io.socket.engineio.parser.Parser.decodePayload(Parser.java:251)
at io.socket.engineio.client.transports.Polling._onData(Polling.java:134)
at io.socket.engineio.client.transports.Polling.onData(Polling.java:106)
at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:113)
at io.socket.thread.EventThread$2.run(EventThread.java:75)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)

Body:
Try these dependencies :

 implementation 'com.shopify.mobilebuysdk:buy3:3.2.3'
 implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
 implementation 'com.squareup.okhttp3:okhttp:3.11.0'

Hope this may help you.


问:
scrollable highchart works in JS but has issues when running through Angular HighCharts?
I was looking at this codebase https://jsfiddle.net/mushigh/zvq46kg8/ which gave me insight on how to develop a scrollbar. When attemptng to do it myself though it doesnt work correctly.

The fiddle shows the following set up for the chart:

```<code>var chart = Highcharts.chart('container', {
  chart: {
    type: 'bar',
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    },
  },
  xAxis: {
    type: 'category',
    min: 0,
    max: 5
  },
  scrollbar: {
    enabled: true
  },
  series: [{
      type: 'pie',
      name: 'Total consumption',
      zIndex: 9,
      data: [{
        name: 'Jane',
        y: 13,
        color: Highcharts.getOptions().colors[0] // Jane's color
      }, {
        name: 'John',
        y: 23,
        color: Highcharts.getOptions().colors[1] // John's color
      }, {
        name: 'Joe',
        y: 19,
        color: Highcharts.getOptions().colors[2] // Joe's color
      }],
      center: [300, 10],
      size: 50,
      showInLegend: false,
      dataLabels: {
        enabled: false
      }
    }, {
      name: "A",
      data: test(20)
    }, {
      name: "B",
      data: test(20)
    },
    {
      name: "C",
      data: test(20)
    },
    {
      name: "D",
      data: test(20)
    }
  ]
});
</code>```

I was trying to implement this with angular-highcharts through and while it looks like everything works, the horizontal bars are not hidden when outside of the view port.

It looks like this though:

You can see there are some bars which show when they should not.  (This is in comparison to the above jsfiddle).

I created a repo in order to create reproducibility.  You should just need to npm intall and then ng serve.  The repo is located at: https://github.com/fallenreaper/highchart-angular-scrolling.git

Everything should be in place and you should be able to serve the app, go to localhost and see the issue.  I didnt update it YET but i can revert the dataset to the one given in the jsfiddle as well.

Is this a glitch with Angular HighCharts, or is here something else going on?

答:
Here is my reproduction of the demo which you have shared in the Angular environment.

Demo: https://codesandbox.io/s/angular-ldxch

Please notice that this example uses the Highstock, not Highcharts - scrollbar is not implemented in Highcharts.

Highcharts use the scrollablePlotArea instead: https://api.highcharts.com/highcharts/chart.scrollablePlotArea

Body:
I was looking at this codebase https://jsfiddle.net/mushigh/zvq46kg8/ which gave me insight on how to develop a scrollbar. When attemptng to do it myself though it doesnt work correctly.

The fiddle shows the following set up for the chart:

var chart = Highcharts.chart('container', {
  chart: {
    type: 'bar',
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    },
  },
  xAxis: {
    type: 'category',
    min: 0,
    max: 5
  },
  scrollbar: {
    enabled: true
  },
  series: [{
      type: 'pie',
      name: 'Total consumption',
      zIndex: 9,
      data: [{
        name: 'Jane',
        y: 13,
        color: Highcharts.getOptions().colors[0] // Jane's color
      }, {
        name: 'John',
        y: 23,
        color: Highcharts.getOptions().colors[1] // John's color
      }, {
        name: 'Joe',
        y: 19,
        color: Highcharts.getOptions().colors[2] // Joe's color
      }],
      center: [300, 10],
      size: 50,
      showInLegend: false,
      dataLabels: {
        enabled: false
      }
    }, {
      name: "A",
      data: test(20)
    }, {
      name: "B",
      data: test(20)
    },
    {
      name: "C",
      data: test(20)
    },
    {
      name: "D",
      data: test(20)
    }
  ]
});

I was trying to implement this with angular-highcharts through and while it looks like everything works, the horizontal bars are not hidden when outside of the view port.

It looks like this though:

You can see there are some bars which show when they should not.  (This is in comparison to the above jsfiddle).

I created a repo in order to create reproducibility.  You should just need to npm intall and then ng serve.  The repo is located at: https://github.com/fallenreaper/highchart-angular-scrolling.git

Everything should be in place and you should be able to serve the app, go to localhost and see the issue.  I didnt update it YET but i can revert the dataset to the one given in the jsfiddle as well.

Is this a glitch with Angular HighCharts, or is here something else going on?


问:
Python how to insert extracted title from name field and add it to its specific column and index?
I am trying to extract the title from name field in a dataframe and append into new column using python:

```<code>import pandas as pd
df = pd.DataFrame(columns = ['id', 'name'])
df = df.append({'id': 123, 'name': 'Mr. Rooney'}, ignore_index=True)
df = df.append({'id': 124, 'name': 'Miss. Aniston'}, ignore_index=True)
df = df.append({'id': 125, 'name': 'Sir. Alex'}, ignore_index=True)
</code>```

And then I have the following list containing title names:

```<code>titles = ['Miss.', 'Mr.', 'Master', 'Sir.', 'Mrs.']
</code>```

I've added a new column to the data frame:

```<code>df['Title']=''
</code>```

Now I will iterate all the rows and write the existing title of each name at its corresponding row:

```<code>for idx, row in (df.iterrows()):
  for t in titles:
    if(t in row['name']):
      df['Title']=t
</code>```

Apparently I am not been able to iterate over each index. I am new to python for data science.

How to extract the title for each row and add to its corespondent index?

答:
df['Title']=t is changing the Title column for all the rows. What you want is to change the Title for specific rows, so you need to specify the index in your for loop as shown below in the fourth line:

```<code>for idx, row in (df.iterrows()):
  for t in titles:
    if(t in row['name']):
      df['Title'][idx]=t
</code>```

Body:
I am trying to extract the title from name field in a dataframe and append into new column using python:

import pandas as pd
df = pd.DataFrame(columns = ['id', 'name'])
df = df.append({'id': 123, 'name': 'Mr. Rooney'}, ignore_index=True)
df = df.append({'id': 124, 'name': 'Miss. Aniston'}, ignore_index=True)
df = df.append({'id': 125, 'name': 'Sir. Alex'}, ignore_index=True)

And then I have the following list containing title names:

titles = ['Miss.', 'Mr.', 'Master', 'Sir.', 'Mrs.']

I've added a new column to the data frame:

df['Title']=''

Now I will iterate all the rows and write the existing title of each name at its corresponding row:

for idx, row in (df.iterrows()):
  for t in titles:
    if(t in row['name']):
      df['Title']=t

Apparently I am not been able to iterate over each index. I am new to python for data science.

How to extract the title for each row and add to its corespondent index?

Body:
df['Title']=t is changing the Title column for all the rows. What you want is to change the Title for specific rows, so you need to specify the index in your for loop as shown below in the fourth line:

for idx, row in (df.iterrows()):
  for t in titles:
    if(t in row['name']):
      df['Title'][idx]=t


问:
Passing property as pros in react functional component
I am in the process of learning react. Here i got stuck in some basic problems. I learn concept of props and parent-child components in react, but when i try to implement it, it shows error. Please help. I have one parent component named 'Portfolio' and one child component named 'PortfolioBox'. I try to pass title props in PortfolioBox. Here is my sample code. Issue comes while starting the react app 'npm start'. It shows error 'Portfolio is not defined'.

Portfolio Component

```<code>import React from 'react';
import PortfolioBox from './PortfolioBox';

import './portfolio.css';

function Portfolio()
{
    return (
        <div className="row portfolio-container">
            <PortfolioBox title="One" />
            <PortfolioBox title="Two" />
            <PortfolioBox title="Three" />
            <PortfolioBox title="four" />

        </div>
    )
}

export default Portfolio;

</code>```

Portfolio Box Component

```<code>
import React from 'react';

function PortfolioBox(props)
{
    console.log(props);
    return(
        <div className="col-md-4 portfolio-box">
            <h3>{props.title}</h3>
            <p>Description</p>

        </div>
    )
}

export default PortfolioBox;

</code>```

App.js File

```<code>import React from 'react';

function App() {
  return (
    <div className="container-fluid">
      <Portfolio />

    </div>
  );
}

export default App;

</code>```

答:
You are missing an import statement in your app.js file:

```<code>import React from 'react';
import Portfolio from './Portfolio'; // If your file is in the same directory

function App() {
  return (
    <div className="container-fluid">
      <Portfolio />
    </div>
  );
}

export default App;
</code>```

Body:
I am in the process of learning react. Here i got stuck in some basic problems. I learn concept of props and parent-child components in react, but when i try to implement it, it shows error. Please help. I have one parent component named 'Portfolio' and one child component named 'PortfolioBox'. I try to pass title props in PortfolioBox. Here is my sample code. Issue comes while starting the react app 'npm start'. It shows error 'Portfolio is not defined'.

Portfolio Component

import React from 'react';
import PortfolioBox from './PortfolioBox';

import './portfolio.css';

function Portfolio()
{
    return (

            <PortfolioBox title="One" />
            <PortfolioBox title="Two" />
            <PortfolioBox title="Three" />
            <PortfolioBox title="four" />

    )
}

export default Portfolio;

Portfolio Box Component

import React from 'react';

function PortfolioBox(props)
{
    console.log(props);
    return(

{props.title}

Description

    )
}

export default PortfolioBox;

App.js File

import React from 'react';

function App() {
  return (

      <Portfolio />

  );
}

export default App;

Body:
You are missing an import statement in your app.js file:

import React from 'react';
import Portfolio from './Portfolio'; // If your file is in the same directory

function App() {
  return (
    <div className="container-fluid">
      <Portfolio />
    </div>
  );
}

export default App;


问:
Could not get to a route in asp.net core
Why can't I get to the controller in my asp.net core application. Please see code below.

```<code>using System;
using System.Threading.Tasks;
using HashingApplication;
using Microsoft.AspNetCore.Mvc;
using NgWithJwt.Models;

namespace NgWithJwt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public UserController(ApplicationDbContext context)
        {
            this.context = context;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("add-user")]
        public async Task<IActionResult> AddUser(AppUser model)
        {
            if (ModelState.IsValid)
            {
                var saltValue = Guid.NewGuid().ToString() + model.Password;
                var password = Encryption.Encrypt(model.Password, saltValue);

                model.SaltValue = saltValue;
                model.Password = password;
                model.CreatedDate = DateTime.Now;

                context.Add(model);
                var response = await context.SaveChangesAsync();
                if(response > 0)
                {
                    return Ok(model);
                }
            }
            return BadRequest();
        }
    }
}
</code>```

This is my class for model

```<code> public partial class AppUser
    {
        [Key]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Username is required.")]
        [DisplayName("Username")]
        public string UserName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        public string FirstName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [DisplayName("Middle Name")]
        public string MiddleName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        public string LastName { get; set; }

        [Column(TypeName = "nvarchar(max)")]
        public string SaltValue { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Password is required")]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string UserType { get; set; }
        public DateTime CreatedDate { get; set; }
    }
</code>```

My server is running so I try accessing it with postman like so:

```<code>{
    "Username": "juan",
    "FirstName": "Juan",
    "MiddleName": "A.",
    "LastName": "Dela Cruz",
    "Password": "password",
    "UserType": "User"
}
</code>```

Server is running at

"https://localhost:44366/"

I use this url to post data

http://localhost:44366/api/user/add-user

This is the error I get on postman. I am using the debug mode to get to my controller break point.

答:
Firstly,as @Json's answer,you need to send request by url:https://localhost:44366/XXX.

Then,For 400 Bad Request,you need to remove the following line:

```<code>[HttpPost]
//[ValidateAntiForgeryToken]   //remove this line
[Route("add-user")]
</code>```

Body:
Why can't I get to the controller in my asp.net core application. Please see code below.

using System;
using System.Threading.Tasks;
using HashingApplication;
using Microsoft.AspNetCore.Mvc;
using NgWithJwt.Models;

namespace NgWithJwt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public UserController(ApplicationDbContext context)
        {
            this.context = context;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("add-user")]
        public async Task<IActionResult> AddUser(AppUser model)
        {
            if (ModelState.IsValid)
            {
                var saltValue = Guid.NewGuid().ToString() + model.Password;
                var password = Encryption.Encrypt(model.Password, saltValue);

                model.SaltValue = saltValue;
                model.Password = password;
                model.CreatedDate = DateTime.Now;

                context.Add(model);
                var response = await context.SaveChangesAsync();
                if(response > 0)
                {
                    return Ok(model);
                }
            }
            return BadRequest();
        }
    }
}

This is my class for model

 public partial class AppUser
    {
        [Key]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Username is required.")]
        [DisplayName("Username")]
        public string UserName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        public string FirstName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [DisplayName("Middle Name")]
        public string MiddleName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        public string LastName { get; set; }

        [Column(TypeName = "nvarchar(max)")]
        public string SaltValue { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Password is required")]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string UserType { get; set; }
        public DateTime CreatedDate { get; set; }
    }

My server is running so I try accessing it with postman like so:

{
    "Username": "juan",
    "FirstName": "Juan",
    "MiddleName": "A.",
    "LastName": "Dela Cruz",
    "Password": "password",
    "UserType": "User"
}

Server is running at

"https://localhost:44366/"

I use this url to post data

http://localhost:44366/api/user/add-user

This is the error I get on postman. I am using the debug mode to get to my controller break point.

Body:
Firstly,as @Json's answer,you need to send request by url:https://localhost:44366/XXX.

Then,For 400 Bad Request,you need to remove the following line:

[HttpPost]
//[ValidateAntiForgeryToken]   //remove this line
[Route("add-user")]


问:
How to avoid IAP 30% charges ( IOS Application ) on subscription?
I am working on a matrimonial IOS app which allows users to register as a free member. There is some content on the application for which users need to become a premium member by purchasing a membership package. Each membership package is for a limited period and after that, they need to renew their membership again. Now, IOS is restricting to use IAP only which charges 30%.

Is there any way to avoid this IOS charges? Or any alternative solution where I need t pay minimum charges.

答: You can check great example for using third-party payment for subscription in Netflix & Spotify iOS App. In Netflix you need to signup from website and eroll to your required subscription plan, and in spotify you need to subscribe from website </p>


问:
Usage of pre-trained deep leanring models for commercial usage
There are various pre-trained deep learing models availabel which are trained using data present in ImageNet(or any other data source) like AlexNet, VGGNet, Inception, ResNet, Xception, MobileNet, SqueezeNet etc. I want to develop a certain object detection application which will be ultimately sold to the customer.
I have few questions as follows:

Can we use these pre-trained deep learing models for commercial use direclty?

If object of interest is not supported by these models, can we use their architecture and perform learning using our own data set and use it for commercial use.

Any suggestions would be highly appreciated.

答:
All Source code in GitHub has a license. The License explains whether the code can be used or not. If used then under what circumstances and whether and what you owe to the creators when implementing the code for your science project or as a product that you want to launch.

Some are free and has no problems with it being modified and used where others are more protected.

Please go through the different licenses usually used and understand what are the key points of the license on the code you want to use to avoid legal disputes in the future.

In the case where the license does not care what you do with the code..both the answers to your above 2 questions is yes..


问:
Invalid initialization of reference of type error
A million thanks to anyone, who is willing to help me with this.

First, the code:

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

void Beolvas (vector<vector<int> > mat);
bool VanNemNull (const vector<vector<int> > &mat);

int main()
{
cout << "Van-e a mátrixnak olyan oszlopa, hogy a főátló alatt csak 0-át tartalmaz, és ha igen, akkor melyik az?\n" <<endl;

    char ch;
    do{
        // Adatbevitel
        vector<vector<int> > mat;
        Beolvas(mat);

        //Kiértékelés
        int i;
       if (VanNemNull(&mat[i])) cout<<"szupiiiiii";

        cout<< endl << "Futtassam újra?   (I/N)";cin>>ch;
        }while (ch!='n' && ch!='N');
    return 0;
}

void Beolvas(vector<vector<int> > mat)
{
    ifstream fajl;
    bool hiba;
    string str;

    do{
        cout << "Fajl neve:";
        cin >> str;
        fajl.open(str.c_str());
        if (hiba = fajl.fail())
        {
            cout << "Nincs ilyen nevű fájl" << endl;
            fajl.clear();
        }
    }while (hiba);

    int n;
    fajl >> n;
    if (n<1)
    {
        cout<<"Helytelen a mátrix mérete\n Kérem ellenőrizze a forrásfájlt!\n";
        cout<<"E megnyomásával kilép"<<endl;

    char ex;
    do{
        cin>>ex;
        }while (ex!='e' && ex!='E');exit(0);
    }

    mat.resize(n);
    for(int i=0; i<n; ++i)
        {
            mat[i].resize(n);
            for (int j=0; j<n; ++j)
            {
                fajl >> mat[i][j];
            }
        }
    fajl.close();
    cout<<"A mátrix a következöképpen néz ki:"<<"\n";
    cout<<"Elemszáma: "; cout<<n*n<<"\n";
    for (int i=0; i<n; ++i)
        {
            for (int j=0; j<n; ++j)
            {
                cout<<mat[i][j]<<"\t";
            }
            cout<<"\n";

        }

}

/*void Vansor (const vector<vector<int> > mat)
{
    //bool l = false;
}*/

bool VanNemNull (const vector<vector<int> > mat)
{
    bool l = false;
    int i=0;
    cout<<(int)mat.size();
    for (int j=i+1; !l && j<(int)mat.size(); ++j)
    {
        cout<<mat[j][i]<<"\n";
        if (l) cout<<"hej\n";
        l = (mat[j][i]!=0);
        if (l= true) cout<<"22"; else cout<<"11";

    }
    return (l);
}
</code>```

The main problem (I think) is the last part. Also, I get these error messages:

```<code>||In function `int main()':|
|23|error: invalid initialization of reference of type 'const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&' from expression of type 'std::vector<int, std::allocator<int> >*'|
|9|error: in passing argument 1 of `bool VanNemNull(const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&)'|
||=== Build finished: 2 errors, 0 warnings ===|
</code>```

答:
First your compile-error:

```<code>vector<vector<int> > mat;
...
if (VanNemNull(&mat[i])) cout<<"szupiiiiii";
</code>```

does not match : bool VanNemNull (const vector<vector<int> > mat);

you are passing a copy of a vector_of_ints (an element of vector_of_vector_of_int) as parameter.
You should either call it like this :

```<code>if (VanNemNull(mat)) ...
</code>```

or change the function to look like this :

```<code> bool VanNemNull (const vector<int> > mat);
</code>```

and change the implemetation (in regard to usage of mat[j][i]).

Also you use the variable i in if (VanNemNull(&mat[i]) whithout initializing i.

Second ,your call to

```<code>void Beolvas(vector<vector<int> > mat );
</code>```

is also done with a copy of mat ,so the changes you make in BeolVas(..) are applied to that copy and will be lost when the function returns.
you should change it to :

void Beolvas(vector<vector<int> >&  mat )

Body:
A million thanks to anyone, who is willing to help me with this.

First, the code:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

void Beolvas (vector<vector<int> > mat);
bool VanNemNull (const vector<vector<int> > &mat);

int main()
{
cout << "Van-e a mátrixnak olyan oszlopa, hogy a főátló alatt csak 0-át tartalmaz, és ha igen, akkor melyik az?\n" <<endl;

    char ch;
    do{
        // Adatbevitel
        vector<vector<int> > mat;
        Beolvas(mat);

        //Kiértékelés
        int i;
       if (VanNemNull(&mat[i])) cout<<"szupiiiiii";

        cout<< endl << "Futtassam újra?   (I/N)";cin>>ch;
        }while (ch!='n' && ch!='N');
    return 0;
}

void Beolvas(vector<vector<int> > mat)
{
    ifstream fajl;
    bool hiba;
    string str;

    do{
        cout << "Fajl neve:";
        cin >> str;
        fajl.open(str.c_str());
        if (hiba = fajl.fail())
        {
            cout << "Nincs ilyen nevű fájl" << endl;
            fajl.clear();
        }
    }while (hiba);

    int n;
    fajl >> n;
    if (n<1)
    {
        cout<<"Helytelen a mátrix mérete\n Kérem ellenőrizze a forrásfájlt!\n";
        cout<<"E megnyomásával kilép"<<endl;

    char ex;
    do{
        cin>>ex;
        }while (ex!='e' && ex!='E');exit(0);
    }

    mat.resize(n);
    for(int i=0; i<n; ++i)
        {
            mat[i].resize(n);
            for (int j=0; j<n; ++j)
            {
                fajl >> mat[i][j];
            }
        }
    fajl.close();
    cout<<"A mátrix a következöképpen néz ki:"<<"\n";
    cout<<"Elemszáma: "; cout<<n*n<<"\n";
    for (int i=0; i<n; ++i)
        {
            for (int j=0; j<n; ++j)
            {
                cout<<mat[i][j]<<"\t";
            }
            cout<<"\n";

        }

}

/*void Vansor (const vector<vector<int> > mat)
{
    //bool l = false;
}*/

bool VanNemNull (const vector<vector<int> > mat)
{
    bool l = false;
    int i=0;
    cout<<(int)mat.size();
    for (int j=i+1; !l && j<(int)mat.size(); ++j)
    {
        cout<<mat[j][i]<<"\n";
        if (l) cout<<"hej\n";
        l = (mat[j][i]!=0);
        if (l= true) cout<<"22"; else cout<<"11";

    }
    return (l);
}

The main problem (I think) is the last part. Also, I get these error messages:

||In function `int main()':|
|23|error: invalid initialization of reference of type 'const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&' from expression of type 'std::vector<int, std::allocator<int> >*'|
|9|error: in passing argument 1 of `bool VanNemNull(const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&)'|
||=== Build finished: 2 errors, 0 warnings ===|

Body:
First your compile-error:

vector<vector<int> > mat;
...
if (VanNemNull(&mat[i])) cout<<"szupiiiiii";

does not match : bool VanNemNull (const vector<vector<int> > mat);

you are passing a copy of a vector_of_ints (an element of vector_of_vector_of_int) as parameter.
You should either call it like this :

if (VanNemNull(mat)) ...

or change the function to look like this :

 bool VanNemNull (const vector<int> > mat);

and change the implemetation (in regard to usage of mat[j][i]).

Also you use the variable i in if (VanNemNull(&mat[i]) whithout initializing i.

Second ,your call to

void Beolvas(vector<vector<int> > mat );

is also done with a copy of mat ,so the changes you make in BeolVas(..) are applied to that copy and will be lost when the function returns.
you should change it to :

void Beolvas(vector<vector<int> >&  mat )


问:
How to get substring ends with multiple characters and have at least n characters
I want to get substring that ends with 'd', 'g', 'y' and the substring contains at least five characters.

str = 'Did David go swimming yesterday'

The result should be 'David', 'swimming' and 'yesterday'

How to use regex to do it?

Thank you.

答:
Try this regex: [^\s]{4,}[dgy]\b

[^\s] to match any non-whitespace character.

{4,} to match at least 4 of the characters described above.

[dgy] to match the last character of the word.

\b to match a word boundary.

I would recommend checking out https://regexr.com/ to help you solve a regex problem.


问:
My Python code pass simple tests but not extended ones due to performance constrains
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result
```

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.

答:
You are correct in figuring out that it's O(n^2) which is causing the time limit exceeded error.

Instead of using two for loops to check occurrences for each character, can you think of a way to do it in one simple pass through the string and store it?

That would significantly reduce the execution time.

You are correct in terms of space complexity.

Body:
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.


问:
Learning Python. Having trouble with the tkinter widget.Grid manager and adding a scrollbar to a listbox widget
I got most of this attached code from another question.  I'm using Python 3.8.  It would seem that the Pack Manager will easily add a scrollbar widget to a listbox widget.  However, I'm using the Grid Manager.  I can't get a vertical scrollbar to work properly.

When you run this code,  a vertical scrollbar will appear, but it is not physically attached to the listbox widget properly.  BTW: I got the horizontal scrollbar working without a problem.

```<code>from tkinter import *

master = Tk()

listbox = Listbox(master)

scrollbar = Scrollbar(master, orient=VERTICAL)
scrollbar.grid(row=2, rowspan=50, column=40, sticky=N + S)

for i in range(50):
    listbox.insert(END, str(i))
listbox.grid(sticky="news")

scrollbar.config(command=listbox.yview)

mainloop()
</code>```

答:
If you think pack() is more easier, then you can pack the Listbox and Scrollbar inside a Frame and then use grid() on the frame:

```<code>import tkinter as tk

master = tk.Tk()

frame = tk.Frame(master)
frame.grid(row=0, column=0) # set row and column to the desired position

listbox = tk.Listbox(frame)
listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL, command=listbox.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

listbox.config(yscrollcommand=scrollbar.set)
for i in range(50):
    listbox.insert(tk.END, str(i))

master.mainloop()
</code>```

Body:
I got most of this attached code from another question.  I'm using Python 3.8.  It would seem that the Pack Manager will easily add a scrollbar widget to a listbox widget.  However, I'm using the Grid Manager.  I can't get a vertical scrollbar to work properly.

When you run this code,  a vertical scrollbar will appear, but it is not physically attached to the listbox widget properly.  BTW: I got the horizontal scrollbar working without a problem.

from tkinter import *

master = Tk()

listbox = Listbox(master)

scrollbar = Scrollbar(master, orient=VERTICAL)
scrollbar.grid(row=2, rowspan=50, column=40, sticky=N + S)

for i in range(50):
    listbox.insert(END, str(i))
listbox.grid(sticky="news")

scrollbar.config(command=listbox.yview)

mainloop()

Body:
If you think pack() is more easier, then you can pack the Listbox and Scrollbar inside a Frame and then use grid() on the frame:

import tkinter as tk

master = tk.Tk()

frame = tk.Frame(master)
frame.grid(row=0, column=0) # set row and column to the desired position

listbox = tk.Listbox(frame)
listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL, command=listbox.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

listbox.config(yscrollcommand=scrollbar.set)
for i in range(50):
    listbox.insert(tk.END, str(i))

master.mainloop()


问:
Is there any limit to store the files inside the app-specific storage[data/data/{packagename}] in Android?
Usecase: I would like to store the files into the app-specific storage completely so that no one can access the files directly.

I have stored files into the internal storage[storage/emulated/xxx/xxx] and app-specific storage[data/data/com.x.x]but I didn't get any exceptions from the device until storage is full. I couldn't find anything about the restriction of app-specific storage in Android Docs, is there any limit really? Please find the devices which I have tested below.

Samsung Tab 32GB    [Stored up to 20GB in app-specific storage]

Samsung S10 128GB   [Stored up to 100GB in app-specific storage]

OnePlus7 128GB      [Stored up to 100GB in app-specific storage]

As per my R&D on app-specific storage, there are no limitations. But I can't find this in the Android documentation. Can someone help me with this?

答:
Yes, there is no storage limit specified in the android document. But it mentioned that "Internal storage has limited space for app-specific data. Use other types of storage if you need to save a substantial amount of data."

You can write the multiple files unless storage is available otherwise it will throw the IOException.

It is also mentioned that "if you read or write the same files for multiple times then it can impact the application performance" if you are using app-specific storage.

It basically stores the files that are meant for your app's use only.

So choose storage wisely.

You can read more information here or Android Dev Summit '19.

I hope it helps you!


问:
What's the pythonic way to set class variables?
perhaps I'm asking the wrong question.  I have code like this:

```<code>class ExpressionGrammar(Grammar):
  def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
    self.nonterminals = nonterminals
    self.terminals = terminals
    self.rules = rules
    self.macros = macros
    self.precedence = precedence
    self.nonterminal = nonterminal
</code>```

and I find it redundant to always have to to self.x = x.  I know python tries to avoid repetition, so what would be the correct way to do something like this?

答:
You can avoid doing that with something like:

```<code>class C(object):
    def __init__(self, x, y, z, etc):
        self.__dict__.update(locals())
</code>```

then all these arguments become members (including the self argument). So you may remove it with: self.__dict__.pop('self')

I don't know how pythonic this approach is, but it works.

PS:
If you're wondering what __dict__ is, it's a dict that holds every member of an instance in the form {'member1': value, 'member2': value}

locals() is a function that returns a dict with local variables.

Body:
perhaps I'm asking the wrong question.  I have code like this:

class ExpressionGrammar(Grammar):
  def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
    self.nonterminals = nonterminals
    self.terminals = terminals
    self.rules = rules
    self.macros = macros
    self.precedence = precedence
    self.nonterminal = nonterminal

and I find it redundant to always have to to self.x = x.  I know python tries to avoid repetition, so what would be the correct way to do something like this?

Body:
You can avoid doing that with something like:

class C(object):
    def __init__(self, x, y, z, etc):
        self.__dict__.update(locals())

then all these arguments become members (including the self argument). So you may remove it with: self.__dict__.pop('self')

I don't know how pythonic this approach is, but it works.

PS:
If you're wondering what __dict__ is, it's a dict that holds every member of an instance in the form {'member1': value, 'member2': value}

locals() is a function that returns a dict with local variables.


问:
Why am I getting a segmention fault?
For my class, we are using two compilers, xcode and codeboard, where codeboard is the more rigorous of the two and has a list of preset asserts to test your code. In my code for function a, I have nested loops, where I want i to always be one ahead of k. It works fine in xcode, but gives me a segmentation fault on codeboard.

```<code>for (int k = 0; k <= n-2; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] == array[i])
</code>```

What's strange is if I use k++ or ++k instead of k+1, it won't result in a segmentation fault, but my code won't pass all the asserts. I thought they were supposed to be the same thing?

What's even more strange is if I use k+1 in function b, it doesn't result in an error in codeboard.

```<code>for (int k = 0; k <= n-1; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] > array[i])
</code>```

Basically, what is happening here?

Edit: So, what I'm getting from everyone is that when I use i = k+1 in the inner loop, it increases the k value in the outer loop. Like, if k=1, i=2, then when it goes back to the outer loop, k=3. If that's the case, how would I get i from staying ahead of k?

Edit: Please ignore the k++ and k+1 part of my question, that was not really my main issue, just a side thing that kind of confused me, but I get the difference now. I'd delete that part from my post, but I'm pretty sure that's not allowed. My main question is how to keep my i value 1 greater than my k value.

In the following code, the goal is if any of the array values are the same, it should cout true at some point. In regards to reproducible results:

```<code>string a[3] = {"aaa", "bbbb", "cccc"};
int n = 3;
for (int k = 0; k <= n-2; k++) {
    int b = 0;
    for (int i = k+1; i <= n-1; i++) {
        if (a[k] == a[i])
            b++;
    }
    if (b != 0) {
        cout << "true" << endl;
        break;
    }
    else
        cout << "false" << endl;
}
</code>```

答:
No, they're not the same:

k + 1

Returns the value of k plus one, but does not change the value of k itself.

++k

Adds 1 to k and returns the new value (pre-increment).

k++

Also adds 1 to k but returns the previous value of k (post-increment).

Title: Why am I getting a segmention fault?

Body:
For my class, we are using two compilers, xcode and codeboard, where codeboard is the more rigorous of the two and has a list of preset asserts to test your code. In my code for function a, I have nested loops, where I want i to always be one ahead of k. It works fine in xcode, but gives me a segmentation fault on codeboard.

for (int k = 0; k <= n-2; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] == array[i])

What's strange is if I use k++ or ++k instead of k+1, it won't result in a segmentation fault, but my code won't pass all the asserts. I thought they were supposed to be the same thing?

What's even more strange is if I use k+1 in function b, it doesn't result in an error in codeboard.

for (int k = 0; k <= n-1; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] > array[i])

Basically, what is happening here?

Edit: So, what I'm getting from everyone is that when I use i = k+1 in the inner loop, it increases the k value in the outer loop. Like, if k=1, i=2, then when it goes back to the outer loop, k=3. If that's the case, how would I get i from staying ahead of k?

Edit: Please ignore the k++ and k+1 part of my question, that was not really my main issue, just a side thing that kind of confused me, but I get the difference now. I'd delete that part from my post, but I'm pretty sure that's not allowed. My main question is how to keep my i value 1 greater than my k value.

In the following code, the goal is if any of the array values are the same, it should cout true at some point. In regards to reproducible results:

string a[3] = {"aaa", "bbbb", "cccc"};
int n = 3;
for (int k = 0; k <= n-2; k++) {
    int b = 0;
    for (int i = k+1; i <= n-1; i++) {
        if (a[k] == a[i])
            b++;
    }
    if (b != 0) {
        cout << "true" << endl;
        break;
    }
    else
        cout << "false" << endl;
}


问:
foreach display only first 3 items
We use a foreach code and we want to display only the first 3 items.
But for some reason our code does not work, it currently still display all items.

What am I missing here?

CODE:

```<code><?php $items = $_order->getAllItems(); $i = 0; foreach($items as $i): if($i < 3) {?>
    <li class="order-row-item">
        <div class="order-row-product">
            <div class="order-row-product-image">
                <img src="<?php echo $_product = Mage::getModel('catalog/product')->load($i->getProductId())->getSmallImageUrl();?>" border="0" />       </div>
            <div class="order-row-product-name">
                <?php echo substr($this->escapeHtml($i->getName()), 0, 20) ?>
            </div>
        </div>
    </li>
<?php $i++; } endforeach;?>
</code>```

答:
```<code>    $count='1';
      for ( $i = 0; $i <= 100; $i++ ) {
        if ( $var[$i] == "value" ) {
          print $i.'-'.$var[$i] . "<br>"; // print $i to display row number
          if ( $count++ >= 3 ) {
            break;
          }else{
           // have a cup of coffee ;)
        }
      }
</code>```

Title: foreach display only first 3 items

Body:
We use a foreach code and we want to display only the first 3 items.
But for some reason our code does not work, it currently still display all items.

What am I missing here?

CODE:

<?php $items = $_order->getAllItems(); $i = 0; foreach($items as $i): if($i < 3) {?>

                <img src="<?php echo $_product = Mage::getModel('catalog/product')->load($i->getProductId())->getSmallImageUrl();?>" border="0" />

                <?php echo substr($this->escapeHtml($i->getName()), 0, 20) ?>

<?php $i++; } endforeach;?>


问:
Apache Flink - Counter value displayed but meter values not displayed
We are using Flink 1.8.0 and running it on EMR - Yarn and would like to measure the throughput.

Because our operators are chained, we have added meters and counters in our code - essentially an async operator that makes API calls with kinesis as both source and sync. In the Application Master i.e. Flink's web UI, we are able to get the value for the counters but not the meters.

```<code>public class AsyncClass extends RichAsyncFunction<String, String> {

    private transient Counter counter;

    private transient Meter meter;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        this.counter = getRuntimeContext()
                  .getMetricGroup()
                  .counter("myCounter");

        this.meter = getRuntimeContext()
                .getMetricGroup()
                .meter("myMeter", new DropwizardMeterWrapper(new com.codahale.metrics.Meter()));
    }

    @Override
    public void close() throws Exception {
        super.close();
        ExecutorUtils.gracefulShutdown(20000, TimeUnit.MILLISECONDS, executorService);
    }

    @Override
    public void asyncInvoke(String key, final ResultFuture<String> resultFuture) throws Exception {

        resultFuture.complete(key);
        this.meter.markEvent();
        this.counter.inc();

    }
}
</code>```

To measure the complete throughput of the application, we obviously need the throughput of all the task managers together. Using meters, we are able to get the metrics for individual task managers. Is there any way to measure it at the operator level?

答: Turns out the meter displays whole number values and the rate is measured in decimals. When my load was a constant 1 event per second, it was actually measured as 0.9xxx something and hence was showing only 0 events per second.</p>

Body:
We are using Flink 1.8.0 and running it on EMR - Yarn and would like to measure the throughput.

Because our operators are chained, we have added meters and counters in our code - essentially an async operator that makes API calls with kinesis as both source and sync. In the Application Master i.e. Flink's web UI, we are able to get the value for the counters but not the meters.

public class AsyncClass extends RichAsyncFunction<String, String> {

    private transient Counter counter;

    private transient Meter meter;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        this.counter = getRuntimeContext()
                  .getMetricGroup()
                  .counter("myCounter");

        this.meter = getRuntimeContext()
                .getMetricGroup()
                .meter("myMeter", new DropwizardMeterWrapper(new com.codahale.metrics.Meter()));
    }

    @Override
    public void close() throws Exception {
        super.close();
        ExecutorUtils.gracefulShutdown(20000, TimeUnit.MILLISECONDS, executorService);
    }

    @Override
    public void asyncInvoke(String key, final ResultFuture<String> resultFuture) throws Exception {

        resultFuture.complete(key);
        this.meter.markEvent();
        this.counter.inc();

    }
}

To measure the complete throughput of the application, we obviously need the throughput of all the task managers together. Using meters, we are able to get the metrics for individual task managers. Is there any way to measure it at the operator level?


问:
How do I disallow download file through direct url access?
I am currently working on a project that allows user to update and patch their application when updates are available. I am using Apache as web server and put my patch files in the webroot. The application download the patch files through https (I am using a patching system bought from unity assets stores. It supports http, https and ftp. It is done in c#). I have disable directory listing for better security, however I still able to download specific files through browser if I specify the path. For example:
https://example.com/patch/test.txt

Is there any way I can restrict user from downloading the files directly through url? Is there any better approach that I can improve the security?

Thank you.

答:
To prevent file download when:

User copy & paste URL directly into browser and hit enter

User clicking direct link
from some other website

You may consider the following options:

Your Update Client set Custom HTTP Header or Cookies prior to
requesting file from server, then Server (PHP) check if either of them is
presence then serve the file.

Since you are using Apache web server, you could use RewriteRule to do the same as above option.

Example .htaccess:

Check for Cookie:

```<code>RewriteEngine on
RewriteCond %{HTTP_COOKIE} !YourMagicCookie=123456 [NC]
RewriteRule ^ - [F]
</code>```

Check for custom HTTP header:

```<code>RewriteEngine on
RewriteCond %{HTTP:X-YourUpdateClient} !^$
RewriteRule ^ - [F]
</code>```

Body:
To prevent file download when:

User copy & paste URL directly into browser and hit enter

User clicking direct link
from some other website

You may consider the following options:

Your Update Client set Custom HTTP Header or Cookies prior to
requesting file from server, then Server (PHP) check if either of them is
presence then serve the file.

Since you are using Apache web server, you could use RewriteRule to do the same as above option.

Example .htaccess:

Check for Cookie:

RewriteEngine on
RewriteCond %{HTTP_COOKIE} !YourMagicCookie=123456 [NC]
RewriteRule ^ - [F]

Check for custom HTTP header:

RewriteEngine on
RewriteCond %{HTTP:X-YourUpdateClient} !^$
RewriteRule ^ - [F]


问:
Is data safety guaranteed while using `ThreadPoolExecutor` from python's `future` module?
I'm looking for a conceptual answer on this question.

I'm wondering whether using ThreadPool in python to perform concurrent tasks, guarantees that data is not corrupted; I mean multiple threads don't access the critical data at the same time.

If so, how does this ThreadPoolExecutor internally works to ensure that critical data is accessed by only one thread at a time?

答:
If so, how does this ThreadPoolExecutor internally works to ensure that critical data is accessed by only one thread at a time?

It doesn't, that's your job.

The high-level methods like map will use a safe work queue and not share work items between threads, but if you've got other resources which can be shared then the pool does not know or care, it's your problem as the developer.


问:
Sonal lint : change this condition so that it does not always evaluate to true
I am trying to consume Data JPA Repository from From Java Service which is something like below:

```<code>@Service
public class APIKeyServiceImpl implements APIKeyService {

    private APIKeyRepo apiKeyRepo;

    @Autowired
    public APIKeyServiceImpl(APIKeyRepo apiKeyRepo) {
        this.apiKeyRepo = apiKeyRepo;
    }

    @Override
    public String save(String apiKeyInput) {

        APIKEY apikey = new APIKEY();
        apikey.setApikey(apiKeyInput);

        APIKEY savedKey = apiKeyRepo.save(apikey);

        return null != savedKey ? savedKey.getApikey() : null;
    }

}
</code>```

Now Short Repo Code is below:

```<code>public interface APIKeyRepo extends JpaRepository<APIKEY, String> {

}
</code>```

Problem is whenever I run Sonarlint Report then I am getting below major issue:

change this condition so that it does not always evaluate to true

Which is occurring at ternary operator code which is :

```<code>return null != savedKey ? savedKey.getApikey() : null;
</code>```

I havn't much understand which part of this will always evaluate true.

答:
As you save an entity save method will return you the saved entity, which can never be null.

Source: Method Doc.

Body:
I am trying to consume Data JPA Repository from From Java Service which is something like below:

@Service
public class APIKeyServiceImpl implements APIKeyService {

    private APIKeyRepo apiKeyRepo;

    @Autowired
    public APIKeyServiceImpl(APIKeyRepo apiKeyRepo) {
        this.apiKeyRepo = apiKeyRepo;
    }

    @Override
    public String save(String apiKeyInput) {

        APIKEY apikey = new APIKEY();
        apikey.setApikey(apiKeyInput);

        APIKEY savedKey = apiKeyRepo.save(apikey);

        return null != savedKey ? savedKey.getApikey() : null;
    }

}

Now Short Repo Code is below:

public interface APIKeyRepo extends JpaRepository<APIKEY, String> {

}

Problem is whenever I run Sonarlint Report then I am getting below major issue:

change this condition so that it does not always evaluate to true

Which is occurring at ternary operator code which is :

return null != savedKey ? savedKey.getApikey() : null;

I havn't much understand which part of this will always evaluate true.


问:
How to join two different databases' tables in C# with Linq?
I try to join two different databases tables in c# but it gives me an error  how can I handle that ?

this is my query:

```<code> var list = (from h in db.database1.AsEnumerable()
                        join j in NV_DB.database2.AsEnumerable()
                        on h.Creation_Date equals j.Creation_Date
                        where j.Ship_Status == 3 && h.CustomerNo == CustomerNo
                        select new
                        {
                            shipName = h.ShipName,
                            creationDate = j.Creation_Date,
                            endingDate = j.Ending_Date
                        }
                        ).ToList();
</code>```

if I do like this it gives me System.OverflowException error. But when I run this in sql, it gives me just 30 records*

答:
You need to remove °AsEnumerable`. While it does not run the sql, when you use it in the where it actually brings the entire tables in memory and then performs the job where part of your query

Your answer is basically the first comment in the accepted answer here: Am I misunderstanding LINQ to SQL .AsEnumerable()?

While AsEnumerable doesn't evaluate the query at the time that it's called , it definitely has an effect. Anything further called on the query will be evaluated using LINQ to objects, so you can't compose additional elements onto the query (another Where or an OrderBy or anything of that nature) that will become part of the SQL statement.

In depth explanation here: https://www.codeproject.com/Articles/732425/IEnumerable-Vs-IQueryable

While querying data from database, IEnumerable executes select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.

While querying data from database, IQueryable executes select query on server side with all filters. Hence does less work and becomes fas

Body:
I try to join two different databases tables in c# but it gives me an error  how can I handle that ?

this is my query:

 var list = (from h in db.database1.AsEnumerable()
                        join j in NV_DB.database2.AsEnumerable()
                        on h.Creation_Date equals j.Creation_Date
                        where j.Ship_Status == 3 && h.CustomerNo == CustomerNo
                        select new
                        {
                            shipName = h.ShipName,
                            creationDate = j.Creation_Date,
                            endingDate = j.Ending_Date
                        }
                        ).ToList();

if I do like this it gives me System.OverflowException error. But when I run this in sql, it gives me just 30 records*


答:
k++ and ++k both increase k by one, changing the value of k.

k+1 does not.

Your segmentation fault comes from the fact that you are increasing k every time  your initial for-loop is evaluated but also every time your second for loop is initialized. This means that you're reading further than your array at the end of your loop.

Title: Why am I getting a segmention fault?


问:
Windows Terminal and (MinGW, Cygwin)
It appears Microsoft are to introduce "Windows Terminal", see https://devblogs.microsoft.com/commandline/introducing-windows-terminal/
It appears that you will be able to programme in C.

I was thinking of installing either MinGW or Cygwin so that I could write some programmes in C. Will the introduction of Windows Terminal make these redundant?

答:
As described in: https://github.com/microsoft/terminal/blob/master/doc/user-docs/ThirdPartyToolProfiles.md

Assuming that you've installed Cygwin into C:/Cygwin:

```<code>{
    "guid": "{916f2925-597a-4b52-aac2-9a4387626b4c}",
    "name" : "Cygwin",
    "commandline" : "C:/Cygwin/bin/bash --login -i",
    "icon" : "C:/Cygwin/Cygwin.ico",
    "startingDirectory" : "C:/Cygwin/bin"
}
</code>```

Note that the starting directory of Cygwin is set as it is to make the path work. The default directory opened when starting Cygwin will be $HOME because of the --login flag.

FYI: Following works on my PC using Cygwin64:

```<code>{
    "guid": "{379bd4d8-dc40-409a-abd4-3ff1712c12f7}",
    "name" : "Cygwin",
    "commandline" : "c:/cygwin64/bin/bash --login -i",
    "icon" : "c:/cygwin64/Cygwin.ico",
    "startingDirectory" : "c:/cygwin64/bin"
}
</code>```

Title: Windows Terminal and (MinGW, Cygwin)

Body:
As described in: https://github.com/microsoft/terminal/blob/master/doc/user-docs/ThirdPartyToolProfiles.md

Assuming that you've installed Cygwin into C:/Cygwin:

{
    "guid": "{916f2925-597a-4b52-aac2-9a4387626b4c}",
    "name" : "Cygwin",
    "commandline" : "C:/Cygwin/bin/bash --login -i",
    "icon" : "C:/Cygwin/Cygwin.ico",
    "startingDirectory" : "C:/Cygwin/bin"
}

Note that the starting directory of Cygwin is set as it is to make the path work. The default directory opened when starting Cygwin will be $HOME because of the --login flag.

FYI: Following works on my PC using Cygwin64:

{
    "guid": "{379bd4d8-dc40-409a-abd4-3ff1712c12f7}",
    "name" : "Cygwin",
    "commandline" : "c:/cygwin64/bin/bash --login -i",
    "icon" : "c:/cygwin64/Cygwin.ico",
    "startingDirectory" : "c:/cygwin64/bin"
}


问:
How can I extract contents from a file stored in gitlab repos
Using the gitlab-python package, I'd like to extract lines from all Dockerfiles. Using my code below, I am able to get project names and url to the repo I want but how can I ensure there is a Dockerfile and read the contents of the Dockerfile. </p>

```<code>import gitlab
import json
from pprint import pprint
import requests
import urllib.request

# private token authentication
gl = gitlab.Gitlab('<path_to_gitlab_repo>', private_token=<token_here>)

gl.auth()

# list all projects
projects = gl.projects.list()
for project in projects:
    # print(project) # prints all the meta data for the project
    print("Project: ", project.name)
    print("Gitlab URL: ", project.http_url_to_repo)
    # print("Branches: ", project.repo_branches)
    pprint(project.repository_tree(all=True))
    f = urllib.request.urlopen(project.http_url_to_repo)
    myfile = f.read()
    print(myfile)
    print("\n\n")
</code>```

<p>The output I get now is : </p>

```<code>Gitlab URL:  <path_to_gitlab_repo>
[{'id': '0c4a64925f5c129d33557',
  'mode': '1044',
  'name': 'README.md',
  'path': 'README.md',
  'type': 'blob'}]
</code>```

答:
You can use the project.files.get() method (see documentation) to get the Dockerfile of the project.

You can then print the content of the Dockerfile/do whatever you want to do with it like this:

```<code>import gitlab
import base64

# private token authentication
gl = gitlab.Gitlab(<gitlab-url>, private_token=<private-token>)

gl.auth()

# list all projects
projects = gl.projects.list(all=True)
for project in projects:
    # print(project) # prints all the meta data for the project
    # print("Project: ", project.name)
    # print("Gitlab URL: ", project.http_url_to_repo)

    # Skip projects without branches
    if len(project.branches.list()) == 0:
        continue

    branch = project.branches.list()[0].name

    try:
        f = project.files.get(file_path='Dockerfile', ref=branch)
    except gitlab.exceptions.GitlabGetError:
        # Skip projects without Dockerfile
        continue

    file_content = base64.b64decode(f.content).decode("utf-8")
    print(file_content.replace('\\n', '\n'))

</code>```

You might have to adjust the branch name in case there are multiple branches.

Body:
Using the gitlab-python package, I'd like to extract lines from all Dockerfiles. Using my code below, I am able to get project names and url to the repo I want but how can I ensure there is a Dockerfile and read the contents of the Dockerfile.

import gitlab
import json
from pprint import pprint
import requests
import urllib.request

# private token authentication
gl = gitlab.Gitlab('<path_to_gitlab_repo>', private_token=<token_here>)

gl.auth()

# list all projects
projects = gl.projects.list()
for project in projects:
    # print(project) # prints all the meta data for the project
    print("Project: ", project.name)
    print("Gitlab URL: ", project.http_url_to_repo)
    # print("Branches: ", project.repo_branches)
    pprint(project.repository_tree(all=True))
    f = urllib.request.urlopen(project.http_url_to_repo)
    myfile = f.read()
    print(myfile)
    print("\n\n")

The output I get now is :

Gitlab URL:  <path_to_gitlab_repo>
[{'id': '0c4a64925f5c129d33557',
  'mode': '1044',
  'name': 'README.md',
  'path': 'README.md',
  'type': 'blob'}]

Body:
You can use the project.files.get() method (see documentation) to get the Dockerfile of the project.

You can then print the content of the Dockerfile/do whatever you want to do with it like this:

import gitlab
import base64

# private token authentication
gl = gitlab.Gitlab(<gitlab-url>, private_token=<private-token>)

gl.auth()

# list all projects
projects = gl.projects.list(all=True)
for project in projects:
    # print(project) # prints all the meta data for the project
    # print("Project: ", project.name)
    # print("Gitlab URL: ", project.http_url_to_repo)

    # Skip projects without branches
    if len(project.branches.list()) == 0:
        continue

    branch = project.branches.list()[0].name

    try:
        f = project.files.get(file_path='Dockerfile', ref=branch)
    except gitlab.exceptions.GitlabGetError:
        # Skip projects without Dockerfile
        continue

    file_content = base64.b64decode(f.content).decode("utf-8")
    print(file_content.replace('\\n', '\n'))

You might have to adjust the branch name in case there are multiple branches.