text:
Q: BST intersection, NullPointerException I am trying to create a new BST from the intersection of 2 known BSTs. I am getting a NullPointerException in the intersect2 method int he second case, at the line  "cur3.item.set_account_id(cur1.item.get_accountid()+ cur2.item.get_accountid());". I know you get the error when you try to dereference the variable without initializing it but i think i am initializing it? I'm not really sure. I would appreciate the help.
public static Bst<Customer> intersect(Bst<Customer> a, Bst<Customer> b){
     return( intersect2(a.root, b.root));
 }

  public static Bst<Customer> intersect2(BTNode<Customer> cur1, BTNode<Customer> cur2){
  Bst<Customer> result = new Bst<Customer>();

// 1. both empty -> true
  if (cur1==null && cur2==null){
  result=null;
 }
// 2. both non-empty -> compare them
 else if (cur1!=null && cur2!=null) {
  BTNode<Customer> cur3 = new BTNode<Customer>();
  cur3.item.set_account_id(cur1.item.get_accountid()+ cur2.item.get_accountid());
  result.insert(cur3.item);
  intersect2(cur1.left, cur2.left);
  intersect2(cur1.right, cur2.right);
 }

// 3. one empty, one not -> false
else if (cur1==null ||cur2==null){
  BTNode<Customer> cur3 = new BTNode<Customer>();
  cur3.item=null;
  intersect2(cur1.left, cur2.left);
  intersect2(cur1.right, cur2.right);
}
 return result;
}

Here is the image of the problem:

A: A NullPointerException can be caused by a number of things. In your given example, cur1 and cur2 are not null, but there is no guarantee that cur1.item, cur1.item.accountId (and similarly for cur2) are not null.
Being as you have no description for the underlying implementation, I cannot assist further.
I can suggest that you do some of a few things:
1.) check the implementation of your objects (if this happens EVERY time, there may be some sort of initialization problem.
2.) Whenever you create an instance of your item, do you make sure to specify the accountId field? Try giving a default value for this field so it cannot be null. (try some sort of illegal value [eg -1, false, etc] and test for it.
If you would post more implementation details, I (or someone) may be able to directly identify the problem.
Regards.
Edit:4/20@17:11
Here's an example of what you should be doing.
public class Customer {
    private int accountId;

    public Customer() {
        this.accountId = 0;
    }

    public Customer(int account_identification) {
        this.accountId = account_identification);
    }

    //As a side note, general practice implies fields be private
    //Use a method (hence the term 'getter' and the reciprocal, 'setter')
    public int getId() {
        return this.accountId;
    }

    public void setId(int replacement_account_identification) {
        this.accountId = replacement_account_identification;
    }
}

A: It is because the item variable in Customer object is not initialized.

A: Does creating a BTNode automatically allocate its member item ?
You do:
cur3.item.set_account_id(.. )

For this to succeed, both cur3 and cur3.item need to be not null.
Same applies to cur1 and cur2 as well, that you reference later in that line.
And the example of the 3rd case shows that BTNode.item can be null in some scenarios:
cur3.item=null;


text:
Q: How to create custom Artisan commands to generate Bitbucket CI/CD Pipeline I want to create a custom Artisan command to generate the boiler pate for Bitbucket CI/CD Pipeline.

A: To create a new command, you may use the make:command Artisan command. This command will create a new command class in the app/Console/Commands directory. Don't worry if this directory does not exist in your application - it will be created the first time you run the make:command Artisan command:
php artisan make:command SendEmails
https://laravel.com/docs/8.x/artisan#writing-commands

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access/view local web server via public IP? Good day everyone. I'm running an Ubuntu desktop 22.04. I'm new to linux world for about a month or so.
I already configure my router for port forwarding.
When I was developing this web app in windows, I got no problem with accessing it via public IP with just configuring my router. I run the web server using nodejs and it's on port 3000.
I could access the web page in my localhost or any computer in my local network just by typing localhost:3000 or 192.168.1.200:3000 but not 102.154.23.2:3000 - an example public IP.
When I run the server. ready - started server on 0.0.0.0:3000, url: http://localhost:3000
This is my ufw configuration.
I dont know if this would help but I'll post this anyway.
What I would want to achieve is to show the develop web app to my client. Is there any way to do this? Thanks in advance!
UPDATE
Steps I did so far to achieve this and after following @user68186 answer:

*

*start my web server at port 80 with sudo

*forward my external and internal IP port to 80 in my router since setting my external IP to port 80 and running my web server at 3000
and setting internal PORT to 3000 will not do the trick.

Follow up question:
Is there some configuration needed to achieve forwarding external IP routes from port 80 to port 3000 with iptables?
Say 102.154.23.2 external IP forwarded to 192.168.1.200:3000 internal IP. Thanks much!

A: Allow port 3000 in firewall
You are not using the default web server ports 80 or 443. As you put it in the question: "I run the web server using nodejs and it's on port 3000." So, you have to open the port 3000.
Open a terminal by pressing Ctrl+Alt+T and enter:
sudo ufw allow proto tcp from any to any port 3000

Forward port 3000 in the router
Make sure port 3000 is forwarded to the Ubuntu server's internal IP address in the home router. This will allow anyone from outside the home LAN access the web server.
The instructions are router specific and beyond the scope of this answer as it has nothing to do with Ubuntu.

Port 80 is the default port for the http protocol. If you want to make it easier for external users to access the web server, you may want to map the router's port 80 to the internal port 3000. This way, external users won't have to add the port number at the end of the external IP address.

The pictures above is just an example. The settings in your router may look different.
Test
Test whether you can access the web server from outside your home network.
Cleanup
Now you may delete the unwanted ufw rules. Use the command:
sudo ufw status numbered

to find the rule number(s) you want to delete, followed by :
    sudo ufw delete N

where N is the number of the rule you want to delete.
Note, the rule numbers may change once you delete a rule. So use the sudo ufw status numbered command again before you delete another rule.
Finally delete the port forwarding rules from your router you do not need.
Hope this helps

A: Consider ngrok
ngrok http 80 # Expose a local HTTP service on a given port:

Cloudflared
cloudflared tunnel --url http://localhost:3000

Or some of the others?


text:
Q: Optimize Mysql Query (rawdata to processed table) Hi everyone so my question is this, So I have a file that reads in roughly 3000 rows of data by the local infile command. After which there is a trigger on the table that's inserted into that copies three columns from from the updated table and two columns from a table that exist in the database already(if this is unclear to what I mean the structures are coming). From there only combinations that have unique glNumbers will be entered into the processed table. This takes over a minute and half normally. I find this pretty long, I was wondering if this is normal for what I'm doing(can't believe that's true) or is there a way to optimize the queries so it goes faster?
Tables that are inserted to are labeled the first three letters of each month. Here is the default structure.
RawData Structure
| idjan | glNumber  | journel  | invoiceNumber  | date  | JT  | debit  | credit | descriptionDetail  | totalDebit  | totalCredit |

(sorry) for the poor format there isn't a really good way to do this it seems)
After Insert Trigger Query
delete from processedjan;
insert into processedjan(glNumber,debit,credit,bucket1,bucket2)
select  a.glNumber, a.totalDebit, a.totalCredit, b.bucket1, b.bucket2
from jan a inner join bucketinformation b on a.glNumber = b.glNumber
group by glNumber;

Processed Datatable Structure
| glNumber | bucket1| bucket2| credit | debit |
Also I guess it helps to know the bucket 1 and bucket 2 come from another table where its matched against the glNumber. That table is roughly 800 rows with three columns for the glNumber and the two buckets.

A: While postgresql has statement level triggers, mysql only has row level triggers. From the mysql reference:

A trigger is defined to activate when a statement inserts, updates, or
  deletes rows in the associated table. These row operations are trigger
  events. For example, rows can be inserted by INSERT or LOAD DATA
  statements, and an insert trigger activates for each inserted row.

So while you are managing to load 3000 rows in one operation, unfortunately 3000 more queries are executed by the triggers. But the complex nature of your transaction sounds like you might actually be performing 2-3 queries per row. That's the real reason for the slow down.
You can speed things up by disabling the trigger and carrying out a INSERT .. SELECT after the load data in file. You can automate it with a small script.


text:
Q: Populating values in django-admin based on a foreign key selection ... Again I saw the original post Populating values in django-admin based on a foreign key selection but did not understand the template extending example:

    {% extends "admin/change_form.html" %}

    {% block extrahead %}

          $(document).ready(function() {
            $('#id_template').change(function() {
              $.ajax({
                type: 'POST',
                url: "{% url get_template_info %}",
                data: {'template_id': $('#id_template').val()},
                success: function(data, _status) {
                  $('#id_throttle').val(data.throttle);
                  $('#id_rate_limit').val(data.rate_limit);
                  $('#id_product').val(data.product);
                  $('#id_tier_group').val(data.tier_group);
                },
                dataType: "json"
              });
            });
          });

    {% endblock %}

I am trying to do something similar, but do not understand where the url get_template_info comes from.
I am assuming should be a method that belongs to TemplateAdmin(admin.ModelAdmin) but I am not sure about that. the only clue in django documentation was  https://docs.djangoproject.com/en/dev/ref/contrib/admin/ which puts an example

    class MyModelAdmin(admin.ModelAdmin):

    # A template for a very customized change view:
    change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'

    def get_osm_info(self):
        # ...
        pass

    def change_view(self, request, object_id, extra_context=None):
        extra_context = extra_context or {}
        extra_context['osm_data'] = self.get_osm_info()
        return super(MyModelAdmin, self).change_view(request, object_id,
            extra_context=extra_context)

But tend to be more cryptic!, I am new on Django so please give me some guidance on this thing.

A: The author of that answer wasn't very comprehensive, but there's a hint in the last line:

which hits a view that simply takes the id passed in, queries it up
  and returns it to the call. Works like a charm.

get_template_info isn't a built in part of Django. It's the name of the view he created to handle the AJAX request. You'll have to create your own view to return the information you need.


text:
Q: Quick question: SES of refexive sheaves on surface Things are algebraic over $\mathbb{C}$ (or maybe even complex analytic.)
Suppose we have a short exact sequence of torsion free coherent sheaves on a surface $X$ (normal maybe?):
$0\rightarrow A\rightarrow B\rightarrow C\rightarrow 0.$
Does it induce:
$0\rightarrow A^{\vee\vee}\rightarrow B^{\vee\vee}\rightarrow C^{\vee\vee}\rightarrow 0?$


text:
Q: Count number of days in a year with a record I have a SQL Server table named AgentLog in which I store for each agent his daily number of sales.
+-----------+------------+-------------+
| AgentName |    Date    | SalesNumber |
+-----------+------------+-------------+
| John      | 01.01.2014 |          45 |
| Terry     | 01.01.2014 |          30 |
| John      | 02.01.2014 |          20 |
| Terry     | 02.01.2014 |          15 |
| Terry     | 03.01.2014 |          52 |
| Terry     | 04.01.2014 |          24 |
| Terry     | 05.01.2014 |          12 |
| Terry     | 06.01.2014 |          10 |
| Terry     | 07.01.2014 |          23 |
| John      | 08.01.2014 |          48 |
| Terry     | 08.01.2014 |          35 |
| John      | 09.01.2014 |          37 |
| Terry     | 10.01.2014 |          35 |
+-----------+------------+-------------+

If an agent doesn't work on one particular day, there is no record of his sales on that date.
I want to generate a report(query) on a given date interval (ex: 01.01.2014 - 10.01.2014) that counts on how many days an agent wasn't present for work (ex: John - 6 days), was at work (John - 4 days) and also returns the date interval it wasn't present (ex: John 03.01.2014 - 07.01.2014, 10.01.2014) (there can be multiple intervals).

A: You need to create a custom table and populate it with a record for each date you want in your range (Feel free to go as far back in the past and forward into the future as you feel you may need.). You could do this in Excel very easily and import it.
Select *
from Custom.DateListTable dlt
left outer join agentlog ag
on dlt.Date = ag.Date

A: I would approach this by getting the number of dates in the interval, as well as the number of dates the agent was at work, and you then have everything you need.
To get the number of days you can use DATEDIFF:
SELECT DATEDIFF(day, '2014-01-01', '2014-10-01') AS totalDays;

To get the number of days an agent worked, you can use the COUNT(*) aggregate function:
SELECT agentName, COUNT(*) AS daysWorked
FROM myTable
GROUP BY agentName;

Then, you can just add to that query to get the days not worked by subtracting totalDays - daysWorked:
SELECT agentName, COUNT(*) AS daysWorked, (DATEDIFF(day, '2014-01-01', '2014-10-01') - COUNT(*)) AS daysMissed
FROM myTable
GROUP BY agentName;

Here is an SQL Fiddle example.

A: The only way I can think of to resolve this is to creating a temporary table with only one column (datetime) and save there all the dates from the selected range. You can create an stored procedure that fills that temporary table using a cursor with all the dates from the interval. Then do a LEFT join between your table and the temporary table to look for null values in your table (The days where that person didn't come to work)

A: NOTE: The following answer mainly addresses the trickiest part of the question, which is how to obtain "absence from work" intervals.
Given these values as Interval Start - End dates:
DECLARE @IntervalStart DATE = '2013-12-30'
DECLARE @IntervalEnd DATE = '2014-01-10'

the following query gives you the "absence from work" intervals:
SELECT AgentName,
       DATEADD(d, 1, t.[Date]) As OffWorkStart,
       DATEADD(d, -1, t.NextDate) As OffWorkEnd
FROM (
   SELECT AgentName, [Date], LEAD([Date]) OVER (PARTITION BY AgentName ORDER BY [Date] ASC) As NextDate,
          DATEDIFF(DAY, [Date], LEAD([Date]) OVER (PARTITION BY AgentName ORDER BY [Date] ASC)) As NextMinusCurrent
   FROM #AgentLog) t
WHERE t.NextMinusCurrent > 1

-- Get marginal beginning interval (in case such an interval exists)
UNION ALL

SELECT AgentName, @IntervalStart AS OffWorkStart, DATEADD(DAY, -1, MIN([Date])) AS OffWorkEnd
FROM #AgentLog
GROUP BY AgentName
HAVING MIN([Date]) > @IntervalStart

-- Get marginal ending interval (in case such an interval exists)
UNION ALL

SELECT AgentName, DATEADD(DAY, 1, MAX([Date])) AS OffWorkStart, @IntervalEnd
FROM #AgentLog
GROUP BY AgentName
HAVING MAX([Date]) < @IntervalEnd

ORDER By AgentName, OffWorkStart

With the input data you supplied, the above query gives you the following output:
AgentName   OffWorkStart    OffWorkEnd
---------------------------------------
John        2013-12-30      2013-12-31
John        2014-01-03      2014-01-07
John        2014-01-10      2014-01-10
Terry       2013-12-30      2013-12-31
Terry       2014-01-09      2014-01-09

The idea behind the basic part of the query is to employ the following nested query:
SELECT AgentName,
       [Date],
       LEAD([Date]) OVER (PARTITION BY AgentName ORDER BY [Date] ASC) As NextDate,
       DATEDIFF(DAY, [Date], LEAD([Date]) OVER (PARTITION BY AgentName ORDER BY [Date] ASC)) As NextMinusCurrent
FROM #AgentLog

in order to get any existing gaps between the days a certain agent is present for work. A value of NextMinusCurrent > 1 indicates such a gap.
Counting days is trivial once you have the above query in place. E.g. placing the above query in a CTE you can count total number of absence days with sth like:
;WITH cte (

... query goes here

)
SELECT AgentName, SUM(DATEDIFF(DAY, OffWorkStart, OffWorkEnd) + 1) AS AbsenceDays
FROM cte
GROUP By AgentName

P.S. The above query makes use of SQL Server LEAD function, which is available from SQL SERVER 2012 onwards.
SQL Fiddle here
EDIT:
CTEs together with ROW_NUMBER() can be used to simulate LEAD function. The first part of the query becomes:
;WITH cte1 AS (
   SELECT AgentName,
          [Date],
          ROW_NUMBER() OVER (PARTITION BY AgentName ORDER BY [Date] ASC) As rn
   FROM #AgentLog
),
cte2 AS (
   SELECT cte1.AgentName, cte1.[Date],
          cteLead.[Date] AS NextDate,
          DATEDIFF(DAY, cte1.[Date], cteLead.[Date])  As NextMinusCurrent
   FROM cte1
   LEFT OUTER JOIN cte1 AS cteLead
      ON (cte1.rn = cteLead.rn - 1) AND (cte1.AgentName = cteLead.AgentName)
)
SELECT AgentName,
       DATEADD(d, 1, cte2.[Date]) As OffWorkStart,
       DATEADD(d, -1, cte2.NextDate) As OffWorkEnd
FROM cte2
WHERE NextMinusCurrent > 1

SQL Fiddle for SQL Server 2008 here. I hope it executes in SQL Server 2005 also!

A: Try this...
SET DATEFIRST 1; --Monday

DECLARE @StartDate  DATETIME = '2014-01.01',
        @EndDate    DATETIME = '2014-01.10';

WITH data as (
    select 0 as i, DATEADD(DAY, 0, @StartDate) as TheDate
    union all
    select i + 1, DATEADD(DAY, i + 1, @StartDate) as TheDate
    from data
    where i < (@EndDate - @StartDate)
)

SELECT a.AgentName,
SUM(CASE WHEN c.Date IS NULL THEN 1 ELSE 0 END) AS  Missing,
SUM(CASE WHEN c.Date IS NOT NULL THEN 1 ELSE 0 END) AS  Working
FROM Agent a
JOIN data b ON NOT EXISTS(SELECT NULL FROM SpecialDate s WHERE s.date = b.TheDate)
LEFT JOIN AgentLog c ON
    c.AgentName = a.AgentName
AND c.Date = b.TheDate
WHERE DATEPART(weekday, b.TheDate) <= 5
GROUP BY a.AgentName
OPTION (MAXRECURSION 10000);

It includes a check for weekends, as well as a reference to "SpecialDate" where a list of non working days can be maintained, and excluded from the check.
Reading your question again, I realise that this will only solve half your problem.


text:
Q: select only if all sub-objects match a condition There is an Orders table and a Content table.
Each order contains multiple items stored in content table with join of order number.
Order table contains order number.
Content table contains multiple items with each record having order number and item status columns.
I need to a query that would output distinct order numbers where all of the items should have status done.
I tried this
SELECT O.O_NUM FROM ORDER O, CONTENT C WHERE C.STATUS=DONE

but this will return order number even if any one content item status is done.

A: SELECT Orders.OrderNumber
FROM Orders
WHERE NOT EXISTS ( SELECT NULL
                   FROM Content
                   WHERE Orders.OrderNumber = Content.OrderNumber
                     AND Content.Status != 'Done' )

A: You can do aggregation :
select o.orderno
from orders o inner join
     content c
     on c.orderno = o.orderno
group by o.orderno
having sum(case when c.status <> 'done' then 1 else 0 end) = 0;


text:
Q: Django Writtable Nested Serializers - Error NOT NULL Constraints I am trying to create a "Prospect" object, which is nested under my "Appointment" serializer. But when posting, I keep getting the error "NOT NULL constraint failed: schedule_appointment.prospect_id".
I suppose Django is expecting me to pass a prospect_id when posting, but how do I go about doing this? I've read elsewhere that an alternative is to set the foreign key to null=True, but in my case, an Appointment MUST have a Prospect.
Any suggestions?
Serializers
class ProspectSerializer(serializers.ModelSerializer):

    class Meta:
        model = Prospect
        fields = [  'id','first_name', 'last_name', 'email']

class AppointmentSerializer(serializers.ModelSerializer):
    prospect = ProspectSerializer()

    class Meta:
        model = Appointment
        fields = ['appointment_time', 'unit', 'staff', 'prospect']

    def create(self, validated_data):
        prospect_data = validated_data.pop('prospect')
        appointment = Appointment.objects.create(**validated_data)
        Prospect.objects.create(appointment=appointment, **prospect_data)
        return appointment

Models
class Appointment(models.Model):
    appointment_time = models.DateTimeField()
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
    staff = models.ForeignKey(Staff, on_delete=models.CASCADE)
    prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE)

class Prospect(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=30)

A: First you need create Prospect model and then Appointment
def create(self, validated_data):
        prospect_data = validated_data.pop('prospect')
        prospect = Prospect.objects.create(**prospect_data)
        appointment = Appointment.objects.create(prospect=prospect, **validated_data)

        return appointment


text:
Q: Reuse component in projection (NHibernate) Is it possible to reuse a component mapping in a projection?
Here is the mapping for the Vendor entity:
   <class name="Vendor" table="vendor">
     ...
     <property name="Name" column="Name" />
     <component name="Address" class="MyProject.Address, MyAssembly" >
       <property name="Street" column="street" />
       <property name="City" column="City" />
     </component>
   </class>

For a report I'd like to retrieve these vendors in a data transfer object but reuse the Address component (because there are many fields and some useful formatting behavour).
public class VendorDTO
{
    public string Name;
    public Address Address;

}

public class Address
{
    public string Street;
    public string City;
    public string SomeUsefulBehavour();
}

Is this possible without splitting Address out into it's own table?
Thanks!

A: I believe this should 'just work':
Session.QueryOver<Vendor>()
    .SelectList(builder =>
        builder.Select(x => x.Name)
            .Select(x => x.Address))
    .TransformUsing(Transformers.AliasToBean<VendorDTO>())
    .List<VendorDTO>();


text:
Q: Пересечение треугольника и окружности Задал окружность и треугольник:
void enter_coordinate_circle(circle* c)
{
    printf("Введите координаты окружности: ");
    scanf("%d %d", &c->C.x, &c->C.y);
    printf("Введите радиус окружности: ");
    scanf("%d", &c->r);
}

void enter_triangle_coordinate(triangle* t)
{
    printf("Введите координаты треугольника\n");
    for (int i = 1; i <= 3; i++) {
        printf("Введите координаты вершины: %d\n", i);
        scanf("%d %d", &t->T[i].x, &t->T[i].y);
    }
    t->T[4].x = t->T[1].x;
    t->T[4].y = t->T[1].y;

Как найти пересечение этих фигур(если оно есть при заданных координатах)

A: Представьте каждую сторону треугольника в параметрическом виде
X = X1 + t * (X2 - X1)
Y = Y1 + t * (Y2 - Y1)

И подставьте в уравнение окружности
(X - CX)^2 + (Y - CY)^2 = R^2

и решите полученное квадратное уравнение для неизвестного t. Если корни существуют и находятся в интервале 0..1 - пересечение со стороной есть.
Уравнения будут несколько проще, если от всех координат отнять координаты центра окружности
 X1' = X1-C.x
 Y1' = Y1-C.y
 X' = X1' + t * (X2-X1)
 Y' = Y1' + t * (Y2-Y1)

 X'^2 + Y'^2 = R^2


text:
Q: How do you tell if the span of a set of vectors enters the most positive sector of a graph? I have $k$ linearly independent vectors in $\mathbb{R}^n$.  I want to know if the span of these vectors (i.e. the set of points in $\mathbb{R}^n$ that can be described by linear combinations of these vectors) intersects the portion of $\mathbb{R}^n$ where all the axes are positive (e.g. the first quadrant in $\mathbb{R}^2$, the first octant in $\mathbb{R}^3$, etc.).
Is there a test I can run on my vectors that will answer this question?

A: In practice, the way to do this (where $n$ and $k$ may be large) is with linear programming software, since this is basically a linear programming feasibility problem: $A x \ge (1,\ldots, 1)^T$ where $A$ is the $n \times k$ matrix whose columns are your vectors.

A: The magic words are "Farkas' Lemma".


text:
Q: Flash looping causing variable value issues Flash keeps looping which is causing certain variables to add values constantly. E.g.
if (userWord.text == word){
 score = score + 1;
 trace(score);
}

That will constantly add one to "score" when a certain word is typed into a text box.
How do I add one to "score" without stopping the application or playing it once?

A: Add an eventListener to your text field and have it react to Event.CHANGE:
userWord.addEventListener (Event.CHANGE, onWordChange);

function onWordChange (ev:Event) : void {
    if (userWord.text == word) {
        score = score + 1;
        trace (score);
    }
}


text:
Q: RemoteViews setOnClickPendingIntent not firing for Widget ListView I have a ListView Widget for Honeycomb and above.
I have a bar across the top with setOnClickPendingIntents in the onUpdate and they all work fine.
However in my ListViewAdapter in the RemoteViews getViewAt() function setOnClickPendingIntents never fires.
The strange thing is it was working fine in ICS, but stopped on my JellyBean devices.
My Code is as follows
@Override
public RemoteViews getViewAt(final int position) {
    final RemoteViews views = new RemoteViews(context.getPackageName(), layout);
            final PendingIntent home_intent = PendingIntent.getActivity(context, 0, new Intent(
            INTENT_ACTION_HOME), Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    views.setOnClickPendingIntent(R.id.row_item, home_intent);
}

This exact same intent fired in the onUpdate function of the widget works fine, just not when in the ListView Adapter.

A: From the docs
public void setOnClickPendingIntent (int viewId, PendingIntent pendingIntent)
Equivalent to calling setOnClickListener(android.view.View.OnClickListener) to launch the provided PendingIntent. When setting the on-click action of items within collections (eg. ListView, StackView etc.), this method will not work. Instead, use {@link RemoteViews#setPendingIntentTemplate(int, PendingIntent) in conjunction with RemoteViews#setOnClickFillInIntent(int, Intent).
http://developer.android.com/reference/android/widget/RemoteViews.html


text:
Q: I'm using shared prefrences to store a Location value received from gps, How can i retrive the same from the getAppData()? public class StorageHelper {

public static final String PREFS_NAME = "LOCATION_DATA";

public static void saveAppData(Context ctx, String key, Location value){
    SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    String lat =Double.toString(value.getLatitude());
    String lon=Double.toString(value.getLongitude());
    Set location = new HashSet();
    location.add(lat);
    location.add(lon);
    editor.putStringSet(key,location);
    editor.apply();
}

public static String getAppData(Context ctx, String key){
    SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);

    return settings.getStringSet(key,);
}

}

what is the second argument to pass in the return settings.getStringSet()?
I am expected to send a java.lang parameter , but a Set is of java.utiity type.

A: As said in documentation, second parameter is value that returns if there is no object associated with used key value. You can use empty set or null, but after call this method you should check for not null value.


text:
Q: Android up button doesn't open parent activity I'm developing an app using the Android Support Library to implement ActionBar on old devices, but I'm  encountering a problem.
The problem is that when I press the Up button the activity doesn't start the parent activity, but the activity that started the current one.
The problem occurs on Android 4.2.2 KitKat but not on Android 2.3.6 Gingerbread.
<activity android:name=".innerPackage.SecondaryActivity"
          android:screenOrientation="portrait"
          android:parentActivityName="com.dev.myapp.OtherActivity">
    <meta-data android:name="android.support.PARENT_ACTIVITY"
               android:value="com.dev.myapp.OtherActivity"/>
</activity>

The activities are:

*

*com.dev.myapp.MainActivity.java;

*com.dev.myapp.innerpackage.SecondaryActivity.java;

*com.dev.myapp.OtherActivity.java.

The sequence is: MainActivity -> open SecondaryActivity -> press Up button -> MainActivity (but it should start OtherActivity).


text:
Q: Perl getting "can't locate error" trying to use IO::prompt C:\sample\ss>perl dd_tsys.pl
Can't locate IO/prompt.pm in @INC (@INC contains: C:/strawberry/perl/lib C:/stra
wberry/perl/site/lib C:\strawberry\perl\vendor\lib .) at dd_tsys.pl line 8.
BEGIN failed--compilation aborted at dd_tsys.pl line 8.

I installed the io::pack, but when I try to use the IO::prompt, it saying the above error,
Here are my installation steps I followed, check it out.

A: Perl is case-sensitive; the module is IO::Prompt.
Additionally, your build log shows:
Test Summary Report
-------------------
t\01.dependencies.t (Wstat: 512 Tests: 2 Failed: 2)
Failed tests: 1-2
Non-zero exit status: 2
Files=4, Tests=3, 1 wallclock secs ( 0.06 usr + 0.03 sys = 0.09 CPU)
Result: FAIL
Failed 1/4 test programs. 2/3 subtests failed.
DCONWAY/IO-Prompt-0.997001.tar.gz
C:\strawberry\perl\bin\perl.exe ./Build test -- NOT OK
//hint// to see the cpan-testers results for installing this module, try:
reports DCONWAY/IO-Prompt-0.997001.tar.gz
Running Build install
make test had returned bad status, won't install without force
Failed during this command:
DCONWAY/IO-Prompt-0.997001.tar.gz : make_test NO

So, the module was not installed, which is the rest of the reason it is not found.


text:
Q: Clone record with its related list by clicking on custom button on that record ? i have created one button on record top beside the clone button,
when clicked, execute code that would make a new version record with the same name and append today's date on the end of the name to distinguish it from the original.i created apex class and custom list button but the i clicked on button so java script does'not working on this.so below error occour during click on the button.
How should i do this ?

Apex class:-
global class CloneVersionwithText
{
webservice static void cloneMSAVersion(Id msaId) // you can pass parameters
{
   List<MSA_Text_Block__c> MText = new List<MSA_Text_Block__c>();
   Master_Service_Agreement_Version__c msa = [SELECT ID, Name FROM Master_Service_Agreement_Version__c WHERE Id = : msaId];
   Master_Service_Agreement_Version__c msaCopy = msa.clone(false,true);
   msaCopy.Name = msa.Name +'-'+system.today();
   insert msaCopy;
   //cloning Related MSA Text Records
   for(MSA_Text_Block__c c : [SELECT Id, Name, Service__c,         Order_within_Service__c,Master_Service_Agreement_Version__r.ID FROM      MSA_Text_Block__c WHERE Master_Service_Agreement_Version__r.ID = : msa.Id]){
     MSA_Text_Block__c textCopy = c.clone(false,true);
     textCopy.Master_Service_Agreement_Version__r.ID = msaCopy.Id;
     MText.add(textCopy);
    }
   insert MText;
}
}

create a java script button to call the apex class
 {!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
 {!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}
 sforce.apex.execute("CloneVersionwithText","cloneMSAVersion",{msaId{!Master_Service_Agreement_Version__c.Id}}"});

A: believe its a syntax issue in passing the parameter to the apex method
you need a semicolon between the parameter name and value.
its always better to declare and initialize your param value and use it wherever you need it.
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

var myParam = "{!Master_Service_Agreement_Version__c.Id}";
sforce.apex.execute("CloneVersionwithText","cloneMSAVersion", {msaId : myParam});


text:
Q: Not able to decrypt the encryptedValue using crypto I am trying to decrypt a value (encrypted in des) coming from VB.
When I try to decrypt the encryptedValue using crypto in Javascript the output gives me an empty value.
I have attached how the encryption was done in VB.
HOW I AM TRYING TO DECRYPT IN JAVASCRIPT
var CryptoJS       = require("crypto-js");
var key            = "peekaboo";
var encryptedValue = "50AznWWn4fJI19T392wIv/ZysP/Ke3mB";
encryptedValue     = CryptoJS.enc.Base64.parse(encryptedValue);

var data           = CryptoJS.DES.decrypt(encryptedValue, key, { iv: "cbauthiv" });

const email  = data.toString(CryptoJS.enc.Utf8);

console.log(email, "ORIGINAL TEXT");

THE WAY IT IS ENCRYPTED IN VB
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module Module1

    Private Const ENCRYPTIONKEY As String = "peekaboo"

    Sub Main()

        Dim s As String = Encrypt("ditzymoose@outlook.com")

        Dim r As String = Decrypt(s)
        Console.ReadLine()

    End Sub

    Private Function Encrypt(stringToEncrypt As String) As String
        Dim rng As New RNGCryptoServiceProvider
        Dim byteArray() As Byte = New Byte(8) {}
        Dim iv_value As String = "cbauthiv"
        Dim key() As Byte = {}
        Dim IV() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(iv_value, 8))

        key = System.Text.Encoding.UTF8.GetBytes(Left(ENCRYPTIONKEY, 8))
        Dim des As New DESCryptoServiceProvider
        rng.GetBytes(byteArray)
        Dim Salt As String = BitConverter.ToString(byteArray)
        Dim SaltedInput As String = Salt & "~" & stringToEncrypt
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())

    End Function
End Module

A: The key and IV must be passed as WordArray. For the conversion the Utf8-Encoder has to be used, here.
Also, the ciphertext must be passed as a CipherParams object or alternatively Base64 encoded (which is then implicitly converted to a CipherParams object), here.
With these changes the ciphertext of the VB code can be successfully decrypted using the CryptoJS code:

var key            = CryptoJS.enc.Utf8.parse("peekaboo");
var iv             = CryptoJS.enc.Utf8.parse("cbauthiv");
var encryptedValue = "50AznWWn4fJI19T392wIv/ZysP/Ke3mB";

var data           = CryptoJS.DES.decrypt(encryptedValue, key, {iv: iv});
var email          = data.toString(CryptoJS.enc.Utf8);

console.log(email, "ORIGINAL TEXT");
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

Please note that DES is insecure (here) and was replaced by AES almost 20 years ago. Also insecure is a static IV. Instead, a random IV should be generated for each encryption.
Furthermore a password should not be used as key. If a password is to be used, the key should be derived from the password using a reliable key derivation function such as PBKDF2.


text:
Q: Can I change the contents of a description meta tag generated by Yoast in a WordPress site? I am quite new to WordPress so I am not sure how this would work.
Essentially I have the Yoast plugin handling my SEO related things. The main one giving problems is the description meta tag.
The site is bilingual and I would like the description meta tag to be translated as well. Yoast currently does not provide that option, unless I get another plugin which I do not want to get into.
As it stands, I am told that I can insert the description meta tag through the functions.php using add_action. This unfortunately does not work as it only adds another description meta tag.
Currently my code looks like this:
function insert_meta_tag_in_head () {
    echo '<meta name="description" content="My New content" />';
}

add_action('wp_head', 'insert_meta_tag_in_head', 1);

So basically this just gives me a second description meta tag. I have also seen in other threads, that if I want to replace a tag, I should use the do_action function. Which I call as follows:
do_action('wp_head', 'insert_meta_tag_in_head');

This however does nothing.
What am I doing wrong? How can I change the contents of the description tag given to me through Yoast?

A: We've previously changed a Yoast title before, however, a description is something we have been working on too.
To sum-up the link above:

You need to filter the wpseo_metadesc action in order to display your
  new description.

add_filter('wpseo_metadesc', 'new_desc_function');


text:
Q: How do I create a centred 3-column layout similar to Quora using Tailwind CSS I am attempting to re-create the layout of the home page of Quora.com using Tailwind CSS. The goal is to have a 3-column layout after the header section. I am having  trouble centring the columns so that it matches the centring of the header. This is what I have so far:
The markup is:

              <button>

              </button>

              <button>

              </button>

              <button>

              </button>

              <button>

              </button>

              <button>

              </button>

            <button type="submit" class="mr-1 outline-none focus:outline-none active:outline-none">
              <svg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                   viewBox="0 0 24 24" class="w-4 h-4">
                <path d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </button>
            <input type="search" name="search" id="search" placeholder="Search Quora"
                   class="text-sm appearance-none w-full outline-none focus:outline-none active:outline-none"/>

            <button>

            </button>

          Add Questions

I am trying to achieve this:

A: You can leverage grid layout + max-w-7xl with mx-auto. Checkout this grid layout for working modal.

      Quora

1

2

3


text:
Q: How to setup .htaccess redirect for particular category blogs (wordpress) I have URL scheme for my blog like this:
http://www.example.com/%YEAR%/%MONTH%/%CATEGORY%/%POST_TITLE%/
Now i want to redirect a particular category blogs to a different domain. The URL Scheme on that other domain is similar.
Please suggest me how can i do it using .htaccess

A: Assuming you're using Apache the solution is to use mod_rewrite. The following in your .htaccess should achieve what you're after. I'm assuming that %YEAR% is four numerals and %MONTH% is two numerals, adjust accordingly if this is not the case.
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(/\d{4}/\d{2}/)([^/]+)(/.*)$
RewriteCond %2 ^category1|category2|category3|category5$
RewriteRule ^(.*)$ http://other.example.com$1 [redirect=permanent,last]

Explanation of each line:

*

*Enable mod_rewrite

*Check if the url is /four numerals/two numerals/anything/anything else

*If the above pattern matched then check if the text captured by the second set of brackets matches any of the word separated by pipes

*If the above condition matched then redirect to the same path at the server other.example.com


text:
Q: How to export User Rights Assignments and import them on another machine How would one export all of the user rights assignments from one Windows Server 2008 box and import them on another. Neither would be on a domain so this would just be local security policy.

A: Just had to right click on enough stuff :-)
You can export by right-clicking on Security Settings in secpol.msc and selecting export. This creates an INF of the User Rights Assignments which can be imported using the same method on another computer only selecting Import instead.


text:
Q: contenteditable loose focus but writes anyway I am using Foundation alert-box and joyride. I am experiencing a strange issue;
when I write in contenteditable and open an alert-box, when I close the alert-box (with the x) and then I type again (random char) even if the contenteditable has loose its focus ( I checked with document.activeElement ) the typed letter is inserted in the contenteditable, the keypress not fired on the contenteditable and a keydown event is fired on the body.
This happens in Chrome, in Firefox works as well.
Fiddle
To get the problem: while you have focus on contenteditable, then click on the alert-box "x" (contenteditable will loose focus), it will type anyway in the contenteditable.

A: Solved the issue with:
$("#mycontenteditable").on("blur", function(){
   var sel = document.getSelection();
   sel.removeAllRanges();
})


text:
Q: Mac Yosemite Python I am usually an R user for all my statistical analysis work, but I wanted to learn Python. At the time I did not know that Python comes native to the Mac OS, so I went to python.org and installed Python 3.4.2 on my Mac. This created a Python folder in my Applications from where I can access IDLE. For my purposes specifically, I also needed a few libraries, namely Pandas and Numpy. After some research I learnt that the best way to do this was to get Anaconda.
Hence, I went ahead and installed Anaconda for Python 3.4 from their website. Now, the issue is, the Anaconda launcher came with its own IDE called Spyder and I found that this was much easier to use than IDLE, since it contained all the libraries I needed already. So this raised a couple of questions for me:

*

*Do I still need the Python 3.4 I installed from python.org? If not, how can I remove this? I should mention that I'm not very familiar with how the Mac command line works, so if I could get instructions that have more detail, it would be easier for me

*Do I have 2 installs of Python 3.4 on my Mac now or did the Anacondas one replace the one from python.org? If this is the case, can I just go ahead and delete the Python 3.4 folder in my Applications folder (which contains IDLE, etc.)?

A: You now have three versions of Python on your Mac -- Anaconda will have installed itself into the directory anaconda in your home directory. You can remove the python.org install by following the instructions at: https://docs.python.org/3/using/mac.html?highlight=uninstall -- you may need to use the command line and rm command to remove files (for example, the symlink in /usr/local/bin/). Don't do this unless you're sure of what you're doing because they don't go to the Trash.
Important note: do not delete or modify the system-provided Python in /System/Library/Frameworks/Python.framework and /usr/bin/python or you will hose your operating system and need to reinstall Yosemite.
If this all seems too scary, I would live with the bloat as long as anaconda is your default Python and you're happy with it.


text:
Q: Механизм Attention для RNN Модель Encoder-Decoder для реализации задачи Seq2Seq:
class Encoder(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.embed = tf.keras.layers.Embedding(INPUT_VOCAB_SIZE, EMB_SIZE)
        self.lstm = tf.keras.layers.LSTM(H_SIZE,
                                         return_sequences=False,
                                         return_state=True)

    def call(self, x):
        out = self.embed(x)
        _, h, c = self.lstm(out)
        state = (h, c)
        return state

class Decoder(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.embed = tf.keras.layers.Embedding(TARGET_VOCAB_SIZE, EMB_SIZE)
        self.lstm = tf.keras.layers.LSTM(H_SIZE,
                                         return_sequences=True,
                                         return_state=True)
        self.fc = tf.keras.layers.Dense(TARGET_VOCAB_SIZE, activation='softmax')

    def call(self, x, init_state):
        out = self.embed(x)
        out, h, c = self.lstm(out, initial_state=init_state)
        out = self.fc(out)
        state = (h, c)
        return out, state

Далее объединяем в единую систему:
encoder_model = Encoder()
decoder_model = Decoder()

encoder_inputs = tf.keras.layers.Input(shape=(None,))
decoder_inputs = tf.keras.layers.Input(shape=(None,))

enc_state = encoder_model(encoder_inputs)
decoder_outputs, _ = decoder_model(decoder_inputs, enc_state)

seq2seq = tf.keras.Model([encoder_inputs, decoder_inputs], decoder_outputs)

Имеется реализация механизма Attention от TensorFlow:
tf.keras.layers.Attention()

Вопрос: Как данную реализацию можно внедрить в имеющуюся систему, чтобы Attention отрабатывал?
Сломано множество копий, вариантов реализации и попыток.
Ни это - https://github.com/thushv89/attention_keras
Ни это - https://stackoverflow.com/questions/56946995/how-to-build-a-attention-model-with-keras
Ни это - https://www.tensorflow.org/tutorials/text/nmt_with_attention?hl=ru  не работает.


text:
Q: How to have scrolling in Java GUI JTextArea with Eclipse? I am trying to put an muti lines text in the JtextArea, but there isn't a scrolling so I cannot move to see any data below the default JtextArea area, here is the code and textArea_1 is the JtextArea:
String abc="";
for(int i=0; i<=100; i++){
abc = abc + data[i][0]+"\n";
}
textArea_1.setText(abc);

A: You need to look into adding a JScrollPane.
Link: http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html
import javax.swing.JScrollPane;
JScrollPane scrollPane = new JScrollPane(TEXTAREAHERE);

A: Scrolling is handled by JScrollPane.
Check out How to use scroll panes and for your own reference, JScrollPane and which is also demonstrated in How to use Text Areas
Updated with example

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestScrollPane04 {

    public static void main(String[] args) {
        new TestScrollPane04();
    }

    public TestScrollPane04() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JTextArea textArea = new JTextArea(10, 20);
                String abc = "";
                for (int i = 0; i <= 100; i++) {
                    abc = abc + "This is some additional text " + i + "\n";
                }
                textArea.setText(abc);

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(textArea));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

A: You should add a JScrollPane. as
JscrollPane myScroll=new JScrollPane(textArea_1);

If your text is more than that can see other text by scrolling. By default when you set or append text to JTextArea it scrolls to end (you can see that if text is large so that scroll bar appeard). So to scroll back to first line try
textArea_1.setCaretPosition(0);

see Java doc


text:
Q: Manually stop jquery-ui sliding event for element I need to manually stop an element from being slided (i used .slider() to create the slider). How can i achieve this?
I need to do this because the jquery-ui slider has issues when inside an iframe. So far i have managed to create a function that change the value of the slider however i had no luck trying to active the stop, or mouseup event of the slider.

A: I havent found how to solve this, so what i did was prevent the sliding event from doing anything at start with this:
 $('.slider',$document).slider({start:function(event,ui){return false;}});

That i way i can have a total manual control over the slider.
If you are curios about why i needed to do this you can check out this question


text:
Q: NATIVESCRIPT + JS add marker to map with button how can i select mymap by id and then add the marker ?
function addMarker(args){
        var MyMapById; // i dont know how to bind mymaps to this variable
        MyMapById.clear();
        var marker = new mapsModule.Marker();
        marker.position = mapsModule.Position.positionFromLatLng(latitude, longitude);
        MyMapById.addMarker(marker);
    }

here is my xml page:
<Page
    xmlns="http://www.nativescript.org/tns.xsd"
    xmlns:maps="nativescript-google-maps-sdk"
    navigatedTo="onNavigatedTo">
    <GridLayout rows="auto, *">
        <Button text="Add Marker" tap="addMarker" />

        <maps:mapView latitude="{{ latitude }}" longitude="{{ longitude }}" row="1" id="mymap"
         mapAnimations="false" cameraChanged="onCameraChanged" zoom="12" mapReady="onMapReady" />
    </GridLayout>
</Page>

thanks.

A: You must be able to get reference to any component on the page with getViewById method, for instance page.getViewById("mymap")


text:
Q: Pick subtitle file from storage and load in ExoPlayer I have an app that plays videos using ExoPlayer but I wanted to add an option to pick and load any subtitle file into the player.
This is my code for subtitle:
    public void setSubSelectedSubtitle(MediaSource mediaSource, String subtitle, Context context) {
        MergingMediaSource mergedSource;
        if (subtitle != null) {
            Uri subtitleUri = Uri.parse(subtitle);

            Format subtitleFormat = Format.createTextSampleFormat(
                    null, // An identifier for the track. May be null.
                    MimeTypes.TEXT_VTT, // The mime type. Must be set correctly.
                    Format.NO_VALUE, // Selection flags for the track.
                    "en"); // The subtitle language. May be null.

            DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(context,
                    Util.getUserAgent(context, getResources().getString(R.string.app_name)), new DefaultBandwidthMeter());

            MediaSource subtitleSource = new SingleSampleMediaSource
                    .Factory(dataSourceFactory)
                    .createMediaSource(subtitleUri, subtitleFormat, C.TIME_UNSET);

            mergedSource = new MergingMediaSource(mediaSource, subtitleSource);
            player.prepare(mergedSource, false, false);
            //resumePlayer();

        } else {
            Toast.makeText(context, "there is no subtitle", Toast.LENGTH_SHORT).show();
        }
    }

What I'm trying is, when the user clicks on subtitle button, it should open their storage from which they could choose the file which should get loaded and play in ExoPlayer.
Any help is appreciated, thanks!


text:
Q: How to run blastp in rblast? I'm trying to use rBlast for protein sequences but somehow it doesn't work. It works fine for nucleotide sequences but for proteins it just doesn't return any match (I used a sequence from the searched dataset, so there can't be no match). In the description it stands "This includes interfaces to blastn, blastp, blastx..." but in the help file in R studio it says "Description Execute blastn from blast+". Did anybody run rBlast for proteins?
Here's what I ran:
listF<-list.files("Trich_prot_fasta/")

fa<-paste0("Trich_prot_fasta/",listF[i])

makeblastdb(fa, dbtype = "prot", args="")

bl <- blast("Trich_prot_fasta/Tri5640_1_GeneModels_FilteredModels1_aa.fasta", type="blastp")

seq <- readAAStringSet("NDRkinase/testSeq.txt")

cl <- predict(bl, seq)

Result:

> cl <- predict(bl, seq)

Warning message: In predict.BLAST(bl, seq) : BLAST did not return a
match!

A: Tried to reproduce the error but everything worked as expected on my system (macOS BigSur 11.6 / R v4.1.1 / Rstudio v1.4.1717).
Given your blastn was successful, perhaps you are combining multiple fasta files for your protein fasta reference database? If that's the case, try concatenating them together and use the path to the file instead of an R object ("fa") when making your blastdb. Or perhaps:
makeblastdb(file = "Trich_prot_fasta/Tri5640_1_GeneModels_FilteredModels1_aa.fasta", type = "prot)

Instead of:
makeblastdb(fa, dbtype = "prot", args="")

Also, please edit your question to include the output from sessionInfo() (might help narrow things down).
library(tidyverse)
#BiocManager::install("Biostrings")
#devtools::install_github("mhahsler/rBLAST")
library(rBLAST)

# Download an example fasta file:
# https://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000001542/UP000001542_5722.fasta.gz
# Grab the first fasta sequence as "example_sequence.fasta"

listF <- list.files("~/Downloads/Trich_example", full.names = TRUE)
listF
#> [1] "~/Downloads/Trich_example/UP000001542_5722.fasta"
#> [2] "~/Downloads/Trich_example/example_sequence.fasta"

makeblastdb(file = "~/Downloads/Trich_example/UP000001542_5722.fasta", dbtype = "prot")

bl <- blast("~/Downloads/Trich_example/UP000001542_5722.fasta", type = "blastp")
seq <- readAAStringSet("~/Downloads/Trich_example/example_sequence.fasta")
cl <- predict(bl, seq)

cl
#>                 QueryID              SubjectID Perc.Ident Alignment.Length
#> 1    Example_sequence_1 tr|A2D8A1|A2D8A1_TRIVA    100.000              694
#> 2    Example_sequence_1 tr|A2E4L0|A2E4L0_TRIVA     64.553              694
#> 3    Example_sequence_1 tr|A2E4L0|A2E4L0_TRIVA     32.436              669
#> 4    Example_sequence_1 tr|A2D899|A2D899_TRIVA     64.344              488
#> 5    Example_sequence_1 tr|A2D899|A2D899_TRIVA     31.004              458
#> 6    Example_sequence_1 tr|A2D899|A2D899_TRIVA     27.070              314
#> 7    Example_sequence_1 tr|A2D898|A2D898_TRIVA     54.915              468
#> 8    Example_sequence_1 tr|A2D898|A2D898_TRIVA     33.691              653
#> 9    Example_sequence_1 tr|A2D898|A2D898_TRIVA     32.936              671
#> 10   Example_sequence_1 tr|A2D898|A2D898_TRIVA     29.969              654
#> 11   Example_sequence_1 tr|A2D898|A2D898_TRIVA     26.694              487
#> 12   Example_sequence_1 tr|A2D898|A2D898_TRIVA     25.000              464
#> 13   Example_sequence_1 tr|A2F4I3|A2F4I3_TRIVA     39.106              716
#> 14   Example_sequence_1 tr|A2F4I3|A2F4I3_TRIVA     30.724              677
#> 15   Example_sequence_1 tr|A2F4I3|A2F4I3_TRIVA     29.257              417
#> 16   Example_sequence_1 tr|A2F4I3|A2F4I3_TRIVA     23.438              640
#> 17   Example_sequence_1 tr|A2F4I3|A2F4I3_TRIVA     22.981              718
#> 18   Example_sequence_1 tr|A2F4I3|A2F4I3_TRIVA     24.107              112
#> 19   Example_sequence_1 tr|A2FI39|A2FI39_TRIVA     33.378              740
#> 20   Example_sequence_1 tr|A2FI39|A2FI39_TRIVA     31.440              722
#>      Mismatches Gap.Openings Q.start Q.end S.start S.end         E   Bits
#> 1             0            0       1   694       1   694  0.00e+00 1402.0
#> 2           243            2       1   692     163   855  0.00e+00  920.0
#> 3           410           15      22   671       1   646  3.02e-94  312.0
#> 4           173            1     205   692       1   487  0.00e+00  644.0
#> 5           308            7      22   476       1   453  3.55e-55  198.0
#> 6           196            5      13   294     173   485  4.12e-25  110.0
#> 7           211            0       1   468     683  1150 8.48e-169  514.0
#> 8           420           11       2   647     501  1147  1.61e-91  309.0
#> 9           396           10       2   666     363   985  5.78e-89  301.0
#> 10          406           11      16   664     195   801  1.01e-66  238.0
#> 11          297           10     208   662      21   479  1.60e-36  147.0
#> 12          316            7      11   469      29   465  3.04e-36  147.0
#> 13          386            4       2   667     248   963 1.72e-149  461.0
#> 14          411           10       2   625      66   737  8.34e-83  283.0
#> 15          286            5     129   542      14   424  2.66e-52  196.0
#> 16          421           15       5   607     365   972  3.07e-38  152.0
#> 17          407           21      77   662      27   730  1.25e-33  138.0
#> 18           81            3     552   661       3   112  2.10e-01   35.4
#> 19          421            9       3   675     394  1128 1.12e-115  375.0
#> 20          409           15       2   647     163   874  1.21e-82  285.0
...

Created on 2021-09-30 by the reprex package (v2.0.1)


text:
Q: How to trigger a function from one component to another component in React.js? I'am creating React.js Weather project. Currently working on toggle switch which converts celcius to fahrenheit. The celcius count is created in one component whereas toggle button is created in another component. When the toggle button is clicked it must trigger the count and display it. It works fine when both are created in one component, but, I want to trigger the function from another component. How could I do it? Below is the code for reference

*

*CelToFahr.js (Here the count is displayed)

import React, { Component } from 'react'
import CountUp from 'react-countup';

class CeltoFahr extends Component {
    state = {
        celOn: true
    }

    render() {
        return (
            <React.Fragment>
                {/* Code for celcius to farenheit */}

                    <CountUp
                        start={!this.state.celOn ? this.props.temp.cel : this.props.temp.fahr}
                        end={this.state.celOn ? this.props.temp.cel : this.props.temp.fahr}
                        duration={2}
                        >
                        {({ countUpRef, start}) => (

                        )}
                    </CountUp>

                {/*End of Code for celcius to farenheit */}
            </React.Fragment>
        )
    }
}

export default CeltoFahr

*CelToFahrBtn (Here the toggle button is created)

import React, { Component } from 'react'
import CelToFahr from './CeltoFahr'

class CelToFahrBtn extends Component {
    state = {
        celOn: true
    }

    switchCel = () => {
        this.setState({ celOn: !this.state.celOn })
    }

    render = (props) => {
        return (

C°

F°

        )
    }
}

export default CelToFahrBtn

Here when I click on switchCel it must trigger the celcius to fahrenheit value and vice-versa. How to do it? Any suggestions highly appreciated. Thanks in advance

A: I would have the celToFahr be the parent component of the celToFahrBtn and then pass the function you want to invoke via props
<CellToFahrBtn callback={yourfunction}/>

What else could you do is having a common parent for these to components where you would again do the execution via props and callbacks
The 3rd option would be having a global state which would carry the function like Redux or Reacts own Context. There again you would get the desired function via props and you would execute it whenever you like. This is the best option if your components are completely separated in both the UI and in source hierarchically, but I don't think this is the case in this case.
https://reactjs.org/docs/context.html
These are pretty much all the options you have

A: To achieve this you'd need to lift your state up and then pass the state and handlers to the needed components as props.
CeltoFahr & CelToFahrBtn would then become stateless components and would rely on the props that are passed down from TemperatureController
class TemperatureController extends Component {
    state = {
        celOn: true
    }

    switchCel = () => {
        this.setState({ celOn: !this.state.celOn })
    }

    render () {
       return (
         <React.Fragment>
            <CeltoFahr celOn={this.state.celOn} switchCel={this.state.switchCel} />
            <CelToFahrBtn celOn={this.state.celOn} switchCel={this.state.switchCel}/>
         </React.Fragment>
       )
    }
}

It's probably better explained on the React Docs https://reactjs.org/docs/lifting-state-up.html

A: See this more simplified example:
import React, {useState} from 'react';

const Display = ({}) => {
    const [count, setCount] = useState(0);

    return

        {count}
        <Button countUp={() => setCount(count +1)}></Button>

}

const Button = ({countUp}) => {
    return <button>Count up</button>
}

It's always possible, to just pass down functions from parent components.  See Extracting Components for more information.
It's also pretty well described in the "Thinking in React" guidline. Specifically Part 4 and Part 5.

A: In React you should always try to keep components as dumb as possible. I always start with a functional component instead of a class component (read here why you should).
So therefore I'd turn the button into a function:
import React from 'react';
import CelToFahr from './CeltoFahr';

function CelToFahrBtn(props) {
  return (

 props.switchCel()} className="CelSwitchWrap">

C°

F°

  );
}

export default CelToFahrBtn;

And you should put the logic in the parent component:
import React, { Component } from 'react';
import CountUp from 'react-countup';
import CelToFahrBtn from './CelToFahrBtn';

class CeltoFahr extends Component {
  state = {
    celOn: true
  };

  switchCel = () => {
    this.setState({ celOn: !this.state.celOn });
  };

  render() {
    return (
      <>

                <CelToFahrBtn switchCel={this.switchCel} celOn={celOn} />

      </>
    );
  }
}


text:
Q: Excel VBA Code to Force a certain zoom level I have a Validated Dropdown list in Excel that is unreadable if zoom is less than 100. I checked on the internet and fvound that I can not alter the size of the Validated list text size so I want to enforce a set zoom of 100.
I have the code to do this as follows
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    ActiveWindow.Zoom = 100
End Sub

This works and is fine for people who use zoom less than 100, but if people use a greater than 100 zoom it restricts the zoom to 100. Is there a way to overcome this, something along the lines of an If-Else statement.
If zoom less than 100 then zoom = 100
else if zoom greater than 100 do nothing
Thanks.

A: Here's a one-liner that will do the same thing:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  ActiveWindow.Zoom = Application.Max(ActiveWindow.Zoom, 100)
End Sub

A: If (ActiveWindow.Zoom < 100) Then

    ActiveWindow.Zoom = 100

End If

A: To address returning to the default previous zoom level (and prevent unnecessary zoom flickering I suggest:
'Assumed default zoom level= 70
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim Temp As Byte
Temp = 0
        If Not Intersect(Target, Range("G3:H9999")) Is Nothing Then
             If ActiveWindow.Zoom <= 70 Then ActiveWindow.Zoom = 100
             Temp = 1
        End If

        If Not Intersect(Target, Range("E2:E9999")) Is Nothing Then
                If ActiveWindow.Zoom <=70 Then ActiveWindow.Zoom = 100
               Temp = 1
        End If

       If Temp = 0 And ActiveWindow.Zoom = 100 Then ActiveWindow.Zoom = 70
End Sub


text:
Q: How to build Swift project on NixOS? I'm trying to build a simple Swift project on NixOS. Here are the steps to reproduce:
git clone https://github.com/PerfectlySoft/PerfectTemplate.git
cd PerfectTemplate
touch shell.nix

Add shell.nix with following contents:
with import <nixpkgs> {};

stdenv.mkDerivation {
  name = "swift-env";

  buildInputs = [
    openssl
    stdenv
    binutils
    cmake
    pkgconfig
    curl
    glibc
    icu
    libblocksruntime
    libbsd
    libedit
    libuuid
    libxml2
    ncurses
    sqlite
    swig
  ];

}

Running nix-shell --pure shell.nix and from there swift build, gives me:
gcc: error: x86_64-unknown-linux: No such file or directory
gcc: error: unrecognized command line option '-target'
gcc: error: unrecognized command line option '-fblocks'
gcc: error: x86_64-unknown-linux: No such file or directory
gcc: error: unrecognized command line option '-fmodules'; did you mean '-fmudflap'?
gcc: error: x86_64-unknown-linux: No such file or directory
gcc: error: x86_64-unknown-linux: No such file or directory
gcc: error: x86_64-unknown-linux: No such file or directory
gcc: error: x86_64-unknown-linux: No such file or directory
gcc: error: unrecognized command line option '-target'
gcc: error: x86_64-unknown-linux: No such file or directory
gcc: error: unrecognized command line option '-fblocks'
gcc: error: unrecognized command line option '-target'
gcc: error: unrecognized command line option '-target'
gcc: error: unrecognized command line option '-target'
gcc: error: unrecognized command line option '-fblocks'
gcc: error: unrecognized command line option '-fmodules'; did you mean '-fmudflap'?
gcc: error: unrecognized command line option '-fblocks'
gcc: error: unrecognized command line option '-fblocks'
gcc: error: unrecognized command line option '-fmodules'; did you mean '-fmudflap'?
gcc: error: unrecognized command line option '-target'
gcc: error: unrecognized command line option '-fmodules'; did you mean '-fmudflap'?
gcc: error: unrecognized command line option '-fmodules'; did you mean '-fmudflap'?
gcc: error: unrecognized command line option '-fblocks'
gcc: error: unrecognized command line option '-target'
gcc: error: unrecognized command line option '-fmodule-name=PerfectCZlib'
gcc: error: unrecognized command line option '-fmodules'; did you mean '-fmudflap'?
gcc: error: unrecognized command line option '-fmodules-cache-path=/home/dmi3y/Dev/Swift/PerfectTemplate/.build/x86_64-unknown-linux/debug/ModuleCache'
gcc: error: unrecognized command line option '-fblocks'

I'd appreciate any help with this as I'm pretty much new to nix-shell and NixOS.
EDIT:
I changed my shell.nix to this:
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
  name = "swift-env";

  buildInputs = with pkgs; [
    openssl
    clang
    swift
  ];

  shellHook = ''
    CC=clang
  '';
}

However, when I run nix-shell followed by swift build, I'm now getting:
[1/25] Compiling PerfectCZlib zutil.c
[2/25] Compiling PerfectCZlib uncompr.c
[3/25] Compiling PerfectCZlib inftrees.c
[4/25] Compiling PerfectCZlib inflate.c
[5/25] Compiling PerfectCZlib trees.c
[6/25] Compiling PerfectCZlib inffast.c
[7/25] Compiling PerfectCZlib infback.c
[8/25] Compiling PerfectCZlib gzwrite.c
/nix/store/iz6k7x3l14ykr56crz3dizas1rrkcyzr-clang-wrapper-7.1.0/resource-root/include/module.modulemap:24:8: error: redefinition of module '_Builtin_intrinsics'

#  warning _FORTIFY_SOURCE requires compiling with optimization (-O)
   ^
1 warning and 3 errors generated.
1 warning and 3 errors generated.

Full log can be found here.
This is now looks like a missing library dependency or a version conflict.
For the record, here's additional information about my setup that might shed more light:
$ nix-channel --list
home-manager https://github.com/rycee/home-manager/archive/master.tar.gz
nixos https://nixos.org/channels/nixos-19.09

$ nix-shell --run 'swift -version'
Swift version 5.0.2 (swift-5.0.2-RELEASE)
Target: x86_64-unknown-linux-gnub

After searching the web I found a Jira issue for Swift compiler and this specific comment. I decided to exclude clang from dependencies and only include swift, since this combination seem to be conflicting:
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
  name = "swift-env";

  buildInputs = with pkgs; [
    openssl
    swift
  ];

  shellHook = ''
    CC=clang
  '';
}

And that worked! I was finally able to build the project!

A: Since your using the --pure option, nothing from your previous environment will be imported into the shell. This includes the swift binary itself. So first I would add swift to the buildInputs.
The error your getting indicates that gcc doesn't even understand the command line options being passed. I don't know anything about Swift, but after seeing that I assumed that it needs a different compiler. Sure enough, after a quick search it looks like it is llvm based. You will thus need to also add clang to your build inputs. In addition, you'll need to use mkShell instead of mkDerivation to setup the proper environment.
The former is a wrapper to the latter that is specifically designed to set up a nix-shell, and ensures the environment is handled correctly. You'll need to pass in the shellHook attribute to override the default c compiler to clang using the CC envvar. The shellHook is a way of running arbitrary commands at the start of the shell.
As a final note, the nix-shell command searches for shell.nix by default so you don't have to pass it as an argument. If shell.nix does not exist, then it will try default.nix. If neither exist, then you'll have to explicitly specify the nix expressions location.
TLDR
to put it all together:
# a more idiomatic way to import nixpkgs, overridable from the cmdline
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
  name = "swift-env";

  buildInputs = with pkgs; [
    # your other inputs
    clang
    swift
  ];

  shellHook = ''
    CC=clang
  '';
}

Just to be sure my logic was correct I downloaded the repo and gave it go. Everything compiles and runs successfully.


text:
Q: converting into swift 2.0 got error in managedObjectContext  func read()
 {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext!

    let fetchRequest = NSFetchRequest(entityName: "Coupons")

    var error: NSError?

    let sortDescriptor = NSSortDescriptor(key: "coupon_id", ascending: true)

    // Set the list of sort descriptors in the fetch request,
    // so it includes the sort descriptor

    fetchRequest.sortDescriptors = [sortDescriptor]
    for var i = 0; i < fetch_coupon_category.count ; i++ {

    //condition like here.
    let predicate1 = NSPredicate(format: "coupon_categories == %@", fetch_coupon_category[i])

 // Set the predicate on the fetch request
// Combine the two predicates above in to one compound predicate
//let the predicate on the fetch request

    fetchRequest.predicate = predicate1

I'm trying to make this code into swift2 making some try catch functionality
        do{
            let fetchedResults = try managedObjectContext.executeFetchRequest(fetchRequest)
                as? [NSManagedObject]?

                if let results = fetchedResults {

                for (var i=0; i < results.count; i++) {

                    let single_result = results[i]

                    let out = single_result.valueForKey("coupon_name") as! String
                    tickets.append(single_result)

                }

            }
            else
            {
                print("cannot read")
            }
        }catch let fetchError as NSError{

            print("fetching error: \(fetchError.localizedDescription)")
           // return nil

        }

    }

}

I'm getting error in manage

'try managedObjectContext' use unresolved identifier

how can I convert my code into swift 2.0 getting more error converting my code -.-

A: Use try managedContext instead of try managedObjectContext because actually you assigned value of managedObjectContext into managedContext in current viewcontroller


text:
Q: Python JSON to CSV conversion I am working on an example but stuck with some points. I am a beginner for python and try to improve myself. I am trying to use openweather api and get some data from it and then write these data to a csv file. The aim of my code is input a txt file which contains city names, I want to get City name, Country code, lat long, Temperature, Wind speed, Wind direction. and then write them to a csv file. I can input the txt file or get the data with input from the command line but can not do both. And also I want to write the data to a csv file. Could you please help me? I can write it to the console, but I need to write them to the csv file. But, I can not convert my json object to csv
My input.txt
Los Angeles
San Francisco
...

My code:
import requests
from pprint import pprint
import csv
import pandas as pd

file = input("Input the filepath: ")

with open(file) as f:
    for line in f:
        line = line.strip()

        API_key = "MYAPIKEY"
        base_url = "http://api.openweathermap.org/data/2.5/weather?"
        headers = {'content-type': 'application/json'}

        city_name = line

        Final_url = base_url + "appid=" + API_key + "&q=" + city_name

        weather_data = requests.get(Final_url).json()

        print("\nCurrent Weather" + city_name + ":\n")
        weather_data = requests.get(Final_url, headers=headers)

        f = open('weather_data_file.csv', "w")
        f.write(weather_data.text)
        f.close()
        print(f)

The problem after edit:

The CSV file just contains the last city data and data is not in a
proper form if I open with excel

The data it outputs:
{"coord":{"lon":-122.42,"lat":37.77},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":284.74,"feels_like":280.59,"temp_min":283.15,"temp_max":286.48,"pressure":1024,"humidity":76},"visibility":10000,"wind":{"speed":5.1,"deg":260},"clouds":{"all":40},"dt":1609003065,"sys":{"type":1,"id":5817,"country":"US","sunrise":1608996226,"sunset":1609030632},"timezone":-28800,"id":5391959,"name":"San Francisco","cod":200}

A: To write your JSON file to a CSV file:
import pandas as pd

if __name__ == "__main__":
    df = pd.read_json (r'ajsonfile.json')
    df.to_csv (r'filename.csv', index = None)

To write your JSON data from an API:
# Get JSON Data
weather_data = requests.get(yourURL, headers=yourHeaders)

# Write to .CSV
f = open('weather_data_file.csv', "w")
f.write(weather_data.text)
f.close()

A: JavaScript Object Notation (JSON) is a serialized representation of data. pandas.read_json tries to decode the JSON and build a dataframe from it. After you've read the the data with requests and deserialized it into python with the .json() call, its not JSON anymore and pandas.read_json won't work.
Sometimes you can build a dataframe directly from the python object, but in this case you've got an additional problem. You are only asking for one row of data at a time (one city) and its information is nested in multiple dictionaries. You can use python to flatten the received city data into the subset of data you want. And since you are only working row by row anyway, use the csv module to write the rows as you go.
A solution is
import requests
from pprint import pprint
import csv

openweathermap_city_csv_header = ["City Name", "Country Code", "Lat", "Long", "Temperature",
    "Wind Speed", "Wind Direction"]

def openweathermap_city_flatten_record(record):
    coord = record["coord"]
    wind = record["wind"]
    return { "City Name":record["name"],
        "Country Code":record["Code"],
        "Lat":coord["lat"],
        "Long":coord["lon"],
        "Temperature":record["main"]["temp"],
        "Wind Speed":wind["speed"],
        "Wind Direction":wind["deg"] }

file = input("Input the filepath: ")

with open(file) as cities, open('weather_data_file.csv', "w") as outfile:
    writer = csv.DictWriter(outfile, openweathermap_city_csv_header)
    for line in f:
        line = line.strip()
        API_key = "MYAPIKEY"
        base_url = "http://api.openweathermap.org/data/2.5/weather?"
        headers = {'content-type': 'application/json'}
        city_name = line
        Final_url = base_url + "appid=" + API_key + "&q=" + city_name
        weather_data = requests.get(Final_url, headers=headers).json()
        print("\nCurrent Weather" + city_name + ":\n")
        writer.writerow(openweathermap_city_flatten_record(weather_data))


text:
Q: Determine which element triggered OnItemClickListener I have got a listview with 2 textviews inside it. I have set up my OnItemClickListener which works fine. However, I was wondering how to determine whether the OnItemClickListener was triggered by TextView01 or TextView02?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content" android:gravity="left|center"
 android:layout_width="wrap_content" android:paddingBottom="5px"
 android:paddingTop="5px" android:paddingLeft="5px">
 <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
 android:layout_height="wrap_content" android:gravity="center"
 android:background="@drawable/bg" android:textColor="#FFFF00"
 android:text="hi"></TextView>
 <TextView android:text="@+id/TextView02" android:id="@+id/TextView02"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:layout_marginLeft="10px" android:textColor="#0099CC"></TextView>
</LinearLayout>`

 public void onItemClick(AdapterView<?> a, View v, int position, long id) {

 }
 });

A: onitemClickListener is not triggered by click on textview. onItemClickLister() is a callback listener for listview; it is called when user click on list view.
To get click event on textview add clicklistener to textview. You will get its callback in OnclickListener(view v).


text:
Q: Can we say that: $ \sum_{n\geq 1}{\frac{1}{n}(f_n(\omega)-g_n(\omega))}<\infty\qquad a.e $ Let $(\Omega,\mathcal{A},\mu)$ be a finite mesure space, and $\{f_n\}$  and $\{g_n\}$ two $L^1$-bounded  sequences, such that :
$$
\sum_{n\geq 1}{\frac{1}{n}(F_n(f_n)(\omega)-g_n(\omega))}<\infty\qquad a.e
$$
with: $F_n(f_n)=f_n1_{|f_n|\leq n}$
Can we say that:
$$
\sum_{n\geq 1}{\frac{1}{n}(f_n(\omega)-g_n(\omega))}<\infty\qquad a.e
$$

A: Let $f_n$ be independent random variables where $f_n$ takes  values $0, 2n$ with $\mu(f_n=2n)=1/n$ for each $n$. Take $g_n=0$ for all $n$. Then $F_n(f_n)=0$ for all $n$ so the hypothesis holds, but the conclusion fails: $\sum_n (f_n/n) = 2\sum_n 1_{\{f_n=2n\}}$ is infinite a.e. by the Borel-Cantelli Lemma.


text:
Q: javascript determine if my variable is null $(function () {
    //To send data from input text
    $('#add').click(function () {
        var name = $('#name').val();
        var gender = $('#gender').val();
        var age = $('#age').val();
        var address = $('#address').val();
        var illness = $('#illness').val();
        var selectunit = $('#selectunit').val();

        if (typeof name !== null) {
            my codes here...
        } else {
            alert('Some fields are missing!');
        }
        return false;
    });
});

i want to trap my variables (name,age,address,illness) not to be null before doing the codes
please help thanks

A: use
name != null || name != ""

instead of
typeof name !== null

if your case is to check if name is undefined then use
typeof name !== "undefined"

A: You can check for null like so:
if (somevariable == null) { /* code */ }

The check for undefined is a little different:
if (typeof somevariable === "undefined") { /* code */ }


text:
Q: Django admin: ManyToManyField in list_editable? In the Django admin, I would really like to be able to display an editable ManyToManyField in the list display.
It doesn't necessarily need to be the full ManyToManyField control - being able to save just one value would be good enough for the purposes of the list display (though the underlying values are many-to-many in nature).
My model looks like this:
class Item(models.Model):
    name = models.CharField(max_length=500)
    colour = models.ManyToManyField(Colour, related_name='primary_colour')

If I try this in admin.py:
class ItemAdmin(admin.ModelAdmin):
    list_display = ('name', 'colour')
    list_editable = ('colour')

Then I get this error:
'ItemAdmin.list_display[6]', 'colour' is a ManyToManyField which is not supported.

Is there any way at all that I can show an editable ManyToManyField for rapid editing in the list display?
I found this related question, which explains how to make the values visible in the list display, but not editable: ManyToManyField widget in a django admin change list?

A: Django by default won't allow to add ManyToManyField in list_editable in ModelAdmin. So we need to override model admin methods.
On looking your models you need to follow below steps to get the ManyToManyField editable in list display page.
In apps/forms.py  you need to define which ManyToMany fields you need to make editable in list display page. As below,
from django import forms
from app.models import Item

class ItemChangeListForm(forms.ModelForm):

    # here we only need to define the field we want to be editable
    colour = forms.ModelMultipleChoiceField(queryset=Colour.objects.all(),
        required=False)

In app/admin.py  you need to override methods of model admin. As below,
from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
from app.models import Item
from app.forms import ItemChangeListForm

class ItemChangeList(ChangeList):

    def __init__(self, request, model, list_display,
        list_display_links, list_filter, date_hierarchy,
        search_fields, list_select_related, list_per_page,
        list_max_show_all, list_editable, model_admin):

        super(ItemChangeList, self).__init__(request, model,
            list_display, list_display_links, list_filter,
            date_hierarchy, search_fields, list_select_related,
            list_per_page, list_max_show_all, list_editable,
            model_admin)

        # these need to be defined here, and not in ItemAdmin
        self.list_display = ['action_checkbox', 'name', 'colour']
        self.list_display_links = ['name']
        self.list_editable = ['colour']

class ItemAdmin(admin.ModelAdmin):

    def get_changelist(self, request, **kwargs):
        return ItemChangeList

    def get_changelist_form(self, request, **kwargs):
        return ItemChangeListForm

admin.site.register(Item, ItemAdmin)

Now you all set to check the changes, run server and check django admin for Movie model. You can edit ManyToMany field directly from list display page.
Note : If you are going to use muliptle ManyToManyFields editable in list then, you need to set DATA_UPLOAD_MAX_NUMBER_FIELDS in settings.py .

A: You can easily add a custom view to your admin urls and add the required html/javascript/ajax. Here's the basics:
class ItemAdmin(admin.ModelAdmin):
    # regular stuff

    def render_foo(self, obj):
        # add this to your list_display
        html = '<stuff><input/submit action></stuff>'
        return mark_safe(html)

    def get_urls(self):
        urls = super(ItemAdmin, self).get_urls()
        extra_urls = patterns('',
            (r'^process_foo/$', self.admin_site.admin_view(self.process_foo)),
        )
        return extra_urls + urls

    def process_foo(self, request):
        if not request.is_ajax():
            raise Http404
        foo = request.GET.get("attr")
        # process m2m
        # return some json


text:
Q: how to recreate button in excel VTO adds-in i have this pieace of code which gets activated when i press a button on the ribbion
Microsoft.Office.Tools.Excel.Worksheet vstoDocument = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1]);
Excel.Range selection = Globals.ThisAddIn.Application.Selection as Excel.Range;

 if (selection != null)
{
 Button button = new Button();
 button.Text = "THIS IS A BUTTON";
 vstoDocument.Controls.AddControl(button, selection, name);
 button.Click += new EventHandler(btn_Click);
// save the button state and name in custom properties
 Excel.Worksheet sheet = Application.ActiveSheet as Excel.Worksheet;
 sheet.CustomProperties.Add("btnName" "btn_1");
 sheet.CustomProperties.Add("text","THIS IS A BUTTON");
 sheet.CustomProperties.Add("selection", selection);
}

//the click event
void btn_Click(object sender, EventArgs e)
{
 MessageBox.Show("I got Clicked");
}

so this works when i press the button on the ribbion
the problem is when i save the excel and open it again the range does not get assigned in my startup code
 Excel.Application wb;
            wb = this.Application;

            if (wb.ActiveCell.Count > 0)
            {

                object docIndex = 1;
                Worksheet vstoDocument = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1]);
                foreach (Excel.CustomProperty prop in props)
                {
                    if (prop != null)
                    {
                        string pn = prop.Name;
                        if (pn.Contains("selection"))
                        {

                            Excel.Range selection = prop.Value as Excel.Range;
                            if (selection != null)
                            {
                                Button button = new Button();
                               vstoDocument.Controls.AddControl(button, selection, "btn_1");//get an error here
                                button.Click += new EventHandler(btn_Click);
                                button.Text = "THIS IS A BUTTON";
                                button.TextAlign = ContentAlignment.MiddleCenter;
                            }
                        }
                    }
                }

i get an error there saying

System.OutOfMemoryException   HResult=0x8007000E   Message=Not enough
memory resources are available to complete this operation. (Exception
from HRESULT: 0x8007000E (E_OUTOFMEMORY))   Source=   StackTrace:


text:
Q: Edit an existing answer, or incorporate existing answer into a new one?
Possible Duplicate:
Which solution is better? Edit old answer or add new one?

If there is a good answer that could be improved with more information, what is the best way to add that information:

*

*Edit and extend the existing answer with the new/extra information.

*Create a new answer which includes the content of the earlier existing answer

*Create a new answer in isolation from the existing answer

A: Note: I'm not sure how tolerated this is elsewhere, but the Physics.SE community seems to be fine with it.
Depends. I usually use
4) Write an "extension" answer, referring to the original answer, adding the relevant data.
I generally think its impolite to make major edits to an established user's answer. Also, my addendums usually go way beyond the scope of the other answer.
General rule of thumb:

*

*If its just a bit of more info (read:a paragraph), add it and leave a comment.

*If it's a completely new bundle of stuff, but is based on stuff gleaned from the answer, write an addendum answer as described above. Hat it with "This is in addition to @JonSkeet's answer". You may also comment on the original answer and ask the poster to incorporate your answer if s/he wishes--and then delete your answer once the deal is done (Something smilar could have happened here, though it didn't).

Examples:
Factors affecting torque and RPM of a motor
How can one imagine curled up dimensions?
Penetration versus Frequency
Will an emf be induced across the ends of a stationary metal rod placed in a time-varying magnetic field?

A: If the edits are minor then do it on the existing answer but if the edits are major then add your own answer and you can refer to that answer in yours.
But your 3rd option states the different topic, i mean giving answer isolated from the another user's answer is a case when you have the answer in different way for the same question then you have to share it as new answer, in this case don't edit existing answer.

A: IMHO option 3, add a different answer with the fixes. I think there should be specific protocol that way there is no confusion and no argument over what constitutes a minor or major change. If the answer is wrong, post a new one.


text:
Q: Using conditional probability to calculate sentiment score probability I would like to find out the probability of A(tweet sentiment being negative or positive) based B (the length of the tweet).
This to me sounds like a conditional probability problem and know that the formula translates to P(A|B) = P(A and B)/P(B), but I have no idea how to implement in on my R dataframe. Just to be clear I am trying to calculate the probability of a sentiment being positive or negative if it contains over 35 words
This is a sample of my dataframe
Data
Sorry for not producing an example of what I have done, kind of stumped on what to do

A: In order to calculate $P(A|B)$ using a dataframe in R, you'll want to find the proportion of cases where $A$ is true and $B$ is also true and then divide by the number of observations where $B$ is true.  So for example, let's say we have this dataset:
> ##Generate some sample data
> set.seed(3434)
> n<-100
> A<-rbinom(n, 1, .25)
> B<-rbinom(n, 1, 0.6)
> mydata<-data.frame(A=A, B=B)
> rm("A", "B")
> head(mydata)
  A B
1 0 1
2 1 0
3 0 0
4 0 1
5 1 0
6 0 0

Then you can calculate $P(A|B)$ in one of two ways:
Method 1
You could use the formula you mentioned in your post and obtain ${P(AB)\over{P(B)}}$ by summing all the observations where both $A$ and $B$ are true (or equal 1 as I'm assuming 1=TRUE here) and dividing by the total number of observations in the dataframe ($n=100$) to obtain the proportion or probability $P(AB)$, and then dividing by the proportion of those cases where $B$ is true to obtain $P(B)$.
> ##Method 1
> A_true_count <- sum(mydata$A)
> B_true_count <- sum(mydata$B)
> A_and_B_true_count <- sum(mydata$A + mydata$B>1)
> P_of_A <- A_true_count/n
> P_of_B <- B_true_count/n
> P_of_A_and_B <- A_and_B_true_count/n
> P_of_A_given_B_m1 <- P_of_A_and_B/P_of_B
> P_of_A_given_B_m1
[1] 0.2807018

Method 2
You could obtain $P(A|B)$ directly by considering $P(A|B)$ as a reduced sample space.  So you simply determine those cases where $B$ is true and then for each of those, find the proportion where A is also true.  This will yield the same result as method 1.
> ##Method 2
> #For the reduced sample space where B is True, What proportion have A=True?
> P_of_A_given_B_m2 <- sum(mydata$A[mydata$B==1])/sum(mydata$B==1)
> P_of_A_given_B_m2
[1] 0.2807018

So, in this example, $P(A|B)=0.2807018$.  Of course, there are several ways to go about getting these more quickly using various functions in R, but this shows the computation in a way that's hopefully easier for you to understand the probability concepts as well as the computation in R.


text:
Q: Javascript autocomplete current line and add {} curly braces? In VS Code, is there a way I can use keyboard combination like "ctrl+enter" to finish the current line and add { automatically at end of the line? instead of that i have to go to the end of the line my self and type { for it.
For example, when I typed if, VS code gives me if () blocks automatically, and I started typing condition in the braces.
if (condition)
// while the cursor is after 'n' but before ')'

When I'm at the end of the "condition", I have to use arrow key to move to the end and add {}. Do you program Javascript in this way or you have better tools/keyboard shortcut to use?
While I'm programming in Python, most IDE like VScode or Pycharm provides quick completion keyboard shortcut like "ctrl+shift+enter" to finish the line by adding ":" at end of the sentence, which applies to both defining functions, if, for, conditions. But unfortunately I haven't found such a way in Javascript world yet.

A: Search for snippets on the VS extension section ,I think you can find it there for any programming language .


text:
Q: Using Fb.ui feed method not showing message nor user_prompt_message at all using default messages Hi I am new to facebook development, and would like to post a feed using this code below, but the message nor the user_message_prompt do not appear in the text box. Do I need to set something in my application to allow this. All I get is default messages.
I tried the 2 methods below, and both of them do not show the message nor user_message_prompt message.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

A: I believe they are both deprecated. The message parameter is now ignored and I didn't see the other parameter in the documentation. Apparently, Facebook wants users to put their own message into the text field rather than be forced or prompted. Check out the main info page for it here:
https://developers.facebook.com/docs/reference/javascript/FB.ui/
and the detailed page here:
https://developers.facebook.com/docs/reference/dialogs/feed/
Scroll to the bottom and you'll see the supported parameters. Hopefully it's not a game changer for you.

A: You should do something like this
window.fbAsyncInit = function() {FB.init({
appId: '{YOUR APP ID}',
xfbml: true,
version: 'v2.1'
});
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function share_prompt() {
FB.ui({
method: 'feed',
name: 'Your App Name',
link: 'https://example.com',
picture: 'http://example.com/img/fbicon.jpg',
caption: 'Your Caption here',
description: 'some sort of your own description',
message: 'Your Message goes here mate'
 });
 }

Then call the function like below;

Click to open your dialog


text:
Q: php array_multisort use array name as argument Sorry if this is duplicate, I have tried to look at previous posts, but maybe my limited understanding of php gets in the way.
This works to sort arrays 1 and 3 by array 2:
<?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");

array_multisort($ar[2],$ar[1],$ar[3]);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>

output:
rock  A  one
 scissors  B  two
 paper  C  three
 game  D  four
Fine. But I want the list of arrays used as argument for array_multisort() to be specified by user input, so it can't be literal. Instead, I would like the program to decide the order of arrays in the list based on the user input and then name the resulting array of arrays $supar (superarray). But when using $supar as argument for array_multisort(), no sorting is carried out.
<?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");

$supar = array($ar[2],$ar[1],$ar[3]);
array_multisort($supar);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>

Output:
game  D  four
 scissors  B  two
 rock  A  one
 paper  C  three
How should I do to make array_multisort() sort the arrays in $supar by a specified $ar array?
Thank you for your patience.

A: You can't do that with just the PHP function. array_multisort() takes the different arrays separately as arguments and you can't just pass a different thing with the intended arguments inside.
What you could do is writing your own function to do that for you. Something like:
function my_multisort($supar) {
    array_multisort($supar[2], $supar[1], $supar[3]);
}

$supar = array(
    array("game","scissors","rock","paper"),
    array("D", "B", "A", "C"),
    array("four","two","one","three")
);

my_multisort($supar);

EDIT
As @axiac correctly pointed out, this is basically a weird specific way of reinventing call_user_func_array(). You can simply build your array of arguments $supar as you need and then do
call_user_func_array('array_multisort', $supar);

A: You can call array_multisort() (or any other function) without specifying its arguments explicitly if you have the arguments in an array by using call_user_func_array().
array_multisort() gets its arguments by reference (in order to be able to modify them). You have to consider this when you build the array you use as argument to call_user_func_array() and put references in this array:
// Input arrays
$ar[1] = array("game", "scissors", "rock", "paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] = array("four", "two", "one", "three");

// Build the list of arguments for array_multisort()
// Use references to the arrays you want it to sort
$supar = array(&$ar[2], &$ar[1], &$ar[3]);

// Call array_multisort() indirectly
// This is the same as array_multisort($ar[2], $ar[1], $ar[3]);
call_user_func_array('array_multisort', $supar);

Check it in action: https://3v4l.org/ptiog