text:
Q: Django Form: Hidden Field Error When going to next wizard: (Hidden field ) This field is required I have tried couple of ways to avoid this error from view code and on django template as well. Also tried to popped  out the fields as well but none are working and getting the same error every time(This field is required) . We are using step wizards to show and hide the fields on different form wizard steps from views.py . Whenever we visit the  previous page on click on previous button then only the step 2 fields are empty and showing the error. Appreciate any quick help on this.
Here is the models.py

from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

class CStructure(models.Model):

    z_caisson_lower_limit = models.FloatField(verbose_name='C level limits', default=5.0)
    z_caisson_upper_limit = models.FloatField(verbose_name='C limits', default=10.0)
    z_caisson_step_size = models.FloatField(verbose_name='C level limits', default=1)
    caisson_width_lower_limit = models.FloatField(verbose_name='C width limits', default=10)
    caisson_width_upper_limit = models.FloatField(verbose_name='C width limits', default=20)
    caisson_width_step_size = models.FloatField(verbose_name='C width limits', default=5)

Here is the form.html

{% block content %}
    {% if wizard.steps.current == '3' %}

                Calculation can be cancelled on the project
                page.

    {% endif %}
    // Below are the steps of wizards to show the fields or fields label

`enter code here`

Design
                & Hydraulic

Shape constraints

Material

Cost unit rates

Results

                {% bootstrap_messages %}
                {% block bootstrap4_content %}
                    {% load i18n %}
                    {{ form }}
                    {% if form.errors %}
                        {% for field in form %}
                            {% for error in field.errors %}

                                    {{ field.label }}: {{ error|escape }}

                            {% endfor %}
                        {% endfor %}
                    {% endif %}
                    <form method="post" enctype="multipart/form-data">
                        {% csrf_token %}
                        {{ wizard.form.media }}
                        {{ wizard.management_form }}
                        {% if wizard.form.forms %}
                            {{ wizard.form.management_form }}
                            {% for form in wizard.form.forms %}
                                {% bootstrap_form form layout='horizontal' %}
                            {% endfor %}

                         {% endif %}

Here is the form.py

class CaissonStructureStep(forms.ModelForm):

    class Meta:
        model = CaissonStructure
        fields = ['z_caisson_lower_limit',
                  'z_caisson_upper_limit', 'z_caisson_step_size',
                  'caisson_width_lower_limit', 'caisson_width_upper_limit']

        widgets = {
             'z_caisson_lower_limit': forms.TextInput(attrs={'class': 'cs form-control'}),
            'z_caisson_upper_limit': forms.TextInput(attrs={'class': 'cs form-control'}),
            'z_caisson_step_size': forms.TextInput(attrs={'class': 'cs form-control'}),
            'caisson_width_lower_limit': forms.TextInput(attrs={'class': 'cs form-control'}),
            'caisson_width_upper_limit': forms.TextInput(attrs={'class': 'cs form-control'}),
            'caisson_width_step_size': forms.TextInput(attrs={'class': 'cs form-control'}),
            'z_base_lower_limit': forms.TextInput(attrs={'class': 'cs form-control'}),
            'z_base_upper_limit': forms.TextInput(attrs={'class': 'cs form-control'}),
            'z_base_step_size': forms.TextInput(attrs={'class': 'cs form-control'})
            }

    def clean(self):
        cleaned_data = super(CaissonStructureStep2, self).clean()
        for field in list(cleaned_data):
            if '_lower_limit' in field:
                custom_validator.validate_min_max_step_size(self, cleaned_data, field)

        return cleaned_data

    def __init__(self, request, *args, **kwargs):
        super(CaissonStructureStep2, self).__init__(*args, **kwargs)

Here is the code in view.py to hide form fields

from django import forms
def get_form(self, step=None, data=None, files=None):
    form = super(WaterBreakerWizard, self).get_form(step, data, files)
    step = step or self.steps.current

    if step == '1':
        caisson_type_elements = self.storage.data['step_data']['0']['0-caisson_type']
        if ('CAISSON' in caisson_type_elements):

            fields_to_remove = ['z_c_lower_limit', 'z_c_upper_limit', 'z_c_step_size']
            for fields in fields_to_remove:
                # form.fields.pop(fields)
                form.fields[fields].widget = forms.HiddenInput()

        if ( 'RUBBLEMOUND' in caisson_type_elements):
            fields_to_remove = ['z_caisson_lower_limit', 'z_caisson_upper_limit']
            for fields in fields_to_remove:
                # form.fields.pop(fields)
                form.fields[fields].widget = forms.HiddenInput()

    elif step == '2':
        caisson_type_elements = self.storage.data['step_data']['0']['0-caisson_type']
        if ('RUBBLEMOUND' in caisson_type_elements):
            fields_to_remove = ['rho_caisson', 'rho_fd', 'rho_fw', 'rho_bd', 'rho_bw']
            for fields in fields_to_remove:
                if fields in form.fields:
                    form.fields[fields].widget = forms.HiddenInput()
        if ('CAISSON' in caisson_type_elements):

            fields_to_remove = ['rho_w', 'rho_c', 'rho_r', 'rock_gradings',
                                'core_material']
            for fields in fields_to_remove:
                # form.fields.pop(fields)
                form.fields[fields].widget = forms.HiddenInput()

    return form


text:
Q: Reintegrate merge claims missing revisions with numbers lying before branch creation During SVN reintegrate-merge (TortoiseSVN/Windows), I get the following errors:

Command: Auto-merge /svn/branches/branchX into C:\MyRepoFolder
  Error: Reintegrate can only be used if revisions 59635 through 65976 were
  previously
  Error:  merged from svn/trunk to the reintegrate
  source, but this is not the case:
  Error:
  Error: svn/branches/branchX/Applications/.../source/someFile.cpp
  Error:
  Error: Missing ranges:
  Error: /trunk/Applications/.../source/someFile.cpp:43835,43956,43965,...
  ...
  (and so on)
  ...

The branch was created at Rev 59635, why are are older ranges around 43835 missing when the branch was created from trunk in the past?
Can someone please tell me how this is possible and how to solve the issue?
I have already tried many things including:

*

*trunk -> branch: auto merge of problematic revisions

*trunk -> branch: record only merge of these old revisions

*adding revisions to corresponding merge-info

The latter did work, but doing this manually is very exhaustive since the list is extremely long (I have listed only a fraction here). All other attempts did not work. But I don't think that manually adding the the revisions to the corresponding merge-infos is the best solution here. Maybe I can write a script that does it automatically. I would be very interested in alternatives? I can't imagine that there is no better solution here.

A: I suspect this issue is a combination of different svn versions used, together with subtree merges. The first alone is not a problem at all, but subtree merges are a prime source of constant headaches.
My suggestion: find out if the maintainers of the repo have a policy on subtree merges, ie, if they explicitly allow or disallow merging not just at the root level of a branch but also individual files or subfolders.
If they allow it: sorry, you're screwed. Try to find the people who did the subtree merges and ask them if they still use this subtree merge info (and what they were thinking when they did it in the first place).
If subtree merges are not allowed (or you are the sole maintainer of the repo), just delete all subtree merge information but preserve it at the root level. You can do this eg by going to the root of your clean branch working copy and executing
svn pd svn:mergeinfo . -R
svn revert .

The first command will delete all merge information recursively (including the bad stuff), the second will restore the useful and necessary merge information at the branch root. Before proceeding, make sure you did not change anything else (if you did it right, svn st should show a bunch of files/folders with an M only in the second column, indicating that only properties were changed) and commit. Afterwards, reintegration should work again.
Please note: the svn:mergeinfo property is "sticky", so once you merge the trunk again to your branch (or reintegrate other branches with subtree merge information), the bad merge info properties will reappear. To really get rid of them, you need to delete the subtree merge information in the trunk itself and force all users to do the same for their branches before reintegrating back to trunk. We had a similar issue about a year ago and what we did was to check out the whole branches/ subfolder and run a script to delete all unnecessary merge information from all branches simultaneously.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Computing the size of a  on load?

    <canvas id="canvas"> </canvas>

This code displays the size before it has been styled. I need the size after it has been styles. How can I do this?

A: Your problem stems from the difference between the intrinsic dimensions of the canvas and the number of CSS pixels it takes up. The HTML specification says:

The intrinsic dimensions of the canvas
  element equal the size of the
  coordinate space, with the numbers
  interpreted in CSS pixels. However,
  the element can be sized arbitrarily
  by a style sheet. During rendering,
  the image is scaled to fit this layout
  size.

What this means is that your canvas defaults to a drawing space of 300x150px in terms of the coordinates used to draw images. However, your CSS rules will stretch the canvas to the size of the page (at least with regard to width). There will still only be 300px wide to logically draw on, but it will be scaled and physically rendered on whatever 100% of the page width corresponds to.
Anyway, the width and height properties correspond to the intrinsic drawing dimensions of the canvas. Since you care about the CSS size, you can use window.getComputedStyle.
http://jsfiddle.net/3DDsX/

  <canvas id="canvas"></canvas>

A: Do not use the onload function in body, but you can use window.onload instead:

test


text:
Q: Why do I get "Segmentation fault" on fread? When I run valgrind I get this message
==1175== Invalid write of size 8
==1175==    at 0x400923: main (recover.c:37)
==1175==  Address 0x1ffec6e0a8 is on thread 1's stack
==1175==  in frame #0, created by main (recover.c:10)

Line 37 is fread(restored, memSize, 1, mem);
This is my code:
typedef uint8_t BYTE;
#define BLOCK 512

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Invalid number of command-line arguments..\n");
        return 1;
    }

    FILE *mem = fopen(argv[1], "r");

    if(mem == NULL)
    {
        printf("The file could not be opened..\n");
        return 1;
    }

    fseek(mem, 0L, SEEK_END);
    int memSize = ftell(mem);

    rewind(mem);

    printf("%i\n", memSize);

    BYTE restored[memSize];

    fread(restored, memSize, 1, mem);
    fclose(mem);

    // rest of code ...

    return 0;
}


text:
Q: Send email from Linux server as html - Content type and html tags also visible in email I am trying to send an email as html.
#!/bin/sh

#MAIL_LIST="gangadhar.n@xx.com"
MAIL_SENDER=foo

fnSendEmail(){
    echo ${BODY}| mail -r $MAIL_SENDER -s "$(echo "$MAIL_SUBJECT\nContent-Type: text/html")" "$MAIL_LIST"
}

MAIL_SUBJECT="Test email"

BODY="

Hi All

";

fnSendEmail $BODY $MAIL_SENDER $MAIL_SUBJECT $MAIL_LIST

I am receiving email but html tags and Content type also visible in mails as below.
Subject as
"Test email\nContent-Type: text/html"

Email body as:

Hi All

 NOTICE TO RECIPIENT:  If you are not the intended recipient of this e-mail, you are prohibited from sharing, copying, or otherwise using or disclosing its contents.  If you have received this e-mail in error, please notify the sender immediately by reply e-mail and permanently delete this e-mail and any attachments without reading, forwarding or saving them.  Thank you.

Thank you in advance

A: I have done it using sendmail
#MAIL_LIST1="Gangadhar.N@xx.com"
MAIL_SENDER=dap

fnSendEmail(){
(
  echo To: $MAIL_LIST
  echo Cc: $MAIL_LIST
  echo From: dap53
  echo "Content-Type: text/html; "
  echo Subject: $MAIL_SUBJECT
  echo
  echo $BODY
) | /usr/sbin/sendmail -t
}

MAIL_SUBJECT="Test email"
BODY="Sample"

fnSendEmail $BODY $MAIL_SENDER $MAIL_SUBJECT $MAIL_LIST

A: Use option -a to append content-type header, -s is for subject, change your fnSendEmail to following it should work
fnSendEmail(){
    echo ${BODY}| mail -r $MAIL_SENDER -a "Content-type: text/html" -s "$(echo "$MAIL_SUBJECT\n")" "$MAIL_LIST"
}


text:
Q: NSString equals 0? I stumbled across the following code when coding. I'm wondering how it even compiles without warning?
NSString *str = 0
Logging it returns (null) so it's not setting the string literally. Why does this work?

A: With this line, you're assigning the zero value to a pointer, which is only a convention to define a null pointer, which doesn't address to any memory.
Here (Why is address zero used for the null pointer?) you have a discussion about why zero is the null pointer convention in c.

A: In C and, by extension, Objective-C, 0 is the equivalent of NULL and nil and Nil. It's an integer but it freely assigns to any pointer type.


text:
Q: How to get page index in ViewPager after swiping? I've a problem which is I have a viewpager, and I've made a GestureDetector for TouchListener to detect swipes..
I made when user swipes right or left, it increments or decrements an array which have key for every Image according to it's index, so that I can check if this picture is Favorited before or to be able to Download it..etc, it works fine when User swipe smoothly left or right, but the problem is when User swipes fast several times the increment and decrement results incorrect index, so how can I handle such a problem, any ideas?
This is code that extends SimpleOnGestureListener:
      @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean result = false;
        try {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (diffX > 0) {
                        onSwipeRight();
                    } else {
                        onSwipeLeft();
                    }
                }

This is the code when swipe right, and same on swipe left except it increments "pagerPosition" not decrements:
            public void onSwipeRight() {
                pagerPosition--;

               boolean isFavorites = db.checkfavorites(imageUrls[pagerPosition]);
               if(isFavorites){
                      fave.setVisible(true);
                      unfave.setVisible(false);
               }else{
                      fave.setVisible(false);
                      unfave.setVisible(true);
               }

A: If you are using ViewPager why not use OnPageChangeListenerit gives you the position of the current page, you could perform your calculations based on that.


text:
Q: I want to get the parents id from my container in flex I have an issue, so i created a mxml container file called Container1.mxml that has
<mx:VBox>
<mx:Label text="{textName}" />
</mx:VBox>
so when i call it
   it will be something like
<container:Container1 id="hello" />
then the id will appear in my Label text.
appreciate it in advance. thank you

A: Assuming you can't just use text="{this.id}"?
Inside Container1.mxml, have a creation complete listener that calls this function:
protected function _handleCreate(e:Event):void {
    myTextLabel.text = this.id || "unknown";
}


text:
Q: Remove prefix before writing file I have a file name Codex_file001.zip. I wanna remove prefix Codex_ before writing the file. Any help would be appreciated.
File f=new File("Codex_file001.zip");
    String s = f.getName();
    String[] splitted = s.split("_");
    File new1 = new File(splitted[1]);
    Files.copy(f, new1);
    f.delete();

I want to save this file with name file001.zip.

A: It would be something like this:
File f = new File("Codex_test.txt");
String fName = f.getName();
String newFName = fName.substring(fName.indexOf("_")+1);
f.renameTo(new File(newFName));

You can use substring in combination with indexOf to determine the location of the starting character. And then renameTo to create a new file.

A: You can check if String contains _ and then spit, e.g.:
private String removeCharsBeforeUnderscore(String input) {
    return input.contains("_") ? input.split("_")[1] : input;
}

And call it like this:
System.out.println(removeCharsBeforeUnderscore("Codex_file001"));

This would work even if String does not have underscore character.

A: using regex pattern with replaceFirst
String test = "Codex_file001.zip";
System.out.println(test.replaceFirst(".*?_", ""));

output:
file001.zip


text:
Q: Pointers and Their Values in C okay so part of this program i have to create, it's basically a game where a secret number is created and the user has to try and guess it, and i'm having some trouble with the pointers aspect of it. In my "generate_secret_number" function I have no issues in printing the value of the pointer, but in my "imTrying" function when I call the generate_secret_number function and try to print out the value of the pointer a I keep getting an error called "cygwin_exception::open_stackdumpfile:" I was hoping someone could give me some insight as to what I am doing wrong, Thank you so much!
void generate_secret_number(int *a, int *b, int *c)
{
    int num1,num2,num3;

    num1 = (rand() % 5) + 1;
    num2 = (rand() % 6);
    num3 = (rand() % 6);

    a = &num1;
    b = &num2;
    c = &num3;

    printf("the secret number is: %d%d%d", *a,*b,*c);
}

void imTrying(int *a, int *b, int *c)
{
    int num1,num2,num3;
    generate_secret_number(a,b,c);
    printf("\n%d", *a);
}

A: you're taking the addresses of the local variables to store them in local pointer variables (no effect whatsoever outside the function, the printf statement works which adds to the illusion)
a = &num1;
b = &num2;
c = &num3;

instead of copying their values in the passed-by-reference variables, proper way:
*a = num1;
*b = num2;
*c = num3;

(note that you can avoid using num1, etc...) by just doing:
*a = (rand() % 5) + 1;
*b = (rand() % 6);
*c = (rand() % 6);

of course, a, b and c must point to valid memory when calling the function.
int num1,num2,num3;
generate_secret_number(&num1,&num2,&num3);

We don't see the caller of the caller but since you say:

I keep getting an error called "cygwin_exception::open_stackdumpfile:"

it's probably because you caller (you're not showing) is like:
int *a,*b,*c;
imTrying(a,b,c);

since address pointed by a is not initialized, but isn't written to properly because of your other mistake, the program crashes with undefined behaviour when you're trying to print the value.
To fix it, in your context:
void imTrying(int *a, int *b, int *c)
{
    // int num1,num2,num3;  // useless
    generate_secret_number(a,b,c);
}

caller:
int num1,num2,num3;    // valid memory
imTrying(&num1,&num2,&num3);
printf("%d, %d, %d\n", num1,num2,num3);

A: In
foo(int *bar)
{
    bar = 0x42;
}

it would be pointless (no pun intended) to modify the value of bar. (The value of a pointer is the address it holds). Since the pointer bar is a copy of the address that foo() is called with, nobody outside foo() would ever notice, that bar changed.
What you want to do instead, is to change the object bar points too:
foo(int *bar)
{
    *bar = 42;
}


text:
Q: youtube-dl Downloading channel page #number => how to skip old pages?
I live off grid, no internet access. Once in a while I go to the library and run my scripts, which backs up video channels (youtube, bitchute, rumble, ...)
I lose a lot of time with large channels... because youtube-dl has to load all the pages... like:

[BitChuteChannel] thedavidknightshow: Downloading channel page 1
... [BitChuteChannel] thedavidknightshow: Downloading channel page
194

The library blocks BitChute and rumble... so I have to torify those, which slows it down even more.
Since I have already downloaded the whole channel, how do I index the latest page(s) only?
Other tips to speed up the process are welcome too.

A: If you already have the oldest files you can use --playlist-items or --playlist-end
For example:
yt-dlp playlist_url --playlist-end 30

Will only fetch the latest 1 or 2 pages. This also works on accounts or channels because channels are basically playlists of a specific kind


text:
Q: Can someone please clarify what the "<" does when comparing two strings c++ I had a past paper question involving the STL sort algorithm. And it was sorting a vector, i am aware that the sort algorithm sorts into ascending order using the "<" operator. However, I was wondering how two strings are compared? How is a value for a string found? (So i can work out what string is smaller than another in an exam.)

A: Strings are ordered lexicographically. Each character in the first string is compared to the equivalent character in the second string until there are two characters that don't match one another or until one string ends. For example the following statements are true:
"aaab" < "aaac" // because 'b'<'c'
"aaa"  < "aaab" // by convention shorter string are smaller than larger ones
"aaa0" < "aaab" // because '0'=48 and 'b'=98
"aaaB" < "aaab" // because 'B'=66 and 'b'=98

The character comparison is performed using the numeric values of the corresponding characters (using ASCII for instance).


text:
Q: How to fix this. Returning wrong number of list size This queue code must return the exact Head, Tail, and Size of the list. It returns the correct Head and Tail, but the incorrect size.
class Queue:
    '''
        >>> x=Queue()
        >>> x.isEmpty()
        True
        >>> x.dequeue()
        'Queue is empty'
        >>> x.enqueue(1)
        >>> x.enqueue(2)
        >>> x.enqueue(3)
        >>> x.dequeue()
        1
        >>> print(x)
        Head:Node(2)
        Tail:Node(3)
        Queue:2 3
    '''
    def __init__(self):
        # You can add a count variable
        self.head=None
        self.tail=None

    def __str__(self):
        temp=self.head
        out=[]
        while temp:
            out.append(str(temp.value))
            temp=temp.next
        out=' '.join(out)
        return ('Head:{}\nTail:{}\nQueue:{}'.format(self.head,self.tail,out))

    __repr__=__str__

    def isEmpty(self):
        #write your code here
        if self.head == None:
            return True
        else:
            return False

    def __len__(self):
        #write your code here
        node_count = 1
        current_node = self.head
        while current_node != None:
            current_node = current_node.next
            node_count += 1
            return node_count
        else:
            return node_count

    def enqueue(self, value):
        #write your code here
        new_node = Node(value)
        if self.isEmpty():
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node

    def dequeue(self):
        #write your code here
        if self.isEmpty():
            return 'Queue is empty'
        else:
            old_top_node = self.head
            new_top_node = self.head.next
            self.head = new_top_node
            return old_top_node.value

Expected: [12, 8, 11, 5], head=12, tail=5 and size 4
Actual Output: [12, 8, 11, 5], head=12, tail=5 and size 2

A: If you check out your definition of the __len__(self) method:
   def __len__(self):
        #write your code here
        node_count = 1
        current_node = self.head
        while current_node != None:
            current_node = current_node.next
            node_count += 1
            # --- HERE ---
            return node_count
        else:
            return node_count

You are returning the value during the first iteration, so it will always be 2 (or 1 if current_node is None)

A: I feel like this is your issue the promblem stems from first you starting node_count at 1 due to this if there is no node then you will end up with a count of 1 still even though it should be 0. The other thing is your using a return which will exit the function completely. Instead, use continue which will just iterate to back to the top of the loop and after just return the node_count if there are no nodes it will skip the loop and return 0 else it will return the size you are looking for
 def __len__(self):
            node_count = 0
            current_node = self.head
            while current_node != None:
                current_node = current_node.next
                node_count += 1
                contuine
            return node_count


text:
Q: SQL Insert to table 2 column at a time on each row I am stuck on a problem where I need to insert data into a another table, but in a way that I insert 2 columns, then stay on the same row, insert the next 2 and so on.
I have the following table data

I have a table with 2 columns I want to fill but want data to be entered like:
Row 1:(Row1A,Row1B)
Row 2:(Row1C,Row1D)
Row 3:(Row1E,Row1D)
Row 4:(Row2A,Row2B)
Row 5:(Row2C,Row2D)
Row 6:(Row2E,Row2F)

I can achieve the above using a loop, however I want to know another way that can improve performance. Is there a way to achieve this?
Edit: Order needs to be correct. I will need the first row columns added to the table first before moving onto second row.

A: I would use apply:
insert into t2(col1, col2)
    select col1, col2
    from data d cross apply
         (values (varchar1, varchar2), (varchar3, varchar4), (varchar5, varchar6)
         ) v(col1, col2);

Tables represent unordered sets.  Because you have exactly two columns, you don't have a column to specify the ordering.  If you did, then an order by would allow you to have an identity column that captures the ordering.  This would look like:
insert into t2(col1, col2)
    select col1, col2
    from data d cross apply
         (values (varchar1, varchar2, 1), (varchar3, varchar4, 2), (varchar5, varchar6, 3)
         ) v(col1, col2, priority)
    order by d.id, v.priority;


text:
Q: How can I impove this JOIN operation between key table and another My problem is that I have two different queries that work well in different
situations.
SCHEMA
  messages
      message_id, entity_id, message, timestamp

   subscription
      user_id, entity_id

   users
      user_id

   entities
      entity_id

Situation 1: Lots of message entries, and at least one relevant subscription entry
Situation 2: Few message entries and/or few, or zero, subscription entries that are relevant
My Two Queries are:
 SELECT messages.*
   FROM messages
   STRAIGHT_JOIN subscription ON subscription.entity_id = messages.entity_id
   WHERE subscription.user_id = 1
   ORDER BY messages.timestamp DESC
   LIMIT 50

This query works well in situation 1 (.000x seconds):  Lots of message entries, and at least one relevant subscription entry. thisquery will take 1.7+ seconds in situation 2.
 SELECT messages.*
   FROM messages
   INNER JOIN subscription ON subscription.entity_id = messages.entity_id
   WHERE subscription.user_id = 1
   ORDER BY messages.timestamp DESC
   LIMIT 50

This query works well in situation 2 (.000x seconds):  Few message entries and/or few, or zero, subscription entries that are relevant. This query will take 1.3+ seconds in situation 1.
Is there a query that I can use that can get the best of both worlds? If not, what's the best way to
handle this case?
Indexes:
( subscription.user_id, subscription.entity_id )
( subscription.entity_id )
( messages.entity_id, messages.timestamp )
( messages.timestamp )

EXPLAIN INFO
LIMIT 50
| id | select_type | table             | type   | possible_keys                           | key           | key_len | ref                                    | rows | Extra       |
|  1 | SIMPLE      | messages          | index  | idx_timestamp                           | idx_timestamp | 4       | NULL                                   |   50 |             |
|  1 | SIMPLE      | subscription      | eq_ref | PRIMARY,entity_id,user_id               | PRIMARY       | 16      | const, messages.entity_id              |    1 | Using index |

Without Limit
| id | select_type | table             | type   | possible_keys                           | key           | key_len | ref                                    |   rows   | Extra         |
|  1 | SIMPLE      | messages          | ALL    | entity_id_2,entity_id                   | NULL          | NULL    | NUL                                    |   255069 | Using filesort|
|  1 | SIMPLE      | subscription      | eq_ref | PRIMARY,entity_id,user_id               | PRIMARY       | 16      | const, messages.entity_id              |        1 | Using index   |

CREATE TABLE STATEMENTS:
With ~5000 rows
subscription | CREATE TABLE `subscription` (
  `user_id`   bigint(20) unsigned NOT NULL,
  `entity_id` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`user_id`,`entity_id`),
  KEY `entity_id` (`entity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

with ~255,000 rows
messages | CREATE TABLE `messages` (
  `message_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `entity_id` bigint(20) unsigned NOT NULL,
  `message` varchar(255) NOT NULL DEFAULT '',
  `timestamp` int(10) unsigned NOT NULL,
  PRIMARY KEY (`message_id`),
  KEY `entity_id` (`entity_id`,`timestamp`),
  KEY `idx_timestamp` (`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

A: Try changing your WHERE with a AND
SELECT messages.*
   FROM messages
   STRAIGHT_JOIN subscription ON subscription.entity_id = messages.entity_id
        AND subscription.user_id = 1
   ORDER BY messages.timestamp DESC
   LIMIT 50

OR
SELECT messages.*
   FROM messages
   INNER JOIN subscription ON subscription.entity_id = messages.entity_id
           AND subscription.user_id = 1
   ORDER BY messages.timestamp DESC
   LIMIT 50

OR may be this way :
SELECT messages.*
FROM subscription
STRAIGHT_JOIN messages ON subscription.entity_id = messages.entity_id
WHERE subscription.user_id = 1
ORDER BY messages.timestamp DESC
LIMIT 50


text:
Q: Error in mysqli prepare statement $client = $db -> prepare('SELECT CLIENT_ID, CLIENT_NAME FROM client WHERE CLIENT_NAME LIKE "%?%"');
    $query = $_GET['query'];
    $client -> bind_param('s', $query);
    $client -> execute();
    $client -> bind_result($client_id, $client_name);
    while($client -> fetch()){
        $d['suggestions']['value'] = $client_name;
        $d['suggestions']['data'] = $client_id;
    }
    $client -> free_result();

I received the following error in the above statement. Can't see what caused the error.
Warning:  mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in getclient.php on line 15

Notice:  Undefined index: callback in getclient.php on line 24

Now I have another error message:
Call to a member function bind_param() on a non-object

A: You cannot do the LIKE statement like that in regards to percentages.
$client = $db -> prepare('SELECT CLIENT_ID, CLIENT_NAME FROM client WHERE CLIENT_NAME LIKE ?');
$query = $_GET['query'];
$client -> bind_param('s', "%{$query}%");
$client -> execute();
$client -> bind_result($client_id, $client_name);
while($client -> fetch()){
    $d['suggestions']['value'] = $client_name;
    $d['suggestions']['data'] = $client_id;
}
$client -> free_result();`


text:
Q: SQL - Compare 2 Count values to update a Completion field Example Scenario:

*

*an Order has 5 items

*each item has an individual bit column which determines whether or not they have been Received. (ItemReceived) PartsTable

*when all 5 items have been received , I want to update a (OrderComplete)field within the OrdersTable
I know the below code doesn't work but this is an example of what I am trying to achieve:
UPDATE OrdersTable SET OrderComplete = 1
FROM PartsTable
WHERE
     OrdersTable.OrderID = (SELECT TOP 1 OrderID FROM OrdersTable ORDER BY changedate DESC)
AND
    COUNT(PartsTable.ItemReceived) = COUNT(PartsTable.EquipmentID)

so when each individual part has been set as received (ItemReceived), then I want the COUNT function to compare this column to the EquipmentID
Example 1

*

*4 Parts have been Received (ItemsReceived = 4)

*1 Part hasn't been Received

*COUNT(PartsTable.ItemReceived) 4 = COUNT(PartsTable.EquipmentID) 5
In this scenario 4 doesn't equal 5 so nothing happens
Example 2

*

*5 Parts have been Received (ItemsReceived = 5)

*0 Parts have not been Received

*COUNT(PartsTable.ItemReceived) 5 = COUNT(PartsTable.EquipmentID) 5
In this scenario 5 equal's 5 so OrderComplete should equal TRUE
Thanks for any help with this problem

A: You could use NOT EXISTS instead of using COUNT.
This would UPDATE all Orders to complete when there are no parts waiting to be received. If there are one or more parts still waiting to be received then the Order would not be updated to complete.
The join in the NOT EXISTS is likely incorrect as I am not sure how OrdersTable links to PartsTable but it should set you off in the right direction.
UPDATE
    OrdersTable

SET
    OrderComplete = 'TRUE'

FROM
    OrdersTable

WHERE
    NOT EXISTS
    (
        SELECT  *
        FROM    PartsTable
        WHERE   ItemReceived = 'FALSE'
                AND OrdersTable.Id = PartsTable.Id
    )


text:
Q: Swift NSURLConnection doesn't have a member named start  var connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
 connection.start()

ERROR:
NSURLConnection doesn't have a member named start
Any idea ? why start not work here :(

A: As the other posters have noted, since you're passing true as startImmediately, you don't actually need to call start, but that doesn't explain why it isn't found.
var connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)

returns an optional (the request may not be processable by NSURLConnection) so you have to unwrap it, any of:
connection!.start()

connection?.start()

if let connection = connection {
    connection.start()
}
else {
    // handle error case
}

will work for you, in increasing order of preference/safety.

A: This wont work.
Please check documentation: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/instm/NSURLConnection/start
In particular

Calling this method is necessary only if you create a connection with
  the initWithRequest:delegate:startImmediately: method and provide NO
  for the startImmediately parameter. If you don't schedule the
  connection in a run loop or an operation queue before calling this
  method, the connection is scheduled in the current run loop in the
  default mode.

In order to make start work, you have to change startImmediately: true to startImmediately: false


text:
Q: Need to create a chat bubble like Whatsapp with two labels on top of the message in SwiftUI I'm trying to create a chat bubble like this:
Actual Bubble
Actual Bubble 2.0
This is what I have been able to achieve so far.
My attempt
My attempt
This is my code so far:
import SwiftUI

struct TestingView: View {

    var body: some View {
        ZStack {
            /// header
            VStack(alignment: .trailing) {
                HStack {
                    HStack() {
                        Text("abcd")

                    }
                    HStack {
                        Text("~abcd")
                    }
                }.padding([.trailing, .leading], 15)
                    .fixedSize(horizontal: false, vertical: true)

                /// text
                HStack {
                    Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!")

                }.padding([.leading, .trailing], 15)

                /// timestamp
                HStack(alignment: .center) {
                    Text("12:00 PM")
                }.padding(.trailing,15)

            }.background(Color.gray)
                .padding(.leading, 15)
                .frame(maxWidth: 250, alignment: .leading)

        }

    }
}

struct TestingView_Previews: PreviewProvider {
    static var previews: some View {
        TestingView()
    }
}

The main goal is that I want the two labels on top to be distant relative to the size of the message content. I am not able to separate the two labels far apart i.e one should be on the leading edge of the bubble and the other one on the trailing edge.
Already tried spacer, it pushes them to the very edge, we need to apart them relative to the content size of the message as shown in attached images.

A: Here is a simplified code.
Regarding Spacer: To achieve your desired result you put both Text views inside of a HStack, and put a Spacer between them. So the Spacer pushes them apart to the leading and trailing edge.
Also I recommend to only use one padding on the surrounding stack.

        VStack(alignment: .leading) {
            // header
            HStack {
                Text("+123456")
                    .bold()
                Spacer() // Spacer here!
                Text("~abcd")
            }
            .foregroundStyle(.secondary)

            // text
            Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!")
                .padding(.vertical, 5)

            // timestamp
            Text("12:00 PM")
                .frame(maxWidth: .infinity, alignment: .trailing)

        }
        .padding()
        .background(Color.gray.opacity(0.5))
        .cornerRadius(16)
        .frame(maxWidth: 250, alignment: .leading)

    }

A: We can put that header into overlay of main text, so it will be always aligned by size of related view, and then it is safe to add spacer, `cause it do not push label wider than main text.
Tested with Xcode 13.4 / iOS 15.5

var body: some View {
    let padding: CGFloat = 15
    ZStack {
        /// header
        VStack(alignment: .trailing) {
            /// text
            HStack {
                //Text("Hello Everyone")   // short test
                Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!") // long test
            }
            .padding(.top, padding * 2)
            .overlay(
                HStack {            // << here !!
                    HStack() {
                        Text("abcd")

                    }
                    Spacer()
                    HStack {
                        Text("~abcd")
                    }
                }
            , alignment: .top)
            .padding([.trailing, .leading], padding)

            /// timestamp
            HStack(alignment: .center) {
                Text("12:00 PM")
            }.padding(.trailing, padding)

        }.background(Color.gray)
            .padding(.leading, padding)
            .frame(maxWidth: 250, alignment: .leading)
    }
}

A: To separate two components with fairly space in the middle, use HStack{} with Spacer().
This is a sample approach for this case. Code is below the image:

VStack {
  HStack {
    Text("+92 301 8226")
        .foregroundColor(.red)
    Spacer()
    Text("~Usman")
        .foregroundColor(.gray)
  }
  .padding(.bottom, 5)
  .padding(.horizontal, 5)
  Text("Testing testingtesting testing testing testingtesting testing testing testing testing testing testing testing testing testing.")
    .padding(.horizontal, 5)
  HStack {
    Spacer()
    Text("2:57 AM")
        .foregroundColor(.gray)
        .font(.subheadline)
  }
  .padding(.trailing, 5)
}
.frame(width: 300, height: 160)
.background(.white)
.cornerRadius(15)


text:
Q: Tomcat 6.0 starts but ecplise thinks it is not I am using tomcat 6 with Eclipse Kepler Release.
When i start the tomcat, I see below messages:

Aug 03, 2013 11:30:01 AM com.isc.org.apache.coyote.http11.ISCHttp11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-444
Aug 03, 2013 11:30:01 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 20742 ms

This shows that the Tomcat starts but eclipse thinks that the tomcat is not starting yet and keeps showing the starting bar.
When I see the "Progress" window it says:

Starting tomcat 6.0 Server at Localhost

Do you know why Eclipse think tomcat is not starting while it is started and "working".

A: It seems that the Eclipse calls the application url after start up to make sure it is running.
A proxy client (pshione) had changed the system proxy so the eclipse could not call the start page and thinks that the application is not starting yet!!
I removed the proxy and it works fine now!


text:
Q: Python void/null function Python noob so I might be going about this the wrong way
I want to use a try/except block to find if a value in a dict isn't set like
try:
    if entry['VALUE1'] == None: void()
    if entry['VALUE2'] == None: void()
except KeyError:
    print "Values not Found"

Of course the 'void' function doesn't exist, is there anything I can do to get round this so that code will work properly

A: Try replacing void() with pass.
Of course, in practice, you can just do if key in some_dict:. But if you ever need a "do nothing" in a block, pass is what you're looking for.

A: Try:
if "VALUE1" in entry:
    foo()

to determine if the "VALUE1" string is in the set of keys of the entry dict.
Your logic would probably look something like:
if "VALUE1" not in entry or "VALUE2" not in entry:
    print "Values not found"

The try block is completely unnecessary for this test.

A: if entry.has_key('VALUE1'):
 do_something()

or
if 'VALUE1' in entry:
 do_something()

A: I would suggest making a function to help you out:
contains_all_keys = lambda d, keys: reduce(lambda a, b: a and b, map(lambda k: k in d, keys))
di = {'a':'some val', 'b':'some other val'}
if contains_all_keys(di, ['a', 'b']):
    print 'a and b present'
if not contains_all_keys(di, ['a', 'b', 'c']):
    print 'missing keys'

A: If you just want to evoke the exception, through a key lookup, the if is not neccesary.  It's sufficient to just express the lookup on a line by itself, such as:
>>> a = {}
>>> a['value']
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
KeyError: 'value'
>>>


text:
Q: Morse Audio Decoder on MATLAB I was programming a morse audio decoder on Matlab but it didn't work. I have multiple files, but my decoder doesn't work, I also have an encoder which my partner gave me and it works.
I cannot find my mistakes, I cannot even create a struct. Can you please help me?
my cells T is 47*2 is like this:
'A' '01'
'B' '1000'
'C' '1010'
'D' '100'
'E' '0'
function decoded = morse_decode(signal, fs)

C = readtable('morsecode.dat', 'ReadVariableNames', false, ...
'Format', '%s%s', 'Delimiter', 'space');

T = table2cell(C);

for i=1 : length(T)*2
    if isa(T{i}, 'numeric')
        T{i} = num2str(T{i});
    end
end

struc = cell2struct(T(:,1), T(:,2));
clear T

morse2char = @(m) getfield(struc, m);

[b,a] = butter(7,1/20);
signal = filter(b,a,signal);
env = abs(real(hilbert(signal)));
fc=600;
[b,a] = butter(2,1/fc/5);
env=filter(b,a,env);

thresh = mean(env)*0.9;

dur=find(env <= thresh,1) - find(env>thresh,1);
if (dur <0)
    dur = find(env>thresh,1) - find(env<= thresh,1);
    env = env(dur+1:end);
    dur = find(env <= thresh,1) - find(env>thresh,1);
end
env=env(dur+1:end);
dists = [dur,1];
dit = dur;

next = find(env>thresh,1);

while (any(next))
    if(next<dit)
        dit=next;
    end
    dists=[dists; [next,0]];
    env = env(next+1:end);
    next=find(env<thresh,1);
    if (next<dit)
        dit=next;
    end
    dists= [dists; [next,1]];
    env= env(next+1:end);
    next = find(env>thresh,1);
end

letter="";
word="";
for i=1:(rows(dists))
    if(dists(i,2)==i)
        if (dists(i,2)<=dit*1.8)
            letter=[letter "0"];
        else
            letter=[letter "1"];
        end
    else
        if (dists(i,1) > dit * 3.9)
            word = [word; [letter; "break"]];
            letter = "";
        elseif (dists(i,1) > dit*1.5)
            word = [word; (letter)];
            letter = "";
        end
    end
end
word = [word; (letter)];

decoded = morse2char(deblank(word(1,:)));
for i=2:(rows(word))
    if (strcmpi(strtrim(word(i,:)),"break") ==1)
        decoded = [decoded (" ")];
    else
        decoded = [decoded (morse2char(deblank(word(i,:))))];
    end
end

decoded = []; %Replace with actually decoded text

A: In MATLAB you cannot create a struct with a variable names with number but in Octave it works.


text:
Q: Angular: Accessing nested properties in controller I'm new to Angular and I'm having some trouble accessing object properties in my controller. I have an array that I'm able to access in my controller (which was returned from the back-end of my application), and that array contains a single object with properties that I'd like to access. I'm trying to figure out how exactly to access those properties (on the object contained in the array).
I've tried using the angular.forEach() method (although this feels like a hacky approach) but still can't get at the properties nested two levels deep.
Here's how my console represents the array, the object, and its properties:
[Object]   0: Object
    __v: 0
    _id: "55a054808af99da01701ab60"
    hex_color_code: "#B79152"
    name: "camel"
    __proto__: Object
    length: 1   __proto__: Array[0]

Any help here would be greatly appreciated.

A: Afaik you are using mongo database, but didn't expose model population, check your server side controller, generally its exports.list method. Then check mongodb populate function. Or just copy some functionality from exports.[controller_name]ById


text:
Q: How do I code opposite 'levels' or 'factors' in R I have  browsed through many different pages on the net but cannot seem to find an answer to this question:
How do I code up equally-opposing levels for use in multiple regression in R?
The only way I can currently see achieving this is to assign the data type to these columns as 'numeric' however I know that this is not an entirely accurate way of doing this as they should ideally be treated as factors.
Essentially what I am looking for is creating 'dummy' variables that are factors rather than numeric.
By way of example, suppose we have a scenario of sporting teams opposing each other, each row assigns a different game where Team A's presence in the game is suggested by the '1' dummy and Team B's presence is '-1' (and all other team's values are obviously set to 0 because they are not playing in this game).
I have attempted to change the data type of these columns to factors, however this results in three levels of 1,0 and -1 but the beta assigned to 1 and -1 is never equally opposite (and in theory the value assigned to 0 should be zero).
Does anybody know how to correctly mathematically and programatically achieve this? Your help would be much appreciated!


text:
Q: RestSharp и BadRequest Пытаюсь отправить некий POST запрос и все время в ответ получаю Bad Request.
В чем может быть проблема?
Код запроса:
private async void SellItem(string appid, string contextid, string assetid, string amount, string prise)

    {
        await GetJson(Properties.Settings.Default.myProfileURL + "/inventory/json/730/2");
        var client = new RestClient("http://steamcommunity.com")
        {
            UserAgent = @"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0",
            FollowRedirects = true,
            CookieContainer = GenerateCookies(),
            Encoding = Encoding.UTF8
        };

        var request = new RestRequest("/market/sellitem/", Method.POST);
        foreach (var cookie in CookieContainer_ToList(client.CookieContainer))
        {
            if (cookie.Name == "sessionid")
            {
                request.AddParameter("sessionid", cookie.Value, ParameterType.GetOrPost);
            }
        }
        request.AddParameter("appid", appid, ParameterType.GetOrPost);
        request.AddParameter("contextid", contextid, ParameterType.GetOrPost);
        request.AddParameter("assetid", _list.rgInventory[1].id, ParameterType.GetOrPost);
        request.AddParameter("amount", amount, ParameterType.GetOrPost);
        request.AddParameter("price", prise, ParameterType.GetOrPost);
        request.RequestFormat = DataFormat.Json;

        var response = client.ExecuteTaskAsync(request);
        MessageBox.Show(response.Result.StatusCode.ToString()); //Bad Request
    }

Тело запроса:
POST /market/sellitem/ HTTP/1.1
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Content-Type: application/x-www-form-urlencoded
Host: steamcommunity.com
Cookie: sessionid=цензура; steamLogin=цензура; Steam_Language=russian
Content-Length: 95
Accept-Encoding: gzip, deflate

sessionid=цензура&appid=730&contextid=2&assetid=2836967753&amount=1&price=8679

Если надо, то могу предоставить тело запроса "как в браузере".
UPD: Тело запроса "как в браузере":
    Host: steamcommunity.com
    User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
    Accept: */*
    Accept-Language: uk,ru;q=0.8,en-US;q=0.5,en;q=0.3
    Accept-Encoding: gzip, deflate
    Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    Referer: http://steamcommunity.com/id/kribetko/inventory/
    Content-Length: 95

sessionid=цензура&appid=730&contextid=2&assetid=2875087333&amount=1&price=8697

UPD2: Внезапно обнаружил, что для этого POST запроса используется "защищенное соединение" с шифрами TLS_RSA_WITH_AES_128_CBC_SHA, хотя в js скрипте об этом ни слова. Я так полагаю, что в этом главная проблема.

A: Вывовите до вашего кода:
ServicePointManager.Expect100Continue = false;


text:
Q: Problems with unicode in Python I was having some trouble with using unicode in python, so I wrote this program, and I am confused by the results. Whenever I run it, different characters give me error #2, which means that utf32, utf16 and utf8 all gave errors when I tried to write a unicode character to my test file. Never the same ones. Is it a problem with my program, or am I doing somthing python is not designed to handle?
for a in range(65535):
    try:
        open('test_text.txt','w').write(unichr(a).encode("utf32"))
        if len(open('test_text.txt','r').read()) == 0:
            print  unichr(a) + ' Error #1 #' + str(a)
    except IOError:
        try:
            open('test_text.txt','w').write(unichr(a).encode("utf16"))
        except IOError:
            try:
                open('test_text.txt','w').write(unichr(a).encode("utf8"))
            except IOError:
                print unichr(a) + ' Error #2 #' + str(a)
    except UnicodeEncodeError:
        print unichr(a) + ' Error #3 #' + str(a)
raw_input('\n\nEnter char to end:')

A: Your code did not throw any errors when I tried it. Also, you're overriding the file every time through the loop. You could try changing the mode to 'a' instead of 'w' to append to the file. Or you could simply do the following:
f = open('test_text.txt','wb')
for a in range(65535):
    f.write(unichr(a).encode("utf32"))
f.close()

There is more information about reading/writing to files in python here:
http://docs.python.org/2/tutorial/inputoutput.html


text:
Q: 2D array iteration speed in swift (Beta 4) I've been battling with speed issues in Swift, mainly with arrays. Currently running with latest 'beta 4' release. I've broken the code out into playground to try and show the issues
I setup an 2D array, the iterate over it, set each element.
import UIKit

func getCurrentMillitime() -> NSTimeInterval {
    let date: NSDate = NSDate()
    return date.timeIntervalSince1970*1000;
}

let startTime = getCurrentMillitime()

let X = 40
let Y = 50
var distanceGrid = [[CGFloat]](count: X, repeatedValue:[CGFloat](count: Y,repeatedValue:CGFloat(0.0)))
for xi in 0..<X {
    for yi in 0..<Y {
        distanceGrid[xi][yi] = 1.1
       //println("x:\(xi) y:\(yi) d:\(distanceGrid[xi][yi])")
    }
}

let endTime = getCurrentMillitime()
let computationTime = endTime - startTime
println("Time to compute \(computationTime) ms")

Run the above code and you'll get :
Time to compute 2370.203125 ms

Which sure can't be right !.. Am I being a numpty ?

A: Two things to consider about Swift performance:

*

*It's very much up in the air during the beta.

*Many of Swift's performance tricks depend on the optimizer. Especially when generics are involved (every array is a generic Array<T>), Swift uses a more expressive / debugger-friendly implementation at -O0, but optimizes it away to a higher-performance implementation at -O or -Ofast. (Note that -Ofast also takes away bounds checks and other safety features, so it's not a great idea for production builds.)
Also, note your current example is measuring both the time to create a 2D array with init(count:repeatedValue: and the time to iterate it. If you're out to measure only the latter, you should set your startTime after creating the arrays.

A: In the language guide under "subscripts", you'll find a 2D (struct) implementation of a 2D array. But it is rather slow in assigning values if you go above a 1000 elements.
Creating a local 2D array and setting it into the struct for easy acces is much faster.
It's also faster to create an array with repeated values and overwrite them than to append values to an array.
For about 100k values it takes ~9seconds with the struct, 1.5 seconds with the append and 0.6 seconds with overwriting repeated values.
I kinda like the struct idea, but it is so slow.
I sure hope it's a beta issue.

A: It's obvious that the Swift beta is struggling with arrays.
Even with a one-dimensional array, compared to objective-c the difference is huge.
I've mixed a objC class into a swift program and had both languages create and alter an array of 1,000,000 elements. This is what I got on some MacBook:
Elapsed time by Swift method: 2.7078 sec
Elapsed time by objective-c method: 0.033815 seconds
Code:  ( var nrOfElements = 1000000 )
  // Swift
    let startTime = NSDate();
    var stringList = Array<String>(count: nrOfElements, repeatedValue:String())
    for i in 0..<nrOfElements {
      stringList[i] = "Some string";
    }
    let endTime = NSDate();
    println("Elapsed time by Swift method: " +
      NSString(format:"%.4f", endTime.timeIntervalSinceDate(startTime)) + " sec");

   // Objective-c
      NSDate *startTime = [NSDate date];
      NSMutableArray *stringList = [NSMutableArray arrayWithCapacity:10];
      for (int i = 0; i < nrOfElements; i++) {
        [stringList addObject:@"Some string"];
      }
      NSDate *endTime = [NSDate date];
      printf("%s\n", [[NSString stringWithFormat:@"Elapsed time by objective-c method: %f seconds", [endTime timeIntervalSinceDate:startTime]] UTF8String]);

*

*I found no difference between Beta-3 and Beta-4, so improving
array-handling isn't high on the priority list.

*Processing increasingly larger arrays, give proportional higher process times.

*Handling multi-dimensional arrays is even more costly when increasing the number of higher dimension elements

*Pre-creation of the array in Swift is indeed faster than 'append'

Let's hope that things adequately will be repaired in the final version.

A: I agree with you that even a beta version cannot behave like software of the eighties on hardware of the seventies. So I did some more digging into the Swift array-handling capabilities and I stumbled upon astonishing results. We learned already that the Swift array performance is poor when compared to objective-c or other languages as c++, c#, java, etc.
In my previous tests I measured the time to create and fill a local scope array of one million elements. As we saw, objective-c did this about 80 times faster. Worse it gets when we compare arrays declared in global class scope. Then objC appears to be about 500 times faster!
But hey, when we finally have filled up this global declared array with useful data, we can smoothly work with it right? Wrong!
I've printed 10 elements of the large array and the nightmare deepened. The 10 elements of a local scope array took 0,0004 seconds, as may be expected. But printing the same elements of our global declared array took… 1 minute and 11 seconds. This seems too bad to be true and I'm sure the Swift developers are on it as we speak.


text:
Q: issue_comment is running in the background but I want to run it on the pull request page I want to listen to an edited comment and the GitHub actions to choose block merge or available merge.
So it is working on the actions tab but isn't seen on the pull request screen.
How can I add GitHub action when comments to edited in the pull request screen?
Thank You
name: xx
run-name: xx
on: [issue_comment]
jobs:
  xx:
  ...

Now:

Expected:


text:
Q: Accommodating variable filename for python script I have to read multiple filenames which i will be treating as input for my python script. But the input files may have variable name depending upon the time it got generated.
File1: RM_Sales_Japan_2011201920191124194200.xlsx
File2: RM_Volume_Australia_201120192019154321194200.xlsx

How to accommodate these changes while reading a file instead of exactly specifying the filename every time we run the script?
Things i tried:
I have used below method in my previous scripts because it had only one file with known extension:
xlsxfile = "*.xlsx"
filelocation = "/user/script/" + xlsxfile

But with multiple files with similar extension i am not sure how to get the definition done.
EDIT1:
I was trying to get more clarity on using glob with read_excel. Please see my example code below:
import os
import glob
import pandas as pd
os.chdir ('D:\\Users\\RMoharir\\Downloads\\Smart Spend\\Input')

fls=glob.glob("Medical*.*")

df1 = pd.read_excel(fls, parse_cols = 'A:H', skiprows = 10, header = None)

But this gives me an error:
ValueError: Invalid file path or buffer object type: <class 'list'>

Any help is appreciated.

A: If you simply need to find all the files that match a given pattern in a directory, os and re modules have you covered.
import os
import re

files = os.listdir()

for file in files:
    if re.match(r".*\.xlsx$", file):
        print(file)

This short program will print out every file in the current directory whose name ends with .xslx.  If you need to match a more complicated pattern, you may need to read up on Regular Expressions
Note that os.listdir takes an optional string argument of what path to look in, if not given it will look in the directory the program was ran from


text:
Q: Enable "preserve log" with chromedriver Looking to enable "Preserve log" with chromedriver.
https://sites.google.com/a/chromium.org/chromedriver/capabilities loggingPrefs points to google code archive page and is not very helpful.
My overall goal is to parse logs during test execution looking for errors, but logs get cleared on page navigation which may happen multiple times during test.
I can think of couple non-ideal workarounds:

*

*parse log on every page navigation

*log to file and parse log later

Both are not ideal, so looking for the easiest way.
This question is similar to Enable "Preserve log" in chrome programmatically using chromedriver - but over there the answer seems to be around logging redirects via performance logging, not preserving log on navigation.

A: To enable the "Preserve log" feature with chromedriver, you can use the loggingPrefs capability in your chromedriver options. This capability allows you to specify which types of log messages to capture, and where to send them.
I'll give an example of how to enable the "Preserve log" feature in Python:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--enable-logging')
options.add_argument('--v=1')
capabilities = {'loggingPrefs': {'browser': 'ALL'}}

driver = webdriver.Chrome(options=options, desired_capabilities=capabilities)

In this example, we're creating a new ChromeOptions object, and adding two arguments: --enable-logging and --v=1. These arguments enable verbose logging in the Chrome browser, which is necessary to capture all log messages.
We're also creating a loggingPrefs capability object, with the browser key set to 'ALL'. This tells chromedriver to capture all log messages, including network requests and JavaScript console messages.
Finally, we're passing both the options and capabilities objects to the webdriver.Chrome() constructor, which creates a new ChromeDriver instance with the desired options.
Note that even with the "Preserve log" feature enabled, the log messages will still be cleared when the page is navigated. However, you can use the driver.get_log('browser') method to retrieve all captured log messages at any time during your test.

A: //chromedriver,preserve log
// request postdata
ChromeOptions chromeOptions = new ChromeOptions();
//HAR
ArrayList<String> excludeSwitches = new ArrayList<>();
excludeSwitches.add("enable-automation");
chromeOptions.setExperimentalOption("excludeSwitches",excludeSwitches);
List<HarEntry> list =  har.getLog().getEntries();
for (HarEntry harEntry : list){
  HarRequest request = harEntry.getRequest();
  if(request != null){
    String requestBody = request.getPostData().getText();
    System.out.println("requestBody:" + requestBody);
  }
}


text:
Q: Query DynamoDB based on GSI In my DynamoDB table, There is HashKey = ID and  GSI  = Type.
I need to fetch all hashKeys (IDs) for particular type (GSI).
What is the efficient way to fetch all IDs for given type in this case.
My DynamoDB table won't be large.

A: Query the index for that type.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Querying
If you want to have only distinct values then you have to group them on client's side: Distinct attribute value from Global Secondary Index in DynamoDB

A: You could just query the GSI for the 'type' you're interested in and retrieve the IDs your interested in since all key field from the table are automatically projected into the GSI


text:
Q: Typed.js t.el is null I'm trying to use type.js but I'm getting an error saying TypeError: t.el is null.
Even after following guides on Google or videos on YouTube and doing it the exact same way, the error is still there..
This is the html's head:

The html's body:

And the JavaScript code:
var typed = new Typed(".typed", {
  strings: [
  'Some strings with',
  'Some HTML',
  'Chars × ©'
  ],
});


text:
Q: Loop changes category on first instance only I have 100s of emails to check for a string. If the string appears in the email, categorize as "Ticketed" else "NOTTICKETED".
The code is working for the first email and not for the rest of the emails.
Sub Find_String()
    Dim olApp As Outlook.Application
    Dim olExp As Outlook.Explorer
    Dim olFolder As Outlook.MAPIFolder
    Dim obj As Object
    Dim i As Long
    Dim x As Long
    Dim count As Long
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")

    Set olApp = Outlook.Application
    Set olExp = olApp.ActiveExplorer
    Dim olMatches As Object
    Set olFolder = olExp.CurrentFolder

    'Set count of email objects
    count = olFolder.Items.count

    'counter for emails
    x = 1

    regEx.Pattern = "(Consumer Number:.*\d{5})"
    regEx.IgnoreCase = True
    regEx.MultiLine = True
    regEx.Global = True
    Set olMatches = regEx.Execute(stremBody)

    For Each obj In olFolder.Items

        If regEx.test(obj.Body) Then
            obj.Categories = "TICKETED"
        Else
            obj.Categories = "NO TICKET"
        End If
        x = x + 1

    Next obj

    MsgBox ("All Emails checked")
ExitProc:
    Set emItm = Nothing
    Set olFolder = Nothing
    Set olNS = Nothing
    Set olApp = Nothing
End Sub

A: You need to save the message after setting the category:
If regEx.test(obj.Body) Then
    obj.Categories = "TICKETED"
Else
    obj.Categories = "NO TICKET"
End If
obj.Save


text:
Q: How to select same value fields in mysql? I have a table with the follwoing fields name, address, city, zip, etc.
How do you select the city column with same value?

A: If you're looking for all entries in New York assuming your table name is called locations
SELECT name, address, zip, city FROM locations WHERE city LIKE "New York"

If you want all the entries to be ordered by city so that they are clustered together:
SELECT name, address, zip, city FROM locations ORDER BY city DESC

If you want to collect a list of names from each city:
SELECT GROUP_CONCAT(name) FROM locations GROUP BY city;

A: It is not really clear what you want.
If you want a list of the cities that appear more than once you can use:
select city, count(city) Total
from yourtable
group by city
having count(city) > 1

If you want to return data based on the city name, you will use:
select *
from yourtable
where city = 'yourCity'

A: select city from table_name group by city having count(city) > 1;


text:
Q: os.chdir returns directory with double slashes I've searched and found solutions to this problem when the os.chdir() contains an actual path in quotes, but I'm trying to use a variable.
scriptpath = os.path.realpath(__file__)
codeScriptPath = os.chdir(scriptpath)

The error message received looks a little something like:
"F:\\path\\path\\path\\path\\main.py"

Not sure how to fix the error and can't find anything hoping I can get some help.
Thanks.

A: The error doesn't have to do with double slashes (that's how python escapes backslash in a string).  Your error has to do with trying to change directory to a path that points to a file.  You probably want something like the below instead:
scriptpath = os.path.realpath(__file__)
d = os.path.dirname(scriptpath)
os.chdir(d)

The call to os.path.dirname will return the path of the directory that contains scriptpath.


text:
Q: Decoding several text files from Byte to UTF-8 I'm currently trying to loop over roughly 9000 .txt files in python to extract data and add them to a joined pandas data frame. The .txt data is stored in bytes, so in order to access it I was told to use a decoder. Because I'm interested in preserving special characters, I would like to use the UTF-8 decoder, but I'm getting the following error when trying to do so:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte

For some reason, the code works just fine when using a 'ISO-8859-1' decoder, but this obviously messes up all special characters. Does anyone know how to fix this? I'm pasting my code below! Also, the decoding works for the first ~1600 .txt files in my dataset, but for the rest it doesn't.
decode_counter = 0
for index, i in enumerate(corpus[0]):
    decode_counter += 1
    corpus.iloc[index][0] = i.decode('UTF-8')

The corpus variable contains the name of the .txt file as an index, and the contents of the individual .txt files in a column named 0. Thank you very much!

A: Maybe you could try every codec available in your environment and check which result fits best.
Here is a way of doing that:
import os, codecs, encodings
from collections import OrderedDict
from typing import Union
from cprinter import TC
from input_timeout import InputTimeout

class CodecChecker:
    def __init__(self):
        self.encodingdict = self.get_codecs()
        self.results = OrderedDict()

    def get_codecs(self):
        dir = encodings.__path__[0]
        codec_names = OrderedDict()
        for filename in os.listdir(dir):
            if not filename.endswith(".py"):
                continue
            name = filename[:-3]
            try:
                codec_names[name] = OrderedDict({"object": codecs.lookup(name)})
            except Exception as Fehler:
                pass
        return codec_names

    def try_open_file(self, path: str, readlines: int = 0):
        self.results = OrderedDict()
        results = OrderedDict()
        if readlines == 0:
            for key, item in self.encodingdict.items():
                results[key] = {"strict_encoded": [], "strict_bad": True}

                try:
                    with open(path, encoding=key) as f:
                        data = f.read()
                        results[key]["strict_encoded"].append(data)
                        results[key]["strict_bad"] = False
                except Exception as fe:
                    results[key]["strict_encoded"].append(str(fe))
                    continue
        else:
            for key, item in self.encodingdict.items():
                results[key] = {"strict_encoded": [], "strict_bad": True}

                try:
                    with open(path, encoding=key) as f:
                        for ini, line in enumerate(f.readlines()):
                            if ini == readlines:
                                break
                            results[key]["strict_encoded"].append(line[:-1])
                        results[key]["strict_bad"] = False
                except Exception as fe:
                    results[key]["strict_encoded"].append(str(fe))
                    continue
        self.results = results.copy()
        return self

    def try_convert_bytes(self, variable: bytes):
        self.results = OrderedDict()

        results = OrderedDict()
        modes = ["strict", "ignore", "replace"]
        for key, item in self.encodingdict.items():
            results[key] = {
                "strict_encoded": [],
                "strict_bad": True,
                "ignore_encoded": [],
                "ignore_bad": True,
                "replace_encoded": [],
                "replace_bad": True,
            }
            for mo in modes:
                try:
                    results[key][f"{mo}_encoded"].append(
                        item["object"].decode(variable, mo)
                    )
                    results[key][f"{mo}_bad"] = False
                except Exception as Fe:
                    results[key][f"{mo}_encoded"].append(str(Fe))
        self.results = results.copy()

        return self

    def print_results(
        self, pause_after_interval: Union[int, float] = 0, items_per_interval: int = 0
    ):
        counter = 0
        for key, item in self.results.items():
            if pause_after_interval != 0 and items_per_interval != 0:
                if items_per_interval == counter and counter > 0:
                    i = InputTimeout(
                        timeout=pause_after_interval,
                        input_message=f"Press any key to continue or wait {pause_after_interval} seconds",
                        timeout_message="",
                        defaultvalue="",
                        cancelbutton=None,
                        show_special_characters_warning=None,
                    ).finalvalue
                    counter = 0
            print(
                f'\n\n\n{"Codec".ljust(20)}: {str(TC(key).bg_cyan.fg_black)}'.ljust(100)
            )
            if "strict_bad" in item and "strict_encoded" in item:
                print(f'{"Mode".ljust(20)}: {TC("strict").fg_yellow.bg_black}')

                if item["strict_bad"] is False:
                    if isinstance(item["strict_encoded"][0], tuple):
                        if item["strict_bad"] is False:

                            try:
                                print(
                                    f"""{'Length'.ljust(20)}: {TC(f'''{item['strict_encoded'][0][1]}''').fg_purple.bg_black}\n{'Converted'.ljust(20)}: {TC(f'''{item['strict_encoded'][0][0]}''').fg_green.bg_black}"""
                                )
                            except Exception:
                                print(
                                    f"""Problems during printing! Raw string: {item['strict_encoded'][0][0]!r}"""
                                )

                        if item["strict_bad"] is True:
                            try:
                                print(
                                    f"""{'Length'.ljust(20)}: {TC(f'''{"None"}''').fg_red.bg_black}\n{'Converted'.ljust(20)}: {TC(f'''{item['strict_encoded'][0]}''').fg_red.bg_black}"""
                                )
                            except Exception:
                                print(
                                    f"""Problems during printing! Raw string: {item['strict_encoded'][0][0]!r}"""
                                )
                    if isinstance(item["strict_encoded"][0], str):
                        if item["strict_bad"] is False:
                            itemlen = len("".join(item["strict_encoded"]))
                            concatitem = "\n" + "\n".join(
                                [
                                    f"""Line: {str(y).ljust(14)} {str(f'''{x}''')}"""
                                    for y, x in enumerate(item["strict_encoded"])
                                ]
                            )
                            try:
                                print(
                                    f"""{'Length'.ljust(20)}: {TC(f'''{itemlen}''').fg_purple.bg_black}\n{'Converted'.ljust(20)}: {concatitem}"""
                                )
                            except Exception:
                                print(
                                    f"""Problems during printing! Raw string: {concatitem!r}"""
                                )

                        if item["strict_bad"] is True:
                            concatitem = TC(
                                " ".join(item["strict_encoded"])
                            ).fg_red.bg_black
                            try:
                                print(
                                    f"""{'Length'.ljust(20)}: {TC(f'''{"None"}''').fg_red.bg_black}\n{'Converted'.ljust(20)}: {concatitem}"""
                                )
                            except Exception:
                                print(
                                    f"""Problems during printing! Raw string: {concatitem!r}"""
                                )
                print("")
            if "ignore_bad" in item and "ignore_encoded" in item:
                print(f'{"Mode".ljust(20)}: {TC("ignore").fg_yellow.bg_black}')

                if item["ignore_bad"] is False:
                    if isinstance(item["ignore_encoded"][0], tuple):

                        if item["ignore_bad"] is False:

                            try:
                                print(
                                    f"""{'Length'.ljust(20)}: {TC(f'''{item['ignore_encoded'][0][1]}''').bg_black.fg_lightgrey}\n{'Converted'.ljust(20)}: {TC(f'''{item['ignore_encoded'][0][0]}''').bg_black.fg_lightgrey}"""
                                )
                            except Exception:
                                print(
                                    f"""Problems during printing! Raw string: {item['ignore_encoded'][0][0]!r}"""
                                )

                print("")

            if "replace_bad" in item and "replace_encoded" in item:
                print(f'{"Mode".ljust(20)}: {TC("replace").fg_yellow.bg_black}')

                if item["replace_bad"] is False:
                    if isinstance(item["replace_encoded"][0], tuple):

                        if item["replace_bad"] is False:
                            try:
                                print(
                                    f"""{'Length'.ljust(20)}: {TC(f'''{item['replace_encoded'][0][1]}''').bg_black.fg_lightgrey}\n{'Converted'.ljust(20)}: {TC(f'''{item['replace_encoded'][0][0]}''').bg_black.fg_lightgrey}"""
                                )
                            except Exception:
                                print(
                                    f"""Problems during printing! Raw string: {item['replace_encoded'][0][0]!r}"""
                                )

            counter = counter + 1

        return self

if __name__ == "__main__":
    teststuff = b"""This is a test!
    Hi there!
    A little test! """
    testfilename = "test_utf8.tmp"
    with open("test_utf8.tmp", mode="w", encoding="utf-8-sig") as f:
        f.write(teststuff.decode("utf-8-sig"))
    codechecker = CodecChecker()
    codechecker.try_open_file(testfilename, readlines=2).print_results(
        pause_after_interval=1, items_per_interval=10
    )
    codechecker.try_open_file(testfilename).print_results()
    codechecker.try_convert_bytes(teststuff.decode("cp850").encode()).print_results(
        pause_after_interval=1, items_per_interval=10
    )

Or you simply run a script to replace all messed up characters. Since I am a German teacher, I have this problem frequently (encoding problems due to Umlaut). Here is a script to replace all characters (too big to post the script here): https://github.com/hansalemaos/LatinFixer/blob/main/__init__.py


text:
Q: What is the best way to get integer's negative sign and store it as char? How to get an integer's sign and store it in a char? One way is:
int n = -5
char c;
if(n<0)
    c = '-';
else
    c = '+';

Or:
char c = n < 0 ? '-' : '+';

But is there a way to do it without conditionals?

A: This creates branchless code with gcc/clang on x86-64:
void storeneg(int X, char *C)
{
    *C='+';
    *C += (X<0)*('-'-'+');
}

https://gcc.godbolt.org/z/yua1go

A: There's the most efficient and portable way, but it doesn't win any beauty awards.
We can assume that the MSB of a signed integer is always set if it is negative. This is a 100% portable assumption even when taking exotic signedness formats in account (one's complement, signed magnitude). Therefore the fastest way is to simply mask out the MSB from the integer.
The MSB of any integer is found at location CHAR_BIT * sizeof(n) - 1;. On a typical 32 bit mainstream system, this would for example be 8 * 4 - 1 = 31.
So we can write a function like this:
_Bool is_signed (int n)
{
  const unsigned int sign_bit_n = CHAR_BIT * sizeof(n) - 1;
  return (_Bool) ((unsigned int)n >> sign_bit_n);
}

On x86-64 gcc 9.1 (-O3), this results in very efficient code:
is_signed:
        mov     eax, edi
        shr     eax, 31
        ret

The advantage of this method is also that, unlike code such as x < 0, it won't risk getting translated into "branch if negative" instructions when ported.
Complete example:
#include <limits.h>
#include <stdio.h>

_Bool is_signed (int n)
{
  const unsigned int sign_bit_n = CHAR_BIT * sizeof(n) - 1;
  return (_Bool) ((unsigned int)n >> sign_bit_n);
}

int main (void)
{
  int n = -1;

  const char SIGNS[] = {' ', '-'};
  char sign = SIGNS[is_signed(n)];
  putchar(sign);
}

Disassembly (x86-64 gcc 9.1 (-O3)):
is_signed:
        mov     eax, edi
        shr     eax, 31
        ret
main:
        sub     rsp, 8
        mov     rsi, QWORD PTR stdout[rip]
        mov     edi, 45
        call    _IO_putc
        xor     eax, eax
        add     rsp, 8
        ret

A: char c = 43 + signbit(n) * 2 ;

*

*char 43 is '+'

*char 45 is '-'

*signbit(NEGATIVE INTEGER) is true, converted to 1
int signbit(int) is included in cmath in C++ and math.h in C


text:
Q: SQLite Android Update statement not changing the new column value sQLdB = openDb(sQLdB);
    sQLdB.rawQuery("UPDATE item_support_table SET groupname ='NANO' WHERE groupcode = 5",null );

    closedb(sQLdB);

The update query is not working no errors are thrown.The row with groupcode = '5' /groupcode = 5 is not updated with new value NANO whose columnName  groupname with new name NANO . Insert ,Select, delete all working fine Why is it happening is there any mistake
rowid  groupcode      groupname
1         1            vegetables
2         2            grocery
5         5            Biscuits

A: Use execSQL() and not rawQuery() for queries that don't return data.
rawQuery() just compiles the SQL but does not execute it until one of the moveTo..() methods is called on the returned Cursor. execSQL() both compiles and runs the SQL.

A: You should use rawQuery() when you execute a SELECT statement that returns rows from the table.
If you want to update a row the recommended way to do it is with the method update() with ContenetValues and ? placeholders for the parameters of the WHERE clause:
ContentValues c = new ContentValues();
c.put("groupname", "NANO");
sQLdB.update("item_support_table", c, "groupcode = ?", new String[] {"5"});


text:
Q: Issue to get animsition plugin working I'm trying to get the animsition to work on my web page for smooth page transition, unfortunately it does not work at all (nothing happens)
Both the CSS and the JS of the plugin are loaded. Same for query. The error console does not return any error.
Any idea what the issue is?
Thanks,
HTML

Who are we?

Sub 1

Sub 2

Services Services Services

Products Products Products

JS
$(document).ready(function() {
  $(".animsition").animsition({
    inClass: 'fade-in',
    outClass: 'fade-out',
    inDuration: 1500,
    outDuration: 800,
    linkElement: '.animsition-link',
    // e.g. linkElement: 'a:not([target="_blank"]):not([href^=#])'
    loading: true,
    loadingParentElement: 'body', //animsition wrapper element
    loadingClass: 'animsition-loading',
    loadingInner: '', // e.g ''
    timeout: false,
    timeoutCountdown: 5000,
    onLoadEvent: true,
    browser: [ 'animation-duration', '-webkit-animation-duration'],
    // "browser" option allows you to disable the "animsition" in case the css property in the array is not supported by your browser.
    // The default setting is to disable the "animsition" in a browser that does not support "animation-duration".
    overlay : false,
    overlayClass : 'animsition-overlay-slide',
    overlayParentElement : 'body',
    transition: function(url){ window.location.href = url; }
  });
});

A: Your selector $(".animsition") is looking for an element with a class of animsition but non exists in your document.
Look at your console output:

Animsition: Element does not exist on page.


text:
Q: Skipping n initial years when calculating nonproprotional hazards using greg package I'm using the package Greg to calculate nonproportional hazards. My dataset contains only subjects 65+ years old so I want to skip the first 65 years.
Here are the codes that I used:
apoe_s_f_ts <- timeSplitter(apoe_s_f_s,
                            by = 5,
                            time_var = "duration21yrs",
                            event_var = "censor21yrs",
                            time_offset = 65)

However, the codes above give the following error:

Error in subset.data.frame(apoe_s_f, parse(text =
  paste("duration21yrs",  :    'subset' must be logical

The range of the variable duration21yrs is 66.2-106.8.
Can anyone please explain to me what mistakes did I make?
Thank you!


text:
Q: Too many select lists polluting my controller actions I have an ASP.Net MVC application and some of the controller actions have about 10 select lists (others have more).  Currently my code looks like this:
public ActionResult Edit(int carId)
{
    CreateCar model = new CreateCar();

    model.Makes = Helper.Makes();
    model.Models = Helper.Models();
    model.Colors = Helper.Colors();
    model.EngineSizes = Helper.EngineSizes();
    model.Materials = Helper.Materials();
    model.FuelTypes = Helper.FuelTypes();
    model.WheelSizes = Helper.WheelSizes();
    model.BodyTypes = Helper.BodyTypes();
    //more select lists below this

    return View(model)
}

In my views i setup select lists like this:
@Html.DropDownListFor(x => x, Model.Makes)

I have code that looks like this in a number of actions and i feel there is a better way of doing this so my actions are not polluted with these select lists.
The only option i can think of to get around this is to actullly call the Helper class in the views e.g.
@Html.DropDownListFor(x => x, Helper.Makes())

Is this approach considered bad practice and are there any other approaches to deal wi this issue?

A: Generally, yes, it's bad practice to do things like that in your view. The controller is responsible for wiring everything up, so your code should go there. Now, it depends a lot on what your Helper class is doing. If the select lists are just generated via some bit of code, it's probably not that bad for that to happen in the view, but what you don't want to be doing is issuing database queries while the view is being rendered. If your helper is interacting with a database, then keep it in the controller.
That said, what is the real issue here? Sure that's a lot of select lists, but I wouldn't go so far as to say it's "polluting" your action. It's very clear what your doing. The action is responsible for creating the model for your view, and that's what it's doing. Just because there may be a lot of lines in your code, doesn't necessarily mean it's "bad" or "wrong".
However, if you're repeating this in a lot of places, I would recommend factoring it out into a private or protected method on your controller. For example:
public ActionResult Edit(int carId)
{
    ...

    PopulateSelectLists(model);
    return View(model);
}

[HttpPost]
public ActionResult Edit(Foo model, int carId)
{
    ...

    PopulateSelectLists(model);
    return View(model);
}

private void PopulateSelectLists(Foo model)
{
    model.Makes = Helper.Makes();
    model.Models = Helper.Models();
    model.Colors = Helper.Colors();
    model.EngineSizes = Helper.EngineSizes();
    model.Materials = Helper.Materials();
    model.FuelTypes = Helper.FuelTypes();
    model.WheelSizes = Helper.WheelSizes();
    model.BodyTypes = Helper.BodyTypes();
    //more select lists below this
}

Then, everything is clean and tidy.


text:
Q: RequiredMessage don't show in p:messages I'm trying to display a requiredMessage in p:messages but dont works. The p:messages just show the messages from BackingBean using addMessage().
See:

<h:form id="frmRegistro">

                    <h:inputText value="#{usuarioLogadoMB.newUser.nomeCompleto}"
                        styleClass="form-control" alt="Nome Completo"
                        pt:placeholder="Nome completo" />

                    <h:inputText value="#{usuarioLogadoMB.newUser.email}" id="iptEmail"
                        required="true" requiredMessage="O email é obrigatório"
                        styleClass="form-control" alt="Email" pt:placeholder="Email" />

                    <h:inputSecret value="#{usuarioLogadoMB.newUser.senha}"
                        required="true" requiredMessage="A senha é obrigatória"
                        styleClass="form-control" alt="Senha" pt:placeholder="Senha" />

                    <h:inputSecret value="#{usuarioLogadoMB.newUser.confirmacaoSenha}"
                        required="true"
                        requiredMessage="A confirmação da senha é obrigatória"
                        styleClass="form-control" alt="Repita a senha"
                        pt:placeholder="Repita a senha" />

                        <h:commandButton action="#{usuarioLogadoMB.concluirRegistro()}"
                            value="Registrar" styleClass="btn btn-primary btn-block btn-flat" />

            </h:form>

If i put p:message with for attribute to each component the message is showed inline, but i want to use the p:messages to avoid add p:message to each component.


text:
Q: Chrome console has to click to see variable? Chrome would usually display all my console.log fine no problem.
All of sudden anything in an object or array looks like this:
error:(...)

Then i have to click (...) to see the value.
Current setup:
Angular 4 via webclipse angular 4 ide (running in ide server)
What do i have to do to see the variable-data with clicking on it (how it used to be)


text:
Q: What genre are games like Arcanists, Worm, Warlings? I'm looking for more games like the ones mentioned above.
Especially one like Jagex's Arcanists where not everyone has the same spells/weapons.
To be clear, I'm not asking for recommendations. I just need the genre so I have something to search for.

A: The genre of games you are looking for are very widely known as Artillery Games.
These types of games are called artillery games due to the nature of the game where the players have to calculate shots over potentially very long distances and readjusting your aim based on previous shots, much like artillery do in real life to make shots.


text:
Q: ObservableList ReadOny Datagrid I have created the following extension of the observable list to mimic a readonly behaviour.
public class WeirdList<T> : ObservableCollection<T>
{

    public new void Add(T item)
    {
        throw new NotImplementedException("Add function not implemented.");
    }

    public new void Insert(int index, T item)
    {
        throw new NotImplementedException("Insert() not implemented.");
    }

}

However, if I bind this to a datagrid that has CanUserAddRows=true then when I add a row on the datagrid via the GUI, then no exception is throw yet I can see the object has been added to the collection despite having overridden the obvious methods that allow adding.
If i try to add in code, as expect the exception is thrown.
Any help?
Regards

A: You haven't overriden the functions, just redefined them. You need to use override not new. The grid probably casts the datasource to an ICollection which means your functions wont be called. They will only be used if the object is exactly your type.
As mentioned in the comments Add and Insert are not virtual, override function InsertItem instead. (Add and insert both call this function internally)

A: You've declared your add method like this:
public new void Add
You're shadowing the base class's version.  The DataGrid is likely using the base class's Add method.
If you're declaring the list that your grid will bing to as
ObservableCollection<T> Src = new WeirdList...
Then change it to
WeirdList<T> Src = new WeirdList...
Since the Add method in ObservableCollection<T> is not declared as virtual, and therefore cannot be overridden.
If that doesn't work, then that will mean that the grid is casting your collection, thereby obviating all your hard work, rendering what you want to do impossible.


text:
Q: Trying to read tiff file using jai_imageio I'm having some issue trying to create a subimage through a doGet method. I'm using  jai_imageio, the same method "getInvoiceNumberTif()" works fine when using the main method.But when I try to call the method from servlet I get an exception.
Heres the GET:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    out.println("");
    out.println("");
    out.println("
Hello Servlet Get
");
    out.println("");
    out.println("");

    FileHandler fh = new FileHandler();
    fh.getInvoiceNumberTif();

}

Here is the method:
public void getInvoiceNumberTif() throws IOException{

    File file = new File("C:\\Users\\gideon\\Desktop\\tmp\\invoice.tif");

    BufferedImage img = ImageIO.read(file);
    BufferedImage subImage = img.getSubimage(1600, 355, 220, 50);

    OutputStream out = new FileOutputStream(new File("C:\\Users\\gideon\\Desktop\\tmp\\img_invoice_nr.tif"));

    ImageIO.write(subImage, "tif", out);
    out.flush();
    out.close();
}

the exception:
java.lang.NullPointerException
at se.visma.servlet.FileHandler.getInvoiceNumberTif(FileHandler.java:145)
at se.visma.servlet.InvoiceServlet.doGet(InvoiceServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)


text:
Q: Flashlight non responsive I have found that the flashlight is not readily accessible to the camera app or any other app for that matter on the project tango tablet. Can someone please point me to the source file for the flashlight. A java api reference would be greatly appreciated.

A: flash light is disabled on tango devices. The flash light's software route is actually used by the IR projector.


text:
Q: Python Pandas extract value from dataframe based on minimum index I've got a df:
import pandas as pd
import numpy as np

df = pd.DataFrame({"price":[1.1,66.3,11,15.2,1.1],
                   "qty":[14,2,1,10,1],
                   "c_h":['cheese','ham','ham','cheese','ham'],
                   "qual":['good','good','bad','good','bad']})

The df looks like this when printed:
      c_h   price  qty  qual
0  cheese     1.1   14  good
1     ham    66.3    2  good
2     ham    11.0    1   bad
3  cheese    15.2   10  good
4     ham     1.1    1   bad

I'm trying to return a price of 'c_h'=='ham' and 'qual=='bad' on the minimum index value from a the df.  The minimum index is the lowest numerical value for index currently [0,1,2,...]in which that criteria is met
In this example, the minimum index sought would be 2 and the returned price would be 11.0.
Note: I'm working mostly with pandas but I could also use numpy.
I thought it'd be something like
df[df['c_h']=='ham' and 'qual'=='bad'].min()[index]

but that's not working.

A: You want something like this:
>>> df[(df.c_h == 'ham') & (df.qual == 'bad')].index.min()
2

But if you don't just want the index, you can use the indexers:
>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].iloc[0]
11.0
>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].iloc[[0]]
2    11.0
Name: price, dtype: float64

Note, the above takes the first index, not the lowest index. If you index is a normal, int-range index, then these will be equivalent.
However, if it isn't:
>>> df.index = [3,1,2,4,0]
>>> df
      c_h  price  qty  qual
3  cheese    1.1   14  good
1     ham   66.3    2  good
2     ham   11.0    1   bad
4  cheese   15.2   10  good
0     ham    1.1    1   bad
>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price']
2    11.0
0     1.1
Name: price, dtype: float64

Then get the first the same way:
>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].iloc[[0]]
2    11.0
Name: price, dtype: float64

But the lowest would require something to the effect of:
>>> df.loc[(df.c_h == 'ham') & (df.qual == 'bad'), 'price'].sort_index().iloc[[0]]
0    1.1
Name: price, dtype: float64

A: You coule use the 'pandas.DataFrame.query()' method :
df.query("col1 == value1 and col2==value2").sort_index()["target_column"].iloc[0]